PluginProbe
Elementor Website Builder – more than just a page builder / 4.1.0-beta2
Elementor Website Builder – more than just a page builder v4.1.0-beta2
4.3.0-beta3 4.3.0-beta2 4.3.0-beta1 4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.5 4.2.0-beta2 4.2.0-dev2 4.2.0-beta1 4.1.4 4.1.3 4.1.2 4.1.1 4.1.0 4.1.0-beta3 4.1.0-dev3 4.0.9 4.1.0-beta2 4.1.0-dev2 4.0.8 4.1.0-beta1 4.1.0-dev1 All 452 releases
elementor / assets / js / common.js

common.js in Elementor Website Builder – more than just a page builder 4.1.0-beta2, at assets/js/common.js

33,789 lines 1.3 MB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ "../assets/dev/js/editor/utils/editor-one-events.js":
5 /*!**********************************************************!*\
6 !*** ../assets/dev/js/editor/utils/editor-one-events.js ***!
7 \**********************************************************/
8 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
9
10 "use strict";
11
12
13 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
14 Object.defineProperty(exports, "__esModule", ({
15 value: true
16 }));
17 exports["default"] = exports.createDebouncedWidgetPanelSearch = exports.createDebouncedFinderSearch = exports.EditorOneEventManager = void 0;
18 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
19 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
20 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
21 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
22 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
23 var EditorOneEventManager = exports.EditorOneEventManager = /*#__PURE__*/function () {
24 function EditorOneEventManager() {
25 (0, _classCallCheck2.default)(this, EditorOneEventManager);
26 }
27 return (0, _createClass2.default)(EditorOneEventManager, null, [{
28 key: "getEventsManager",
29 value: function getEventsManager() {
30 var _elementorCommon;
31 return (_elementorCommon = elementorCommon) === null || _elementorCommon === void 0 ? void 0 : _elementorCommon.eventsManager;
32 }
33 }, {
34 key: "getConfig",
35 value: function getConfig() {
36 var _this$getEventsManage;
37 return (_this$getEventsManage = this.getEventsManager()) === null || _this$getEventsManage === void 0 ? void 0 : _this$getEventsManage.config;
38 }
39 }, {
40 key: "canSendEvents",
41 value: function canSendEvents() {
42 var _elementorCommon2;
43 return ((_elementorCommon2 = elementorCommon) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.config) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.editor_events) === null || _elementorCommon2 === void 0 ? void 0 : _elementorCommon2.can_send_events) || false;
44 }
45 }, {
46 key: "isEventsManagerAvailable",
47 value: function isEventsManagerAvailable() {
48 var eventsManager = this.getEventsManager();
49 return eventsManager && 'function' === typeof eventsManager.dispatchEvent;
50 }
51 }, {
52 key: "dispatchEvent",
53 value: function dispatchEvent(eventName, payload) {
54 if (!this.isEventsManagerAvailable() || !this.canSendEvents()) {
55 return false;
56 }
57 try {
58 return this.getEventsManager().dispatchEvent(eventName, payload);
59 } catch (error) {
60 return false;
61 }
62 }
63 }, {
64 key: "toLowerSnake",
65 value: function toLowerSnake(value) {
66 if (!value || 'string' !== typeof value) {
67 return value;
68 }
69 return value.replace(/\s+/g, '_').toLowerCase();
70 }
71 }, {
72 key: "decodeHtmlEntities",
73 value: function decodeHtmlEntities(text) {
74 if (!text || 'string' !== typeof text) {
75 return text;
76 }
77 var doc = new DOMParser().parseFromString(text, 'text/html');
78 return doc.body.textContent || text;
79 }
80 }, {
81 key: "isInEditorContext",
82 value: function isInEditorContext() {
83 var _window$elementor;
84 return 'undefined' !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
85 }
86 }, {
87 key: "getFinderContext",
88 value: function getFinderContext() {
89 var _config$appTypes, _config$appTypes2, _config$locations, _config$locations2;
90 var config = this.getConfig();
91 var isEditor = this.isInEditorContext();
92 return {
93 windowName: isEditor ? config === null || config === void 0 || (_config$appTypes = config.appTypes) === null || _config$appTypes === void 0 ? void 0 : _config$appTypes.editor : config === null || config === void 0 || (_config$appTypes2 = config.appTypes) === null || _config$appTypes2 === void 0 ? void 0 : _config$appTypes2.wpAdmin,
94 targetLocation: this.toLowerSnake(isEditor ? config === null || config === void 0 || (_config$locations = config.locations) === null || _config$locations === void 0 ? void 0 : _config$locations.topBar : config === null || config === void 0 || (_config$locations2 = config.locations) === null || _config$locations2 === void 0 ? void 0 : _config$locations2.sidebar)
95 };
96 }
97 }, {
98 key: "createBasePayload",
99 value: function createBasePayload() {
100 var _config$appTypes$edit, _config$appTypes3, _config$appTypes$edit2, _config$appTypes4;
101 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
102 var config = this.getConfig();
103 return _objectSpread({
104 app_type: (_config$appTypes$edit = config === null || config === void 0 || (_config$appTypes3 = config.appTypes) === null || _config$appTypes3 === void 0 ? void 0 : _config$appTypes3.editor) !== null && _config$appTypes$edit !== void 0 ? _config$appTypes$edit : 'editor',
105 window_name: (_config$appTypes$edit2 = config === null || config === void 0 || (_config$appTypes4 = config.appTypes) === null || _config$appTypes4 === void 0 ? void 0 : _config$appTypes4.editor) !== null && _config$appTypes$edit2 !== void 0 ? _config$appTypes$edit2 : 'editor'
106 }, overrides);
107 }
108 }, {
109 key: "sendTopBarPublishDropdown",
110 value: function sendTopBarPublishDropdown(targetName) {
111 var _config$names, _config$triggers, _config$targetTypes, _config$interactionRe, _config$locations3, _config$secondaryLoca, _config$targetTypes2;
112 var config = this.getConfig();
113 return this.dispatchEvent(config === null || config === void 0 || (_config$names = config.names) === null || _config$names === void 0 || (_config$names = _config$names.editorOne) === null || _config$names === void 0 ? void 0 : _config$names.topBarPublishDropdown, this.createBasePayload({
114 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
115 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
116 target_name: targetName,
117 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
118 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
119 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
120 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
121 interaction_description: 'User selected an action from the publish dropdown'
122 }));
123 }
124 }, {
125 key: "sendTopBarPageList",
126 value: function sendTopBarPageList(targetName) {
127 var _config$names2, _config$triggers2, _config$targetTypes3, _config$interactionRe2, _config$interactionRe3, _config$locations4, _config$secondaryLoca2, _config$targetTypes4;
128 var isCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
129 var config = this.getConfig();
130 return this.dispatchEvent(config === null || config === void 0 || (_config$names2 = config.names) === null || _config$names2 === void 0 || (_config$names2 = _config$names2.editorOne) === null || _config$names2 === void 0 ? void 0 : _config$names2.topBarPageList, this.createBasePayload({
131 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
132 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
133 target_name: targetName,
134 interaction_result: isCreate ? config === null || config === void 0 || (_config$interactionRe2 = config.interactionResults) === null || _config$interactionRe2 === void 0 ? void 0 : _config$interactionRe2.create : config === null || config === void 0 || (_config$interactionRe3 = config.interactionResults) === null || _config$interactionRe3 === void 0 ? void 0 : _config$interactionRe3.navigate,
135 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
136 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
137 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
138 interaction_description: 'User selected an action from the page list dropdown'
139 }));
140 }
141 }, {
142 key: "sendSiteSettingsSession",
143 value: function sendSiteSettingsSession(_ref) {
144 var _config$names3, _config$triggers3, _config$interactionRe4, _config$locations5, _config$secondaryLoca3;
145 var targetType = _ref.targetType,
146 _ref$visitedItems = _ref.visitedItems,
147 visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems,
148 _ref$savedItems = _ref.savedItems,
149 savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems,
150 state = _ref.state;
151 var config = this.getConfig();
152 return this.dispatchEvent(config === null || config === void 0 || (_config$names3 = config.names) === null || _config$names3 === void 0 || (_config$names3 = _config$names3.editorOne) === null || _config$names3 === void 0 ? void 0 : _config$names3.siteSettingsSession, this.createBasePayload({
153 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
154 target_type: targetType,
155 target_name: 'site_settings',
156 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
157 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
158 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
159 interaction_description: 'Records areas visited as part of the site setting session',
160 metadata: {
161 visited_items: visitedItems,
162 saved_items: savedItems
163 },
164 state: state
165 }));
166 }
167 }, {
168 key: "sendELibraryNav",
169 value: function sendELibraryNav(tabName) {
170 var _config$names4, _config$triggers4, _config$targetTypes5, _config$interactionRe5, _config$locations6, _config$secondaryLoca4;
171 var config = this.getConfig();
172 return this.dispatchEvent(config === null || config === void 0 || (_config$names4 = config.names) === null || _config$names4 === void 0 || (_config$names4 = _config$names4.editorOne) === null || _config$names4 === void 0 ? void 0 : _config$names4.eLibraryNav, this.createBasePayload({
173 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
174 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
175 target_name: this.toLowerSnake(tabName),
176 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
177 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
178 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
179 interaction_description: 'User navigates within elementor library'
180 }));
181 }
182 }, {
183 key: "sendELibraryInsert",
184 value: function sendELibraryInsert(_ref2) {
185 var _config$triggers5, _config$targetTypes6, _config$interactionRe6, _config$locations7, _config$secondaryLoca5, _config$names5;
186 var assetId = _ref2.assetId,
187 assetName = _ref2.assetName,
188 libraryType = _ref2.libraryType,
189 _ref2$proRequired = _ref2.proRequired,
190 proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
191 var config = this.getConfig();
192 var payload = this.createBasePayload({
193 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
194 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
195 target_name: String(assetId),
196 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
197 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
198 location_l1: this.toLowerSnake(libraryType),
199 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
200 interaction_description: 'User inserts block/pages from elementor library',
201 metadata: {
202 template_id: String(assetId),
203 template_name: this.decodeHtmlEntities(assetName) || ''
204 }
205 });
206 if (proRequired) {
207 payload.state = 'pro_plan_required';
208 }
209 return this.dispatchEvent(config === null || config === void 0 || (_config$names5 = config.names) === null || _config$names5 === void 0 || (_config$names5 = _config$names5.editorOne) === null || _config$names5 === void 0 ? void 0 : _config$names5.eLibraryInsert, payload);
210 }
211 }, {
212 key: "sendELibraryFavorite",
213 value: function sendELibraryFavorite(_ref3) {
214 var _config$triggers6, _config$targetTypes7, _config$interactionRe7, _config$locations8, _config$secondaryLoca6, _config$names6;
215 var assetId = _ref3.assetId,
216 assetName = _ref3.assetName,
217 libraryType = _ref3.libraryType,
218 isFavorite = _ref3.isFavorite,
219 _ref3$proRequired = _ref3.proRequired,
220 proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
221 var config = this.getConfig();
222 var payload = this.createBasePayload({
223 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
224 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
225 target_name: String(assetId),
226 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
227 target_value: Boolean(isFavorite),
228 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
229 location_l1: this.toLowerSnake(libraryType),
230 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
231 interaction_description: 'User favorite block/pages from elementor library',
232 metadata: {
233 template_id: String(assetId),
234 template_name: this.decodeHtmlEntities(assetName) || ''
235 }
236 });
237 if (proRequired) {
238 payload.state = 'pro_plan_required';
239 }
240 return this.dispatchEvent(config === null || config === void 0 || (_config$names6 = config.names) === null || _config$names6 === void 0 || (_config$names6 = _config$names6.editorOne) === null || _config$names6 === void 0 ? void 0 : _config$names6.eLibraryFavorite, payload);
241 }
242 }, {
243 key: "sendELibraryGenerateAi",
244 value: function sendELibraryGenerateAi(_ref4) {
245 var _config$names7, _config$triggers7, _config$targetTypes8, _config$interactionRe8, _config$locations9, _config$secondaryLoca7;
246 var assetId = _ref4.assetId,
247 assetName = _ref4.assetName,
248 libraryType = _ref4.libraryType;
249 var config = this.getConfig();
250 return this.dispatchEvent(config === null || config === void 0 || (_config$names7 = config.names) === null || _config$names7 === void 0 || (_config$names7 = _config$names7.editorOne) === null || _config$names7 === void 0 ? void 0 : _config$names7.eLibraryGenerateAi, this.createBasePayload({
251 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
252 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
253 target_name: String(assetId),
254 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
255 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
256 location_l1: this.toLowerSnake(libraryType),
257 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
258 interaction_description: 'User generated block/page based on a library asset',
259 metadata: {
260 template_id: String(assetId),
261 template_name: this.decodeHtmlEntities(assetName) || ''
262 }
263 }));
264 }
265 }, {
266 key: "sendFinderSearchInput",
267 value: function sendFinderSearchInput(_ref5) {
268 var _config$triggers8, _config$targetTypes9, _config$interactionRe9, _config$interactionRe0, _config$secondaryLoca8, _config$names8;
269 var resultsCount = _ref5.resultsCount,
270 _ref5$searchTerm = _ref5.searchTerm,
271 searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
272 var config = this.getConfig();
273 var hasResults = resultsCount > 0;
274 var finderContext = this.getFinderContext();
275 var payload = this.createBasePayload({
276 window_name: finderContext.windowName,
277 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
278 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
279 target_name: 'finder',
280 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe9 = config.interactionResults) === null || _config$interactionRe9 === void 0 ? void 0 : _config$interactionRe9.resultsUpdated : config === null || config === void 0 || (_config$interactionRe0 = config.interactionResults) === null || _config$interactionRe0 === void 0 ? void 0 : _config$interactionRe0.noResults,
281 target_location: finderContext.targetLocation,
282 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
283 interaction_description: 'Finder search input, follows debounce behavior',
284 metadata: {
285 results_count: resultsCount
286 }
287 });
288 if (!hasResults && searchTerm) {
289 payload.metadata.search_term = searchTerm;
290 }
291 return this.dispatchEvent(config === null || config === void 0 || (_config$names8 = config.names) === null || _config$names8 === void 0 || (_config$names8 = _config$names8.editorOne) === null || _config$names8 === void 0 ? void 0 : _config$names8.finderSearchInput, payload);
292 }
293 }, {
294 key: "sendFinderResultSelect",
295 value: function sendFinderResultSelect(choice) {
296 var _config$names9, _config$triggers9, _config$targetTypes0, _config$interactionRe1, _config$secondaryLoca9, _config$secondaryLoca0;
297 var config = this.getConfig();
298 var finderContext = this.getFinderContext();
299 return this.dispatchEvent(config === null || config === void 0 || (_config$names9 = config.names) === null || _config$names9 === void 0 || (_config$names9 = _config$names9.editorOne) === null || _config$names9 === void 0 ? void 0 : _config$names9.finderResultSelect, this.createBasePayload({
300 window_name: finderContext.windowName,
301 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
302 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
303 target_name: choice,
304 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
305 target_location: finderContext.targetLocation,
306 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
307 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
308 interaction_description: 'Finder search results was selected'
309 }));
310 }
311 }, {
312 key: "sendCanvasEmptyBoxAction",
313 value: function sendCanvasEmptyBoxAction(_ref6) {
314 var _config$triggers0, _config$targetTypes1, _config$interactionRe10, _config$locations0, _config$secondaryLoca1, _config$names0;
315 var targetName = _ref6.targetName,
316 _ref6$metadata = _ref6.metadata,
317 metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata,
318 _ref6$containerCreate = _ref6.containerCreated,
319 containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
320 var config = this.getConfig();
321 var payload = this.createBasePayload({
322 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
323 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
324 target_name: targetName,
325 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
326 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
327 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
328 interaction_description: 'Empty box on canvas actions'
329 });
330 if (Object.keys(metadata).length > 0) {
331 payload.metadata = metadata;
332 }
333 if (containerCreated !== null) {
334 payload.state = containerCreated;
335 }
336 return this.dispatchEvent(config === null || config === void 0 || (_config$names0 = config.names) === null || _config$names0 === void 0 || (_config$names0 = _config$names0.editorOne) === null || _config$names0 === void 0 ? void 0 : _config$names0.canvasEmptyBoxAction, payload);
337 }
338 }, {
339 key: "sendWidgetPanelSearch",
340 value: function sendWidgetPanelSearch(_ref7) {
341 var _config$triggers1, _config$targetTypes10, _config$interactionRe11, _config$interactionRe12, _config$locations1, _config$locations10, _config$secondaryLoca10, _config$names1;
342 var resultsCount = _ref7.resultsCount,
343 _ref7$userInput = _ref7.userInput,
344 userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
345 var config = this.getConfig();
346 var hasResults = resultsCount > 0;
347 var payload = this.createBasePayload({
348 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
349 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
350 target_name: 'search_widget',
351 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe11 = config.interactionResults) === null || _config$interactionRe11 === void 0 ? void 0 : _config$interactionRe11.resultsUpdated : config === null || config === void 0 || (_config$interactionRe12 = config.interactionResults) === null || _config$interactionRe12 === void 0 ? void 0 : _config$interactionRe12.noResults,
352 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
353 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
354 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
355 interaction_description: 'Widget search input, follows debounce behavior'
356 });
357 if (!hasResults && userInput) {
358 payload.metadata = {
359 user_input: userInput
360 };
361 }
362 return this.dispatchEvent(config === null || config === void 0 || (_config$names1 = config.names) === null || _config$names1 === void 0 || (_config$names1 = _config$names1.editorOne) === null || _config$names1 === void 0 ? void 0 : _config$names1.widgetPanelSearch, payload);
363 }
364 }]);
365 }();
366 var createDebouncedFinderSearch = exports.createDebouncedFinderSearch = function createDebouncedFinderSearch() {
367 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
368 return _.debounce(function (resultsCount, searchTerm) {
369 EditorOneEventManager.sendFinderSearchInput({
370 resultsCount: resultsCount,
371 searchTerm: searchTerm
372 });
373 }, delay);
374 };
375 var createDebouncedWidgetPanelSearch = exports.createDebouncedWidgetPanelSearch = function createDebouncedWidgetPanelSearch() {
376 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2000;
377 return _.debounce(function (resultsCount, userInput) {
378 EditorOneEventManager.sendWidgetPanelSearch({
379 resultsCount: resultsCount,
380 userInput: userInput
381 });
382 }, delay);
383 };
384 var _default = exports["default"] = EditorOneEventManager;
385
386 /***/ }),
387
388 /***/ "../assets/dev/js/editor/utils/files-upload-handler.js":
389 /*!*************************************************************!*\
390 !*** ../assets/dev/js/editor/utils/files-upload-handler.js ***!
391 \*************************************************************/
392 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
393
394 "use strict";
395 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
396
397
398 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
399 Object.defineProperty(exports, "__esModule", ({
400 value: true
401 }));
402 exports["default"] = void 0;
403 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
404 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
405 var FilesUploadHandler = exports["default"] = /*#__PURE__*/function () {
406 function FilesUploadHandler() {
407 (0, _classCallCheck2.default)(this, FilesUploadHandler);
408 }
409 return (0, _createClass2.default)(FilesUploadHandler, null, [{
410 key: "isUploadEnabled",
411 value: function isUploadEnabled(mediaType) {
412 var unfilteredFilesTypes = ['svg', 'application/json'];
413 if (!unfilteredFilesTypes.includes(mediaType)) {
414 return true;
415 }
416 return elementorCommon.config.filesUpload.unfilteredFiles;
417 }
418 }, {
419 key: "setUploadTypeCaller",
420 value: function setUploadTypeCaller(frame) {
421 frame.uploader.uploader.param('uploadTypeCaller', 'elementor-wp-media-upload');
422 }
423 }, {
424 key: "getUnfilteredFilesNonAdminDialog",
425 value: function getUnfilteredFilesNonAdminDialog() {
426 return elementorCommon.dialogsManager.createWidget('alert', {
427 id: 'e-unfiltered-files-disabled-dialog',
428 headerMessage: __('Sorry, you can\'t upload that file yet', 'elementor'),
429 message: __('This is because JSON files may pose a security risk.', 'elementor') + '<br><br>' + __('To upload them anyway, ask the site administrator to enable unfiltered file uploads.', 'elementor'),
430 strings: {
431 confirm: __('Got it', 'elementor')
432 }
433 });
434 }
435 }, {
436 key: "getUnfilteredFilesNotEnabledDialog",
437 value: function getUnfilteredFilesNotEnabledDialog(callback) {
438 var elementorInstance = window.elementorAdmin || window.elementor;
439 if (!elementorInstance.config.user.is_administrator) {
440 return this.getUnfilteredFilesNonAdminDialog();
441 }
442 var onConfirm = function onConfirm() {
443 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {}, true);
444 elementorCommon.config.filesUpload.unfilteredFiles = true;
445 callback();
446 };
447 return elementorInstance.helpers.getSimpleDialog('e-enable-unfiltered-files-dialog', __('Enable Unfiltered File Uploads', 'elementor'), __('Before you enable unfiltered files upload, note that such files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.', 'elementor'), __('Enable', 'elementor'), onConfirm);
448 }
449 }, {
450 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
451 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
452 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) {
453 return this.getUnfilteredFilesNonAdminDialog();
454 }
455 return elementorCommon.dialogsManager.createWidget('confirm', {
456 id: 'e-enable-unfiltered-files-dialog-import-template',
457 headerMessage: __('Enable Unfiltered File Uploads', 'elementor'),
458 message: __('Before you enable unfiltered files upload, note that such files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.', 'elementor') + '<br /><br />' + __('If you do not enable uploading unfiltered files, any SVG or JSON (including lottie) files used in the uploaded template will not be imported.', 'elementor'),
459 position: {
460 my: 'center center',
461 at: 'center center'
462 },
463 strings: {
464 confirm: __('Enable and Import', 'elementor'),
465 cancel: __('Import Without Enabling', 'elementor')
466 },
467 onConfirm: function onConfirm() {
468 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {
469 success: function success() {
470 // This utility is used in both the admin and the Editor.
471 elementorCommon.config.filesUpload.unfilteredFiles = true;
472 callback();
473 }
474 }, true);
475 },
476 onCancel: function onCancel() {
477 return callback();
478 }
479 });
480 }
481 }]);
482 }();
483
484 /***/ }),
485
486 /***/ "../assets/dev/js/editor/utils/is-instanceof.js":
487 /*!******************************************************!*\
488 !*** ../assets/dev/js/editor/utils/is-instanceof.js ***!
489 \******************************************************/
490 /***/ ((__unused_webpack_module, exports) => {
491
492 "use strict";
493
494
495 Object.defineProperty(exports, "__esModule", ({
496 value: true
497 }));
498 exports["default"] = void 0;
499 function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
500 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; } }
501 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; }
502 /**
503 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
504 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
505 * check whether it's instanceof by using the objects constructor and prototype names.
506 *
507 * @param object
508 * @param constructors
509 * @return {boolean}
510 */
511 var _default = exports["default"] = function _default(object, constructors) {
512 constructors = Array.isArray(constructors) ? constructors : [constructors];
513 var _iterator = _createForOfIteratorHelper(constructors),
514 _step;
515 try {
516 for (_iterator.s(); !(_step = _iterator.n()).done;) {
517 var constructor = _step.value;
518 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) {
519 return true;
520 }
521 }
522 } catch (err) {
523 _iterator.e(err);
524 } finally {
525 _iterator.f();
526 }
527 return false;
528 };
529
530 /***/ }),
531
532 /***/ "../assets/dev/js/modules/imports/args-object.js":
533 /*!*******************************************************!*\
534 !*** ../assets/dev/js/modules/imports/args-object.js ***!
535 \*******************************************************/
536 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
537
538 "use strict";
539
540
541 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
542 Object.defineProperty(exports, "__esModule", ({
543 value: true
544 }));
545 exports["default"] = void 0;
546 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
547 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
548 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
549 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
550 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
551 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
552 var _instanceType = _interopRequireDefault(__webpack_require__(/*! ./instance-type */ "../assets/dev/js/modules/imports/instance-type.js"));
553 var _isInstanceof = _interopRequireDefault(__webpack_require__(/*! ../../editor/utils/is-instanceof */ "../assets/dev/js/editor/utils/is-instanceof.js"));
554 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
555 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
556 var ArgsObject = exports["default"] = /*#__PURE__*/function (_InstanceType) {
557 /**
558 * Function constructor().
559 *
560 * Create ArgsObject.
561 *
562 * @param {{}} args
563 */
564 function ArgsObject(args) {
565 var _this;
566 (0, _classCallCheck2.default)(this, ArgsObject);
567 _this = _callSuper(this, ArgsObject);
568 _this.args = args;
569 return _this;
570 }
571
572 /**
573 * Function requireArgument().
574 *
575 * Validate property in args.
576 *
577 * @param {string} property
578 * @param {{}} args
579 *
580 * @throws {Error}
581 */
582 (0, _inherits2.default)(ArgsObject, _InstanceType);
583 return (0, _createClass2.default)(ArgsObject, [{
584 key: "requireArgument",
585 value: function requireArgument(property) {
586 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.args;
587 if (!Object.prototype.hasOwnProperty.call(args, property)) {
588 throw Error("".concat(property, " is required."));
589 }
590 }
591
592 /**
593 * Function requireArgumentType().
594 *
595 * Validate property in args using `type === typeof(args.whatever)`.
596 *
597 * @param {string} property
598 * @param {string} type
599 * @param {{}} args
600 *
601 * @throws {Error}
602 */
603 }, {
604 key: "requireArgumentType",
605 value: function requireArgumentType(property, type) {
606 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
607 this.requireArgument(property, args);
608 if ((0, _typeof2.default)(args[property]) !== type) {
609 throw Error("".concat(property, " invalid type: ").concat(type, "."));
610 }
611 }
612
613 /**
614 * Function requireArgumentInstance().
615 *
616 * Validate property in args using `args.whatever instanceof instance`.
617 *
618 * @param {string} property
619 * @param {*} instance
620 * @param {{}} args
621 *
622 * @throws {Error}
623 */
624 }, {
625 key: "requireArgumentInstance",
626 value: function requireArgumentInstance(property, instance) {
627 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
628 this.requireArgument(property, args);
629 if (!(args[property] instanceof instance) && !(0, _isInstanceof.default)(args[property], instance)) {
630 throw Error("".concat(property, " invalid instance."));
631 }
632 }
633
634 /**
635 * Function requireArgumentConstructor().
636 *
637 * Validate property in args using `type === args.whatever.constructor`.
638 *
639 * @param {string} property
640 * @param {*} type
641 * @param {{}} args
642 *
643 * @throws {Error}
644 */
645 }, {
646 key: "requireArgumentConstructor",
647 value: function requireArgumentConstructor(property, type) {
648 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
649 this.requireArgument(property, args);
650
651 // Note: Converting the constructor to string in order to avoid equation issues
652 // due to different memory addresses between iframes (window.Object !== window.top.Object).
653 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) {
654 throw Error("".concat(property, " invalid constructor type."));
655 }
656 }
657 }], [{
658 key: "getInstanceType",
659 value: function getInstanceType() {
660 return 'ArgsObject';
661 }
662 }]);
663 }(_instanceType.default);
664
665 /***/ }),
666
667 /***/ "../assets/dev/js/modules/imports/instance-type.js":
668 /*!*********************************************************!*\
669 !*** ../assets/dev/js/modules/imports/instance-type.js ***!
670 \*********************************************************/
671 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
672
673 "use strict";
674
675
676 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
677 Object.defineProperty(exports, "__esModule", ({
678 value: true
679 }));
680 exports["default"] = void 0;
681 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
682 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
683 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
684 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
685 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
686 var InstanceType = exports["default"] = /*#__PURE__*/function () {
687 function InstanceType() {
688 var _this = this;
689 (0, _classCallCheck2.default)(this, InstanceType);
690 // Since anonymous classes sometimes do not get validated by babel, do it manually.
691 var target = this instanceof InstanceType ? this.constructor : void 0;
692 var prototypes = [];
693 while (target.__proto__ && target.__proto__.name) {
694 prototypes.push(target.__proto__);
695 target = target.__proto__;
696 }
697 prototypes.reverse().forEach(function (proto) {
698 return _this instanceof proto;
699 });
700 }
701 return (0, _createClass2.default)(InstanceType, null, [{
702 key: Symbol.hasInstance,
703 value: function value(target) {
704 /**
705 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
706 * its give's opportunity to mange capabilities of instanceOf operator.
707 * saving current class each time will give option later to handle instanceOf manually.
708 */
709 var result = _superPropGet(InstanceType, Symbol.hasInstance, this, 2)([target]);
710
711 // Act normal when validate a class, which does not have instance type.
712 if (target && !target.constructor.getInstanceType) {
713 return result;
714 }
715 if (target) {
716 if (!target.instanceTypes) {
717 target.instanceTypes = [];
718 }
719 if (!result) {
720 if (this.getInstanceType() === target.constructor.getInstanceType()) {
721 result = true;
722 }
723 }
724 if (result) {
725 var name = this.getInstanceType === InstanceType.getInstanceType ? 'BaseInstanceType' : this.getInstanceType();
726 if (-1 === target.instanceTypes.indexOf(name)) {
727 target.instanceTypes.push(name);
728 }
729 }
730 }
731 if (!result && target) {
732 // Check if the given 'target', is instance of known types.
733 result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
734 }
735 return result;
736 }
737 }, {
738 key: "getInstanceType",
739 value: function getInstanceType() {
740 elementorModules.ForceMethodImplementation();
741 }
742 }]);
743 }();
744
745 /***/ }),
746
747 /***/ "../assets/dev/js/modules/imports/module.js":
748 /*!**************************************************!*\
749 !*** ../assets/dev/js/modules/imports/module.js ***!
750 \**************************************************/
751 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
752
753 "use strict";
754
755
756 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
757 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
758 var Module = function Module() {
759 var $ = jQuery,
760 instanceParams = arguments,
761 self = this,
762 events = {};
763 var settings;
764 var ensureClosureMethods = function ensureClosureMethods() {
765 $.each(self, function (methodName) {
766 var oldMethod = self[methodName];
767 if ('function' !== typeof oldMethod) {
768 return;
769 }
770 self[methodName] = function () {
771 return oldMethod.apply(self, arguments);
772 };
773 });
774 };
775 var initSettings = function initSettings() {
776 settings = self.getDefaultSettings();
777 var instanceSettings = instanceParams[0];
778 if (instanceSettings) {
779 $.extend(true, settings, instanceSettings);
780 }
781 };
782 var init = function init() {
783 self.__construct.apply(self, instanceParams);
784 ensureClosureMethods();
785 initSettings();
786 self.trigger('init');
787 };
788 this.getItems = function (items, itemKey) {
789 if (itemKey) {
790 var keyStack = itemKey.split('.'),
791 currentKey = keyStack.splice(0, 1);
792 if (!keyStack.length) {
793 return items[currentKey];
794 }
795 if (!items[currentKey]) {
796 return;
797 }
798 return this.getItems(items[currentKey], keyStack.join('.'));
799 }
800 return items;
801 };
802 this.getSettings = function (setting) {
803 return this.getItems(settings, setting);
804 };
805 this.setSettings = function (settingKey, value, settingsContainer) {
806 if (!settingsContainer) {
807 settingsContainer = settings;
808 }
809 if ('object' === (0, _typeof2.default)(settingKey)) {
810 $.extend(settingsContainer, settingKey);
811 return self;
812 }
813 var keyStack = settingKey.split('.'),
814 currentKey = keyStack.splice(0, 1);
815 if (!keyStack.length) {
816 settingsContainer[currentKey] = value;
817 return self;
818 }
819 if (!settingsContainer[currentKey]) {
820 settingsContainer[currentKey] = {};
821 }
822 return self.setSettings(keyStack.join('.'), value, settingsContainer[currentKey]);
823 };
824 this.getErrorMessage = function (type, functionName) {
825 var message;
826 switch (type) {
827 case 'forceMethodImplementation':
828 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
829 break;
830 default:
831 message = 'An error occurs';
832 }
833 return message;
834 };
835
836 // TODO: This function should be deleted ?.
837 this.forceMethodImplementation = function (functionName) {
838 throw new Error(this.getErrorMessage('forceMethodImplementation', functionName));
839 };
840 this.on = function (eventName, callback) {
841 if ('object' === (0, _typeof2.default)(eventName)) {
842 $.each(eventName, function (singleEventName) {
843 self.on(singleEventName, this);
844 });
845 return self;
846 }
847 var eventNames = eventName.split(' ');
848 eventNames.forEach(function (singleEventName) {
849 if (!events[singleEventName]) {
850 events[singleEventName] = [];
851 }
852 events[singleEventName].push(callback);
853 });
854 return self;
855 };
856 this.off = function (eventName, callback) {
857 if (!events[eventName]) {
858 return self;
859 }
860 if (!callback) {
861 delete events[eventName];
862 return self;
863 }
864 var callbackIndex = events[eventName].indexOf(callback);
865 if (-1 !== callbackIndex) {
866 delete events[eventName][callbackIndex];
867
868 // Reset array index (for next off on same event).
869 events[eventName] = events[eventName].filter(function (val) {
870 return val;
871 });
872 }
873 return self;
874 };
875 this.trigger = function (eventName) {
876 var methodName = 'on' + eventName[0].toUpperCase() + eventName.slice(1),
877 params = Array.prototype.slice.call(arguments, 1);
878 if (self[methodName]) {
879 self[methodName].apply(self, params);
880 }
881 var callbacks = events[eventName];
882 if (!callbacks) {
883 return self;
884 }
885 $.each(callbacks, function (index, callback) {
886 callback.apply(self, params);
887 });
888 return self;
889 };
890 init();
891 };
892 Module.prototype.__construct = function () {};
893 Module.prototype.getDefaultSettings = function () {
894 return {};
895 };
896 Module.prototype.getConstructorID = function () {
897 return this.constructor.name;
898 };
899 Module.extend = function (properties) {
900 var $ = jQuery,
901 parent = this;
902 var child = function child() {
903 return parent.apply(this, arguments);
904 };
905 $.extend(child, parent);
906 child.prototype = Object.create($.extend({}, parent.prototype, properties));
907 child.prototype.constructor = child;
908 child.__super__ = parent.prototype;
909 return child;
910 };
911 module.exports = Module;
912
913 /***/ }),
914
915 /***/ "../assets/dev/js/utils/notifications.js":
916 /*!***********************************************!*\
917 !*** ../assets/dev/js/utils/notifications.js ***!
918 \***********************************************/
919 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
920
921 "use strict";
922
923
924 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
925 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
926 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
927 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
928 module.exports = elementorModules.Module.extend({
929 initToast: function initToast() {
930 var toast = elementorCommon.dialogsManager.createWidget('buttons', {
931 id: 'elementor-toast',
932 position: {
933 my: 'center bottom',
934 at: 'center bottom-10',
935 of: '#elementor-panel-inner',
936 autoRefresh: true
937 },
938 hide: {
939 onClick: true,
940 auto: true,
941 autoDelay: 10000
942 },
943 effects: {
944 show: function show() {
945 var $widget = toast.getElements('widget');
946 $widget.show();
947 toast.refreshPosition();
948 var top = parseInt($widget.css('top'), 10);
949 $widget.hide().css('top', top + 100);
950 $widget.animate({
951 opacity: 'show',
952 height: 'show',
953 paddingBottom: 'show',
954 paddingTop: 'show',
955 top: top
956 }, {
957 easing: 'linear',
958 duration: 300
959 });
960 },
961 hide: function hide() {
962 var $widget = toast.getElements('widget'),
963 top = parseInt($widget.css('top'), 10);
964 $widget.animate({
965 opacity: 'hide',
966 height: 'hide',
967 paddingBottom: 'hide',
968 paddingTop: 'hide',
969 top: top + 100
970 }, {
971 easing: 'linear',
972 duration: 300
973 });
974 }
975 },
976 button: {
977 tag: 'button'
978 }
979 });
980
981 // Add role="status" and aria-live for screen reader announcement
982 toast.getElements('widget').attr({
983 role: 'status',
984 'aria-live': 'polite',
985 'aria-atomic': 'true'
986 });
987 this.getToast = function () {
988 return toast;
989 };
990 },
991 showToast: function showToast(options) {
992 var toast = this.getToast();
993 toast.setMessage(options.message);
994 toast.getElements('buttonsWrapper').empty();
995 toast.focusedButton = null;
996 toast.buttons = [];
997 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
998 if (!isPositionValid) {
999 this.positionToWindow();
1000 }
1001 if (options !== null && options !== void 0 && options.position && isPositionValid) {
1002 toast.setSettings('position', options.position);
1003 }
1004 if (options.buttons) {
1005 options.buttons.forEach(function (button) {
1006 toast.addButton(button);
1007 });
1008 }
1009 if (options.classes) {
1010 toast.getElements('widget').addClass(options.classes);
1011 }
1012 if (options.sticky) {
1013 toast.setSettings({
1014 hide: {
1015 auto: false,
1016 onClick: false
1017 }
1018 });
1019 }
1020 return toast.show();
1021 },
1022 isPositionValid: function isPositionValid(position) {
1023 var _position$of;
1024 var positionToCheck = (_position$of = position === null || position === void 0 ? void 0 : position.of) !== null && _position$of !== void 0 ? _position$of : this.getToast().getSettings('position').of;
1025 if (!positionToCheck) {
1026 return false;
1027 }
1028 return !!document.querySelector(positionToCheck);
1029 },
1030 positionToWindow: function positionToWindow() {
1031 var toast = this.getToast();
1032 var position = _objectSpread(_objectSpread({}, toast.getSettings('position')), {}, {
1033 my: 'right top',
1034 at: 'right-10 top+42',
1035 // 42px is the default admin bar height + 10px
1036 of: ''
1037 });
1038 toast.setSettings('position', position);
1039 toast.getElements('widget').addClass('dialog-position-window');
1040 },
1041 onInit: function onInit() {
1042 this.initToast();
1043 }
1044 });
1045
1046 /***/ }),
1047
1048 /***/ "../assets/dev/js/utils/tiers.js":
1049 /*!***************************************!*\
1050 !*** ../assets/dev/js/utils/tiers.js ***!
1051 \***************************************/
1052 /***/ ((__unused_webpack_module, exports) => {
1053
1054 "use strict";
1055
1056
1057 Object.defineProperty(exports, "__esModule", ({
1058 value: true
1059 }));
1060 exports.isTierAtLeast = exports.TIERS_PRIORITY = exports.TIERS = void 0;
1061 var TIERS_PRIORITY = exports.TIERS_PRIORITY = Object.freeze(['free', 'essential', 'essential-oct2023', 'advanced', 'expert', 'agency']);
1062
1063 /**
1064 * @type {Readonly<{
1065 * free: string;
1066 * essential: string;
1067 * 'essential-oct2023': string;
1068 * advanced: string;
1069 * expert: string;
1070 * agency: string;
1071 * }>}
1072 */
1073 var TIERS = exports.TIERS = Object.freeze(TIERS_PRIORITY.reduce(function (acc, tier) {
1074 acc[tier] = tier;
1075 return acc;
1076 }, {}));
1077 var isTierAtLeast = exports.isTierAtLeast = function isTierAtLeast(currentTier, expectedTier) {
1078 var currentTierIndex = TIERS_PRIORITY.indexOf(currentTier);
1079 var expectedTierIndex = TIERS_PRIORITY.indexOf(expectedTier);
1080 if (-1 === currentTierIndex || -1 === expectedTierIndex) {
1081 return false;
1082 }
1083 return currentTierIndex >= expectedTierIndex;
1084 };
1085
1086 /***/ }),
1087
1088 /***/ "../assets/dev/js/utils/time.js":
1089 /*!**************************************!*\
1090 !*** ../assets/dev/js/utils/time.js ***!
1091 \**************************************/
1092 /***/ ((__unused_webpack_module, exports) => {
1093
1094 "use strict";
1095
1096
1097 Object.defineProperty(exports, "__esModule", ({
1098 value: true
1099 }));
1100 exports["default"] = getUserTimestamp;
1101 /**
1102 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
1103 *
1104 * @since 3.6.0
1105 *
1106 * @param {Date} date
1107 * @return {Date} timestamp
1108 */
1109 function getUserTimestamp() {
1110 var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
1111 var timezoneOffset = date.getTimezoneOffset();
1112
1113 // Local time for the user
1114 var UTCTimestamp = new Date(date.getTime() - timezoneOffset * 60000).toISOString();
1115
1116 // Remove the Z suffix from the string.
1117 UTCTimestamp = UTCTimestamp.slice(0, -1);
1118
1119 // Create the offset string in the format `+HH:00` (or minus (-) prefix for negative offset instead of plus)
1120 var decimalTimezoneOffset = timezoneOffset / 60,
1121 // Negative offsets include a '-' sign in the getTimezoneOffset value, positive values need a '+' prefix (ISO8601).
1122 sign = 0 <= decimalTimezoneOffset ? '+' : '-',
1123 hours = Math.abs(Math.floor(decimalTimezoneOffset)),
1124 minutes = Math.abs(decimalTimezoneOffset % 1) * 60,
1125 addZeroToHour = 10 > hours ? '0' : '',
1126 addZeroToMinutes = 10 > minutes ? '0' : '';
1127 var formattedTimezoneOffset = sign + addZeroToHour + hours + ':' + addZeroToMinutes + minutes;
1128 return UTCTimestamp + formattedTimezoneOffset;
1129 }
1130
1131 /***/ }),
1132
1133 /***/ "../core/common/assets/js/components/wordpress/commands-data/index.js":
1134 /*!****************************************************************************!*\
1135 !*** ../core/common/assets/js/components/wordpress/commands-data/index.js ***!
1136 \****************************************************************************/
1137 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1138
1139 "use strict";
1140
1141
1142 Object.defineProperty(exports, "__esModule", ({
1143 value: true
1144 }));
1145 Object.defineProperty(exports, "Media", ({
1146 enumerable: true,
1147 get: function get() {
1148 return _media.Media;
1149 }
1150 }));
1151 var _media = __webpack_require__(/*! ./media */ "../core/common/assets/js/components/wordpress/commands-data/media.js");
1152
1153 /***/ }),
1154
1155 /***/ "../core/common/assets/js/components/wordpress/commands-data/media.js":
1156 /*!****************************************************************************!*\
1157 !*** ../core/common/assets/js/components/wordpress/commands-data/media.js ***!
1158 \****************************************************************************/
1159 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1160
1161 "use strict";
1162 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1163
1164
1165 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1166 Object.defineProperty(exports, "__esModule", ({
1167 value: true
1168 }));
1169 exports.Media = void 0;
1170 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
1171 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
1172 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1173 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1174 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1175 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1176 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1177 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1178 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
1179 var _filesUploadHandler = _interopRequireDefault(__webpack_require__(/*! elementor-editor/utils/files-upload-handler */ "../assets/dev/js/editor/utils/files-upload-handler.js"));
1180 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1181 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1182 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
1183 var Media = exports.Media = /*#__PURE__*/function (_CommandData) {
1184 function Media() {
1185 (0, _classCallCheck2.default)(this, Media);
1186 return _callSuper(this, Media, arguments);
1187 }
1188 (0, _inherits2.default)(Media, _CommandData);
1189 return (0, _createClass2.default)(Media, [{
1190 key: "validateArgs",
1191 value: function validateArgs() {
1192 this.requireArgumentInstance('file', File);
1193 }
1194 }, {
1195 key: "getRequestData",
1196 value: function getRequestData() {
1197 var requestData = _superPropGet(Media, "getRequestData", this, 3)([]);
1198 requestData.namespace = 'wp';
1199 requestData.version = '2';
1200 return requestData;
1201 }
1202 }, {
1203 key: "applyBeforeCreate",
1204 value: function applyBeforeCreate(args) {
1205 var _args$options;
1206 args.headers = {
1207 'Content-Disposition': "attachment; filename=".concat(this.file.name),
1208 'Content-Type': this.file.type
1209 };
1210 args.query = {
1211 uploadTypeCaller: 'elementor-wp-media-upload'
1212 };
1213 args.data = this.file;
1214 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) {
1215 this.toast = elementor.notifications.showToast({
1216 // eslint-disable-next-line @wordpress/i18n-ellipsis
1217 message: __('Uploading...'),
1218 sticky: true
1219 });
1220 }
1221 return args;
1222 }
1223 }, {
1224 key: "applyAfterCreate",
1225 value: function applyAfterCreate(data, args) {
1226 var _args$options2;
1227 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) {
1228 this.toast.hide();
1229 }
1230 return data;
1231 }
1232 }, {
1233 key: "run",
1234 value: function () {
1235 var _run = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
1236 return _regenerator.default.wrap(function (_context) {
1237 while (1) switch (_context.prev = _context.next) {
1238 case 0:
1239 this.file = this.args.file;
1240 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
1241 _context.next = 1;
1242 break;
1243 }
1244 throw new Error(__('The file exceeds the maximum upload size for this site.', 'elementor'));
1245 case 1:
1246 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(',').includes(this.file.name.split('.').pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
1247 _context.next = 2;
1248 break;
1249 }
1250 _filesUploadHandler.default.getUnfilteredFilesNotEnabledDialog(function () {}).show();
1251 return _context.abrupt("return");
1252 case 2:
1253 _context.next = 3;
1254 return _superPropGet(Media, "run", this, 3)([]);
1255 case 3:
1256 return _context.abrupt("return", _context.sent);
1257 case 4:
1258 case "end":
1259 return _context.stop();
1260 }
1261 }, _callee, this);
1262 }));
1263 function run() {
1264 return _run.apply(this, arguments);
1265 }
1266 return run;
1267 }()
1268 }], [{
1269 key: "getEndpointFormat",
1270 value: function getEndpointFormat() {
1271 // 'wp/media' to 'media' since `requestData.namespace` is 'wp'.
1272 return 'media';
1273 }
1274 }]);
1275 }(_commandData.default);
1276
1277 /***/ }),
1278
1279 /***/ "../core/common/assets/js/components/wordpress/component.js":
1280 /*!******************************************************************!*\
1281 !*** ../core/common/assets/js/components/wordpress/component.js ***!
1282 \******************************************************************/
1283 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1284
1285 "use strict";
1286
1287
1288 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1289 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
1290 Object.defineProperty(exports, "__esModule", ({
1291 value: true
1292 }));
1293 exports["default"] = void 0;
1294 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1295 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1296 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1297 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1298 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1299 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
1300 var dataCommands = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/assets/js/components/wordpress/commands-data/index.js"));
1301 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
1302 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1303 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1304 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
1305 function Component() {
1306 (0, _classCallCheck2.default)(this, Component);
1307 return _callSuper(this, Component, arguments);
1308 }
1309 (0, _inherits2.default)(Component, _ComponentBase);
1310 return (0, _createClass2.default)(Component, [{
1311 key: "getNamespace",
1312 value: function getNamespace() {
1313 return 'wp';
1314 }
1315 }, {
1316 key: "defaultData",
1317 value: function defaultData() {
1318 return this.importCommands(dataCommands);
1319 }
1320 }]);
1321 }(_componentBase.default);
1322
1323 /***/ }),
1324
1325 /***/ "../core/common/assets/js/utils/debug.js":
1326 /*!***********************************************!*\
1327 !*** ../core/common/assets/js/utils/debug.js ***!
1328 \***********************************************/
1329 /***/ ((module) => {
1330
1331 "use strict";
1332
1333
1334 // Moved from assets/dev/js/editor/utils
1335 var Debug = function Debug() {
1336 var self = this,
1337 errorStack = [],
1338 settings = {},
1339 elements = {};
1340 var initSettings = function initSettings() {
1341 settings = {
1342 debounceDelay: 500,
1343 urlsToWatch: ['elementor/assets']
1344 };
1345 };
1346 var initElements = function initElements() {
1347 elements.$window = jQuery(window);
1348 };
1349 var onError = function onError(event) {
1350 var _event$originalEvent;
1351 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
1352 if (!error) {
1353 return;
1354 }
1355 var isInWatchList = false,
1356 urlsToWatch = settings.urlsToWatch;
1357 jQuery.each(urlsToWatch, function () {
1358 if (-1 !== error.stack.indexOf(this)) {
1359 isInWatchList = true;
1360 return false;
1361 }
1362 });
1363 if (!isInWatchList) {
1364 return;
1365 }
1366 self.addError({
1367 type: error.name,
1368 message: error.message,
1369 url: event.originalEvent.filename,
1370 line: event.originalEvent.lineno,
1371 column: event.originalEvent.colno
1372 });
1373 };
1374 var bindEvents = function bindEvents() {
1375 elements.$window.on('error', onError);
1376 };
1377 var init = function init() {
1378 initSettings();
1379 initElements();
1380 bindEvents();
1381 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
1382 };
1383 this.addURLToWatch = function (url) {
1384 settings.urlsToWatch.push(url);
1385 };
1386 this.addCustomError = function (error, category, tag) {
1387 var errorInfo = {
1388 type: error.name,
1389 message: error.message,
1390 url: error.fileName || error.sourceURL,
1391 line: error.lineNumber || error.line,
1392 column: error.columnNumber || error.column,
1393 customFields: {
1394 category: category || 'general',
1395 tag: tag
1396 }
1397 };
1398 if (!errorInfo.url) {
1399 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
1400 if (stackInfo) {
1401 errorInfo.url = stackInfo[1];
1402 errorInfo.line = stackInfo[2];
1403 errorInfo.column = stackInfo[3];
1404 }
1405 }
1406 this.addError(errorInfo);
1407 };
1408 this.addError = function (errorParams) {
1409 var defaultParams = {
1410 type: 'Error',
1411 timestamp: Math.floor(new Date().getTime() / 1000),
1412 message: null,
1413 url: null,
1414 line: null,
1415 column: null,
1416 customFields: {}
1417 };
1418 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
1419 self.sendErrors();
1420 };
1421 this.sendErrors = function () {
1422 // Avoid recursions on errors in ajax
1423 elements.$window.off('error', onError);
1424 jQuery.ajax({
1425 url: elementorCommon.config.ajax.url,
1426 method: 'POST',
1427 data: {
1428 action: 'elementor_js_log',
1429 _nonce: elementorCommon.ajax.getSettings('nonce'),
1430 data: errorStack
1431 },
1432 success: function success() {
1433 errorStack = [];
1434
1435 // Restore error handler
1436 elements.$window.on('error', onError);
1437 }
1438 });
1439 };
1440 init();
1441 };
1442 module.exports = Debug;
1443
1444 /***/ }),
1445
1446 /***/ "../core/common/assets/js/utils/helpers.js":
1447 /*!*************************************************!*\
1448 !*** ../core/common/assets/js/utils/helpers.js ***!
1449 \*************************************************/
1450 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1451
1452 "use strict";
1453
1454
1455 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1456 Object.defineProperty(exports, "__esModule", ({
1457 value: true
1458 }));
1459 exports["default"] = void 0;
1460 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1461 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1462 var Helpers = exports["default"] = /*#__PURE__*/function () {
1463 function Helpers() {
1464 (0, _classCallCheck2.default)(this, Helpers);
1465 }
1466 return (0, _createClass2.default)(Helpers, [{
1467 key: "consoleWarn",
1468 value:
1469 /**
1470 * @param {*} args
1471 * @deprecated since 3.7.0, use `elementorDevTools.consoleWarn()` instead.
1472 */
1473 function consoleWarn() {
1474 var _elementorDevTools;
1475 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
1476
1477 // This is is self is deprecated.
1478 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleWarn()', '3.7.0', 'elementorDevTools.consoleWarn()');
1479 }
1480
1481 /**
1482 * @param {string} message
1483 * @deprecated since 3.7.0, use `console.error()` instead.
1484 */
1485 }, {
1486 key: "consoleError",
1487 value: function consoleError(message) {
1488 // eslint-disable-next-line no-console
1489 console.error(message);
1490
1491 // This is is self is deprecated.
1492 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleError()', '3.7.0', 'console.error()');
1493 }
1494 }, {
1495 key: "cloneObject",
1496 value: function cloneObject(object) {
1497 return JSON.parse(JSON.stringify(object));
1498 }
1499 }, {
1500 key: "upperCaseWords",
1501 value: function upperCaseWords(string) {
1502 return (string + '').replace(/^(.)|\s+(.)/g, function ($1) {
1503 return $1.toUpperCase();
1504 });
1505 }
1506 }, {
1507 key: "getUniqueId",
1508 value: function getUniqueId() {
1509 return Math.random().toString(16).substr(2, 7);
1510 }
1511 }]);
1512 }();
1513
1514 /***/ }),
1515
1516 /***/ "../core/common/assets/js/utils/storage.js":
1517 /*!*************************************************!*\
1518 !*** ../core/common/assets/js/utils/storage.js ***!
1519 \*************************************************/
1520 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1521
1522 "use strict";
1523
1524
1525 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1526 Object.defineProperty(exports, "__esModule", ({
1527 value: true
1528 }));
1529 exports["default"] = void 0;
1530 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1531 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1532 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1533 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1534 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1535 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1536 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1537 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1538 function _default() {
1539 (0, _classCallCheck2.default)(this, _default);
1540 return _callSuper(this, _default, arguments);
1541 }
1542 (0, _inherits2.default)(_default, _elementorModules$Mod);
1543 return (0, _createClass2.default)(_default, [{
1544 key: "get",
1545 value: function get(key, options) {
1546 options = options || {};
1547 var storage;
1548 try {
1549 storage = options.session ? sessionStorage : localStorage;
1550 } catch (e) {
1551 return key ? undefined : {};
1552 }
1553 var elementorStorage = storage.getItem('elementor');
1554 if (elementorStorage) {
1555 elementorStorage = JSON.parse(elementorStorage);
1556 } else {
1557 elementorStorage = {};
1558 }
1559 if (!elementorStorage.__expiration) {
1560 elementorStorage.__expiration = {};
1561 }
1562 var expiration = elementorStorage.__expiration;
1563 var expirationToCheck = [];
1564 if (key) {
1565 if (expiration[key]) {
1566 expirationToCheck = [key];
1567 }
1568 } else {
1569 expirationToCheck = Object.keys(expiration);
1570 }
1571 var entryExpired = false;
1572 expirationToCheck.forEach(function (expirationKey) {
1573 if (new Date(expiration[expirationKey]) < new Date()) {
1574 delete elementorStorage[expirationKey];
1575 delete expiration[expirationKey];
1576 entryExpired = true;
1577 }
1578 });
1579 if (entryExpired) {
1580 this.save(elementorStorage, options.session);
1581 }
1582 if (key) {
1583 return elementorStorage[key];
1584 }
1585 return elementorStorage;
1586 }
1587 }, {
1588 key: "set",
1589 value: function set(key, value, options) {
1590 options = options || {};
1591 var elementorStorage = this.get(null, options);
1592 elementorStorage[key] = value;
1593 if (options.lifetimeInSeconds) {
1594 var date = new Date();
1595 date.setTime(date.getTime() + options.lifetimeInSeconds * 1000);
1596 elementorStorage.__expiration[key] = date.getTime();
1597 }
1598 this.save(elementorStorage, options.session);
1599 }
1600 }, {
1601 key: "save",
1602 value: function save(object, session) {
1603 var storage;
1604 try {
1605 storage = session ? sessionStorage : localStorage;
1606 } catch (e) {
1607 return;
1608 }
1609 storage.setItem('elementor', JSON.stringify(object));
1610 }
1611 }]);
1612 }(elementorModules.Module);
1613
1614 /***/ }),
1615
1616 /***/ "../core/common/modules/ajax/assets/js/ajax.js":
1617 /*!*****************************************************!*\
1618 !*** ../core/common/modules/ajax/assets/js/ajax.js ***!
1619 \*****************************************************/
1620 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1621
1622 "use strict";
1623
1624
1625 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1626 Object.defineProperty(exports, "__esModule", ({
1627 value: true
1628 }));
1629 exports["default"] = void 0;
1630 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
1631 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1632 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1633 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1634 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1635 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1636 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1637 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1638 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1639 function _default() {
1640 var _this;
1641 (0, _classCallCheck2.default)(this, _default);
1642 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1643 args[_key] = arguments[_key];
1644 }
1645 _this = _callSuper(this, _default, [].concat(args));
1646 _this.requests = {};
1647 _this.cache = {};
1648 _this.initRequestConstants();
1649 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
1650 return _this;
1651 }
1652 (0, _inherits2.default)(_default, _elementorModules$Mod);
1653 return (0, _createClass2.default)(_default, [{
1654 key: "getDefaultSettings",
1655 value: function getDefaultSettings() {
1656 return {
1657 ajaxParams: {
1658 type: 'POST',
1659 url: elementorCommon.config.ajax.url,
1660 data: {},
1661 dataType: 'json'
1662 },
1663 actionPrefix: 'elementor_'
1664 };
1665 }
1666 }, {
1667 key: "initRequestConstants",
1668 value: function initRequestConstants() {
1669 this.requestConstants = {
1670 _nonce: this.getSettings('nonce')
1671 };
1672 }
1673 }, {
1674 key: "addRequestConstant",
1675 value: function addRequestConstant(key, value) {
1676 this.requestConstants[key] = value;
1677 }
1678 }, {
1679 key: "getCacheKey",
1680 value: function getCacheKey(request) {
1681 return JSON.stringify({
1682 unique_id: request.unique_id,
1683 data: request.data
1684 });
1685 }
1686 }, {
1687 key: "loadObjects",
1688 value: function loadObjects(options) {
1689 var _this2 = this;
1690 var dataCollection = {};
1691 var deferredArray = [];
1692 if (options.before) {
1693 options.before();
1694 }
1695 options.ids.forEach(function (objectId) {
1696 deferredArray.push(_this2.load({
1697 action: options.action,
1698 unique_id: options.data.unique_id + objectId,
1699 data: jQuery.extend({
1700 id: objectId
1701 }, options.data)
1702 }).done(function (data) {
1703 return dataCollection = jQuery.extend(dataCollection, data);
1704 }));
1705 });
1706 jQuery.when.apply(jQuery, deferredArray).done(function () {
1707 return options.success(dataCollection);
1708 });
1709 }
1710 }, {
1711 key: "load",
1712 value: function load(request, immediately) {
1713 var _this3 = this;
1714 if (!request.unique_id) {
1715 request.unique_id = request.action;
1716 }
1717 if (request.before) {
1718 request.before();
1719 }
1720 var deferred;
1721 var cacheKey = this.getCacheKey(request);
1722 if (_.has(this.cache, cacheKey)) {
1723 deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
1724 } else {
1725 var _request$error;
1726 deferred = this.addRequest(request.action, {
1727 data: request.data,
1728 unique_id: request.unique_id,
1729 success: function success(data) {
1730 return _this3.cache[cacheKey] = data;
1731 },
1732 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function () {}
1733 }, immediately).done(request.success);
1734 }
1735 return deferred;
1736 }
1737 }, {
1738 key: "cancelRequest",
1739 value: function cancelRequest(requestId) {
1740 var request = this.requests[requestId];
1741 if (!request) {
1742 return null;
1743 }
1744 if (request.options.deferred.jqXhr) {
1745 return request.options.deferred.jqXhr.abort('Request canceled');
1746 }
1747 if (request.options.deferred) {
1748 return request.options.deferred.reject('Request canceled');
1749 }
1750 }
1751 }, {
1752 key: "addRequest",
1753 value: function addRequest(action, options, immediately) {
1754 options = options || {};
1755 if (!options.unique_id) {
1756 options.unique_id = action;
1757 }
1758 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
1759 var request = {
1760 action: action,
1761 options: options
1762 };
1763 if (immediately) {
1764 var requests = {};
1765 requests[options.unique_id] = request;
1766 options.deferred.jqXhr = this.sendBatch(requests);
1767 } else {
1768 this.requests[options.unique_id] = request;
1769 this.debounceSendBatch();
1770 }
1771 return options.deferred;
1772 }
1773 }, {
1774 key: "sendBatch",
1775 value: function sendBatch(requests) {
1776 var actions = {};
1777 if (!requests) {
1778 requests = this.requests;
1779
1780 // Empty for next batch.
1781 this.requests = {};
1782 }
1783 Object.entries(requests).forEach(function (_ref) {
1784 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
1785 id = _ref2[0],
1786 request = _ref2[1];
1787 return actions[id] = {
1788 action: request.action,
1789 data: request.options.data
1790 };
1791 });
1792 return this.send('ajax', {
1793 data: {
1794 actions: JSON.stringify(actions)
1795 },
1796 success: function success(data) {
1797 Object.entries(data.responses).forEach(function (_ref3) {
1798 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
1799 id = _ref4[0],
1800 response = _ref4[1];
1801 var options = requests[id].options;
1802 if (options) {
1803 if (response.success) {
1804 options.deferred.resolve(response.data);
1805 } else if (!response.success) {
1806 options.deferred.reject(response.data);
1807 }
1808 }
1809 });
1810 },
1811 error: function error(data) {
1812 return Object.values(requests).forEach(function (args) {
1813 if (args.options) {
1814 args.options.deferred.reject(data);
1815 }
1816 });
1817 }
1818 });
1819 }
1820 }, {
1821 key: "prepareSend",
1822 value: function prepareSend(action, options) {
1823 var _this4 = this;
1824 var settings = this.getSettings(),
1825 ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
1826 options = options || {};
1827 action = settings.actionPrefix + action;
1828 jQuery.extend(ajaxParams, options);
1829 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
1830 requestConstants.action = action;
1831 var isFormData = ajaxParams.data instanceof FormData;
1832 Object.entries(requestConstants).forEach(function (_ref5) {
1833 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
1834 key = _ref6[0],
1835 value = _ref6[1];
1836 if (isFormData) {
1837 ajaxParams.data.append(key, value);
1838 } else {
1839 ajaxParams.data[key] = value;
1840 }
1841 });
1842 var successCallback = ajaxParams.success,
1843 errorCallback = ajaxParams.error;
1844 if (successCallback || errorCallback) {
1845 ajaxParams.success = function (response) {
1846 if (response.success && successCallback) {
1847 successCallback(response.data);
1848 }
1849 if (!response.success && errorCallback) {
1850 errorCallback(response.data);
1851 }
1852 };
1853 if (errorCallback) {
1854 ajaxParams.error = function (data) {
1855 return errorCallback(data);
1856 };
1857 } else {
1858 ajaxParams.error = function (xmlHttpRequest) {
1859 if (xmlHttpRequest.readyState || 'abort' !== xmlHttpRequest.statusText) {
1860 _this4.trigger('request:unhandledError', xmlHttpRequest);
1861 }
1862 };
1863 }
1864 }
1865 return ajaxParams;
1866 }
1867 }, {
1868 key: "send",
1869 value: function send(action, options) {
1870 return jQuery.ajax(this.prepareSend(action, options));
1871 }
1872 }, {
1873 key: "addRequestCache",
1874 value: function addRequestCache(request, data) {
1875 var cacheKey = this.getCacheKey(request);
1876 this.cache[cacheKey] = data;
1877 }
1878 }, {
1879 key: "invalidateCache",
1880 value: function invalidateCache(request) {
1881 var cacheKey = this.getCacheKey(request);
1882 delete this.cache[cacheKey];
1883 }
1884 }]);
1885 }(elementorModules.Module);
1886
1887 /***/ }),
1888
1889 /***/ "../core/common/modules/connect/assets/js/connect.js":
1890 /*!***********************************************************!*\
1891 !*** ../core/common/modules/connect/assets/js/connect.js ***!
1892 \***********************************************************/
1893 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1894
1895 "use strict";
1896 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1897
1898
1899 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1900 Object.defineProperty(exports, "__esModule", ({
1901 value: true
1902 }));
1903 exports["default"] = void 0;
1904 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1905 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1906 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1907 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1908 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1909 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1910 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1911 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1912 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
1913 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Vie) {
1914 function _default() {
1915 (0, _classCallCheck2.default)(this, _default);
1916 return _callSuper(this, _default, arguments);
1917 }
1918 (0, _inherits2.default)(_default, _elementorModules$Vie);
1919 return (0, _createClass2.default)(_default, [{
1920 key: "addPopupPlugin",
1921 value: function addPopupPlugin() {
1922 var counter = 0;
1923 jQuery.fn.elementorConnect = function (options) {
1924 var _this = this;
1925 // Open the Connect Dialog in a popup window.
1926 if (options !== null && options !== void 0 && options.popup) {
1927 jQuery(this).on('click', function (event) {
1928 var _options$popup, _options$popup2;
1929 event.preventDefault();
1930 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600,
1931 height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
1932 window.open(jQuery(_this).attr('href') + '&mode=popup', 'elementorConnect', "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
1933 });
1934 delete options.popup;
1935 }
1936 var settings = jQuery.extend({
1937 // These are the defaults.
1938 success: function success() {
1939 return location.reload();
1940 },
1941 error: function error() {
1942 elementor.notifications.showToast({
1943 message: __('Unable to connect', 'elementor')
1944 });
1945 },
1946 parseUrl: function parseUrl(url) {
1947 return url;
1948 } // Allow to change the url, e.g: replace placeholders like '%%template_type%%' with actual value.
1949 }, options);
1950 this.each(function () {
1951 counter++;
1952 var $this = jQuery(this),
1953 callbackId = 'cb' + counter;
1954 $this.attr({
1955 target: '_blank',
1956 rel: 'opener',
1957 href: settings.parseUrl($this.attr('href') + '&mode=popup&callback_id=' + callbackId)
1958 });
1959 elementorCommon.elements.$window.on('elementor/connect/success/' + callbackId, settings.success).on('elementor/connect/error/' + callbackId, settings.error);
1960 });
1961 return this;
1962 };
1963 }
1964 }, {
1965 key: "getDefaultSettings",
1966 value: function getDefaultSettings() {
1967 return {
1968 selectors: {
1969 connectButton: '#elementor-template-library-connect__button'
1970 }
1971 };
1972 }
1973 }, {
1974 key: "getDefaultElements",
1975 value: function getDefaultElements() {
1976 return {
1977 $connectButton: jQuery(this.getSettings('selectors.connectButton'))
1978 };
1979 }
1980 }, {
1981 key: "applyPopup",
1982 value: function applyPopup() {
1983 this.elements.$connectButton.elementorConnect();
1984 }
1985 }, {
1986 key: "onInit",
1987 value: function onInit() {
1988 _superPropGet(_default, "onInit", this, 3)([]);
1989 this.addPopupPlugin();
1990 this.applyPopup();
1991 }
1992 }]);
1993 }(elementorModules.ViewModule);
1994
1995 /***/ }),
1996
1997 /***/ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js":
1998 /*!**********************************************************************************!*\
1999 !*** ../core/common/modules/event-tracker/assets/js/data/commands-data/index.js ***!
2000 \**********************************************************************************/
2001 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2002
2003 "use strict";
2004
2005
2006 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2007 Object.defineProperty(exports, "__esModule", ({
2008 value: true
2009 }));
2010 exports.Index = void 0;
2011 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2012 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2013 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2014 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2015 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2016 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
2017 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2018 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2019 var Index = exports.Index = /*#__PURE__*/function (_CommandData) {
2020 function Index() {
2021 (0, _classCallCheck2.default)(this, Index);
2022 return _callSuper(this, Index, arguments);
2023 }
2024 (0, _inherits2.default)(Index, _CommandData);
2025 return (0, _createClass2.default)(Index, null, [{
2026 key: "getEndpointFormat",
2027 value: function getEndpointFormat() {
2028 return 'send-event';
2029 }
2030 }]);
2031 }(_commandData.default);
2032
2033 /***/ }),
2034
2035 /***/ "../core/common/modules/event-tracker/assets/js/data/component.js":
2036 /*!************************************************************************!*\
2037 !*** ../core/common/modules/event-tracker/assets/js/data/component.js ***!
2038 \************************************************************************/
2039 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2040
2041 "use strict";
2042
2043
2044 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2045 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2046 Object.defineProperty(exports, "__esModule", ({
2047 value: true
2048 }));
2049 exports["default"] = void 0;
2050 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2051 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2052 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2053 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2054 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2055 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
2056 var commandsData = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js"));
2057 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
2058 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2059 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2060 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
2061 function Component() {
2062 (0, _classCallCheck2.default)(this, Component);
2063 return _callSuper(this, Component, arguments);
2064 }
2065 (0, _inherits2.default)(Component, _ComponentBase);
2066 return (0, _createClass2.default)(Component, [{
2067 key: "getNamespace",
2068 value: function getNamespace() {
2069 return 'event-tracker';
2070 }
2071 }, {
2072 key: "defaultData",
2073 value: function defaultData() {
2074 return this.importCommands(commandsData);
2075 }
2076 }]);
2077 }(_componentBase.default);
2078
2079 /***/ }),
2080
2081 /***/ "../core/common/modules/event-tracker/assets/js/events.js":
2082 /*!****************************************************************!*\
2083 !*** ../core/common/modules/event-tracker/assets/js/events.js ***!
2084 \****************************************************************/
2085 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2086
2087 "use strict";
2088
2089
2090 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2091 Object.defineProperty(exports, "__esModule", ({
2092 value: true
2093 }));
2094 exports["default"] = void 0;
2095 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2096 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2097 var _time = _interopRequireDefault(__webpack_require__(/*! elementor-utils/time */ "../assets/dev/js/utils/time.js"));
2098 var Events = exports["default"] = /*#__PURE__*/function () {
2099 function Events() {
2100 (0, _classCallCheck2.default)(this, Events);
2101 }
2102 return (0, _createClass2.default)(Events, [{
2103 key: "dispatchEvent",
2104 value: function dispatchEvent(eventData) {
2105 if (!eventData) {
2106 return;
2107 }
2108 eventData.ts = (0, _time.default)();
2109
2110 // No need to wait for response, no need to block browser in any way.
2111 $e.data.create('event-tracker/index', {
2112 event_data: eventData
2113 });
2114 }
2115 }]);
2116 }();
2117
2118 /***/ }),
2119
2120 /***/ "../core/common/modules/events-manager/assets/js/events-config.js":
2121 /*!************************************************************************!*\
2122 !*** ../core/common/modules/events-manager/assets/js/events-config.js ***!
2123 \************************************************************************/
2124 /***/ ((__unused_webpack_module, exports) => {
2125
2126 "use strict";
2127
2128
2129 Object.defineProperty(exports, "__esModule", ({
2130 value: true
2131 }));
2132 exports["default"] = void 0;
2133 var eventsConfig = {
2134 appTypes: {
2135 editor: 'editor',
2136 wpAdmin: 'wpadmin'
2137 },
2138 targetTypes: {
2139 dropdownItem: 'dropdown_item',
2140 button: 'button',
2141 tab: 'tab',
2142 toggle: 'toggle',
2143 searchInput: 'search_input',
2144 searchResult: 'search_result',
2145 buttons: 'buttons',
2146 searchWidget: 'search_widget'
2147 },
2148 interactionResults: {
2149 actionSelected: 'action_selected',
2150 navigate: 'navigate',
2151 create: 'create',
2152 sessionEnd: 'session_end',
2153 tabChanged: 'tab_changed',
2154 assetInserted: 'asset_inserted',
2155 assetFavorite: 'asset_favorite',
2156 aiGenerate: 'ai_generate',
2157 resultsUpdated: 'results_updated',
2158 noResults: 'no_results',
2159 selected: 'selected',
2160 promotionViewed: 'promotion_viewed',
2161 upgradeNow: 'upgrade_now'
2162 },
2163 targetNames: {
2164 publishDropdown: {
2165 saveDraft: 'save_draft',
2166 saveAsTemplate: 'save_as_template',
2167 viewPage: 'view_page',
2168 copyAndShare: 'copy_and_share'
2169 },
2170 pageList: {
2171 addNewPage: 'add_new_page'
2172 }
2173 },
2174 triggers: {
2175 click: 'Click',
2176 rightClick: 'Right Click',
2177 doubleClick: 'Double Click',
2178 accordionClick: 'Accordion Click',
2179 toggleClick: 'Toggle Click',
2180 dropdownClick: 'Click Dropdown',
2181 editorLoaded: 'Editor Loaded',
2182 visible: 'Visible',
2183 pageLoaded: 'Page Loaded',
2184 typing: 'Typing',
2185 tabSelect: 'Tab Select',
2186 insert: 'Insert'
2187 },
2188 locations: {
2189 widgetPanel: 'Widget Panel',
2190 topBar: 'Top Bar',
2191 sidebar: 'Sidebar',
2192 elementorEditor: 'Elementor Editor',
2193 templatesLibrary: {
2194 library: 'Templates Library'
2195 },
2196 app: {
2197 import: 'Import Kit',
2198 export: 'Export Kit',
2199 kitLibrary: 'Kit Library',
2200 cloudKitLibrary: 'Cloud Kit Library'
2201 },
2202 variables: 'Variables Panel',
2203 variablesManager: 'Variables Manager',
2204 admin: 'WP admin',
2205 structurePanel: 'Structure Panel',
2206 canvas: 'Canvas',
2207 leftPanel: 'Left Panel',
2208 elementorLibrary: 'Elementor Library',
2209 components: {
2210 instanceEditingPanel: 'Instance Editing Panel'
2211 }
2212 },
2213 secondaryLocations: {
2214 layout: 'Layout Section',
2215 basic: 'Basic Section',
2216 'pro-elements': 'Pro Section',
2217 general: 'General Section',
2218 'theme-elements': 'Site Section',
2219 'theme-elements-single': 'Single Section',
2220 'woocommerce-elements': 'WooCommerce Section',
2221 wordpress: 'WordPress Section',
2222 categories: 'Widgets Tab',
2223 global: 'Globals Tab',
2224 'whats-new': 'What\'s New',
2225 'document-settings': 'Document Settings icon',
2226 'preview-page': 'Preview Page',
2227 'publish-button': 'Publish Button',
2228 'widget-panel': 'Widget Panel Icon',
2229 finder: 'Finder',
2230 help: 'Help',
2231 elementorLogoDropdown: 'top_bar_elementor_logo_dropdown',
2232 elementorLogo: 'Elementor Logo',
2233 eLogoMenu: 'E-logo Menu',
2234 notes: 'Notes',
2235 siteSettings: 'Site Settings',
2236 structure: 'Structure',
2237 documentNameDropdown: 'Document Name dropdown',
2238 responsiveControls: 'Responsive controls',
2239 launchpad: 'launchpad',
2240 checklistHeader: 'Checklist Header',
2241 checklistSteps: 'Checklist Steps',
2242 userPreferences: 'User Preferences',
2243 contextMenu: 'Context Menu',
2244 templateLibrary: {
2245 saveModal: 'Save to Modal',
2246 moveModal: 'Move to Modal',
2247 bulkMoveModal: 'Bulk Move to Modal',
2248 copyModal: 'Copy to Modal',
2249 bulkCopyModal: 'Bulk Copy to Modal',
2250 saveModalSelectFolder: 'Save to Modal - select folder',
2251 saveModalSelectConnect: 'Save to Modal - connect',
2252 saveModalSelectUpgrade: 'Save to Modal - upgrade',
2253 importModal: 'Import Modal',
2254 newFolderModal: 'New Folder Modal',
2255 deleteDialog: 'Delete Dialog',
2256 deleteFolderDialog: 'Delete Folder Dialog',
2257 renameDialog: 'Rename Dialog',
2258 createFolderDialog: 'Create Folder Dialog',
2259 applySettingsDialog: 'Apply Settings Dialog',
2260 cloudTab: 'Cloud Tab',
2261 siteTab: 'Site Tab',
2262 cloudTabFolder: 'Cloud Tab - Folder',
2263 cloudTabConnect: 'Cloud Tab - Connect',
2264 cloudTabUpgrade: 'Cloud Tab - Upgrade',
2265 morePopup: 'Context Menu',
2266 quotaBar: 'Quota Bar'
2267 },
2268 kitLibrary: {
2269 cloudKitLibrary: 'kits_cloud_library',
2270 cloudKitLibraryConnect: 'kits_cloud_library_connect',
2271 cloudKitLibraryUpgrade: 'kits_cloud_library_upgrade',
2272 kitExportCustomization: 'kit_export_customization',
2273 kitExport: 'kit_export',
2274 kitExportCustomizationEdit: 'kit_export_customization_edit',
2275 kitExportSummary: 'kit_export_summary',
2276 kitImportUploadBox: 'kit_import_upload_box',
2277 kitImportCustomization: 'kit_import_customization',
2278 kitImportSummary: 'kit_import_summary'
2279 },
2280 variablesPopover: 'Variables Popover',
2281 admin: {
2282 pluginToolsTab: 'plugin_tools_tab',
2283 pluginWebsiteTemplatesTab: 'plugin_website_templates_tab'
2284 },
2285 componentsTab: 'Components Tab',
2286 canvasElement: 'Canvas Element',
2287 publishDropdown: 'Publish Dropdown',
2288 pageListDropdown: 'Page List Dropdown',
2289 emptyBox: 'Empty Box',
2290 searchBar: 'Search Bar',
2291 finderResults: 'Finder Results',
2292 libraryTabs: 'Library Tabs',
2293 assetCard: 'Asset Card'
2294 },
2295 elements: {
2296 accordionSection: 'Accordion section',
2297 buttonIcon: 'Button Icon',
2298 mainCta: 'Main CTA',
2299 button: 'Button',
2300 link: 'Link',
2301 dropdown: 'Dropdown',
2302 toggle: 'Toggle',
2303 launchpadChecklist: 'Checklist popup'
2304 },
2305 names: {
2306 v1: {
2307 layout: 'v1_widgets_tab_layout_section',
2308 basic: 'v1_widgets_tab_basic_section',
2309 'pro-elements': 'v1_widgets_tab_pro_section',
2310 general: 'v1_widgets_tab_general_section',
2311 'theme-elements': 'v1_widgets_tab_site_section',
2312 'theme-elements-single': 'v1_widgets_tab_single_section',
2313 'woocommerce-elements': 'v1_widgets_tab_woocommerce_section',
2314 wordpress: 'v1_widgets_tab_wordpress_section',
2315 categories: 'v1_widgets_tab',
2316 global: 'v1_globals_tab'
2317 },
2318 topBar: {
2319 whatsNew: 'top_bar_whats_new',
2320 documentSettings: 'top_bar_document_settings_icon',
2321 previewPage: 'top_bar_preview_page',
2322 publishButton: 'top_bar_publish_button',
2323 widgetPanel: 'top_bar_widget_panel_icon',
2324 finder: 'top_bar_finder',
2325 help: 'top_bar_help',
2326 history: 'top_bar_elementor_logo_dropdown_history',
2327 userPreferences: 'top_bar_elementor_logo_dropdown_user_preferences',
2328 keyboardShortcuts: 'top_bar_elementor_logo_dropdown_keyboard_shortcuts',
2329 exitToWordpress: 'top_bar_elementor_logo_dropdown_exit_to_wordpress',
2330 themeBuilder: 'top_bar_elementor_logo_dropdown_theme_builder',
2331 notes: 'top_bar_notes',
2332 siteSettings: 'top_bar_site_setting',
2333 structure: 'top_bar_structure',
2334 documentNameDropdown: 'top_bar_document_name_dropdown',
2335 responsiveControls: 'top_bar_responsive_controls',
2336 launchpadOn: 'top_bar_checklist_icon_show',
2337 launchpadOff: 'top_bar_checklist_icon_hide',
2338 elementorLogoDropdown: 'open_e_menu',
2339 connectAccount: 'connect_account',
2340 accountConnected: 'account_connected'
2341 },
2342 // ChecklistSteps event names are generated dynamically, based on stepId and action type taken: title, action, done, undone, upgrade
2343 elementorEditor: {
2344 editorLoaded: 'editor_loaded',
2345 checklist: {
2346 checklistHeaderClose: 'checklist_header_close_icon',
2347 checklistFirstPopup: 'checklist popup triggered'
2348 },
2349 userPreferences: {
2350 checklistShow: 'checklist_userpreferences_toggle_show',
2351 checklistHide: 'checklist_userpreferences_toggle_hide'
2352 }
2353 },
2354 variables: {
2355 open: 'open_variables_popover',
2356 add: 'add_new_variable',
2357 connect: 'connect_variable',
2358 save: 'save_new_variable',
2359 openManager: 'open_variables_manager',
2360 saveChanges: 'save_variables_changes',
2361 delete: 'delete_variable',
2362 variableSyncToV3: 'variable_sync_to_v3'
2363 },
2364 design_system: {
2365 importOpened: 'design_system_import_opened',
2366 fileSelected: 'design_system_file_selected',
2367 validationFailed: 'design_system_validation_failed',
2368 conflictChoice: 'design_system_conflict_choice',
2369 confirmed: 'design_system_import_confirmed',
2370 imported: 'design_system_imported',
2371 importFailed: 'design_system_import_failed'
2372 },
2373 components: {
2374 createClicked: 'component_create_clicked',
2375 createCancelled: 'component_creation_cancelled',
2376 created: 'component_created',
2377 instanceAdded: 'component_instance_added',
2378 edited: 'component_edited',
2379 propertiesPanelOpened: 'component_properties_panel_opened',
2380 propertiesGroupCreated: 'component_properties_group_created',
2381 propertyExposed: 'component_property_exposed',
2382 propertyRemoved: 'component_property_removed',
2383 detached: 'component_detached'
2384 },
2385 global_classes: {
2386 classApplied: 'class_applied',
2387 classRemoved: 'class_removed',
2388 classManagerFilterCleared: 'class_manager_filter_cleared',
2389 classDeleted: 'class_deleted',
2390 classPublishConflict: 'class_publish_conflict',
2391 classRenamed: 'class_renamed',
2392 classCreated: 'class_created',
2393 classManagerSearched: 'class_manager_searched',
2394 classManagerFiltersOpened: 'class_manager_filters_opened',
2395 classManagerOpened: 'class_manager_opened',
2396 classManagerReorder: 'class_manager_reorder',
2397 classManagerFilterUsed: 'class_manager_filter_used',
2398 classUsageLocate: 'class_usage_locate',
2399 classUsageHovered: 'class_usage_hovered',
2400 classStyled: 'class_styled',
2401 classStateClicked: 'class_state_clicked',
2402 classUsageClicked: 'class_usage_clicked',
2403 classDuplicate: 'class_duplicate',
2404 classSyncToV3PopupShown: 'class_sync_to_v3_popup_shown',
2405 classSyncToV3: 'class_sync_to_v3',
2406 classSyncToV3PopupClick: 'class_sync_to_v3_popup_click'
2407 },
2408 editorOne: {
2409 topBarPublishDropdown: 'top_bar_publish_dropdown',
2410 topBarPageList: 'top_bar_page_list',
2411 siteSettingsSession: 'site_settings_session',
2412 eLibraryNav: 'e_library_nav',
2413 eLibraryInsert: 'e_library_insert',
2414 eLibraryFavorite: 'e_library_favorite',
2415 eLibraryGenerateAi: 'e_library_generate_ai',
2416 finderSearchInput: 'finder_search_input',
2417 finderResultSelect: 'finder_result_select',
2418 canvasEmptyBoxAction: 'canvas_empty_box_action',
2419 widgetPanelSearch: 'widget_panel_search'
2420 },
2421 interactions: {
2422 created: 'interactions_created'
2423 },
2424 promotions: {
2425 viewPromotion: 'view_promotion',
2426 upgradePromotionClick: 'upgrade_promotion_click'
2427 }
2428 }
2429 };
2430 var _default = exports["default"] = eventsConfig;
2431
2432 /***/ }),
2433
2434 /***/ "../core/common/modules/events-manager/assets/js/module.js":
2435 /*!*****************************************************************!*\
2436 !*** ../core/common/modules/events-manager/assets/js/module.js ***!
2437 \*****************************************************************/
2438 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2439
2440 "use strict";
2441
2442
2443 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2444 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2445 Object.defineProperty(exports, "__esModule", ({
2446 value: true
2447 }));
2448 exports["default"] = void 0;
2449 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
2450 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
2451 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2452 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2453 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2454 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2455 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2456 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2457 var _eventsConfig = _interopRequireDefault(__webpack_require__(/*! ./events-config */ "../core/common/modules/events-manager/assets/js/events-config.js"));
2458 var _mixpanelBrowser = _interopRequireWildcard(__webpack_require__(/*! mixpanel-browser */ "../node_modules/mixpanel-browser/dist/mixpanel.module.js"));
2459 var _tiers = __webpack_require__(/*! elementor-utils/tiers */ "../assets/dev/js/utils/tiers.js");
2460 var _sessionRecording = __webpack_require__(/*! ./session-recording */ "../core/common/modules/events-manager/assets/js/session-recording.js");
2461 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t2 in e) "default" !== _t2 && {}.hasOwnProperty.call(e, _t2) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t2)) && (i.get || i.set) ? o(f, _t2, i) : f[_t2] = e[_t2]); return f; })(e, t); }
2462 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2463 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2464 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2465 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2466 /** @type {Mixpanel | null} */
2467 var mixpanelInstance = null;
2468 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
2469 function _default() {
2470 var _this;
2471 (0, _classCallCheck2.default)(this, _default);
2472 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2473 args[_key] = arguments[_key];
2474 }
2475 _this = _callSuper(this, _default, [].concat(args));
2476 (0, _defineProperty2.default)(_this, "trackingEnabled", false);
2477 (0, _defineProperty2.default)(_this, "availableExperiments", []);
2478 return _this;
2479 }
2480 (0, _inherits2.default)(_default, _elementorModules$Mod);
2481 return (0, _createClass2.default)(_default, [{
2482 key: "onInit",
2483 value: function onInit() {
2484 var _elementorCommon$conf,
2485 _this2 = this;
2486 this.config = _eventsConfig.default;
2487 if (!this.canSendEvents()) {
2488 return;
2489 }
2490 (0, _sessionRecording.configureSessionRecording)((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.session_recording_events);
2491 this.initializeMixpanel(function () {
2492 return _this2.enableTracking();
2493 });
2494 }
2495 }, {
2496 key: "initializeMixpanel",
2497 value: function initializeMixpanel(onLoaded) {
2498 if (mixpanelInstance && mixpanelInstance.isInitialized) {
2499 onLoaded(mixpanelInstance);
2500 } else {
2501 var _elementorCommon$conf2;
2502 mixpanelInstance = _mixpanelBrowser.default.init((_elementorCommon$conf2 = elementorCommon.config.editor_events) === null || _elementorCommon$conf2 === void 0 ? void 0 : _elementorCommon$conf2.token, {
2503 persistence: 'localStorage',
2504 autocapture: false,
2505 flags: true,
2506 api_hosts: {
2507 flags: 'https://api-eu.mixpanel.com'
2508 },
2509 loaded: onLoaded,
2510 record_sessions_percent: 0,
2511 record_idle_timeout_ms: 60 * 1000,
2512 // 60 Seconds
2513 record_min_ms: 5 * 1000,
2514 // 5 Seconds
2515 record_max_ms: 30 * 1000,
2516 // 30 Seconds
2517 record_mask_text_selector: ''
2518 }, 'elementor-editor');
2519 }
2520 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
2521 }
2522 }, {
2523 key: "enableTracking",
2524 value: function enableTracking() {
2525 var _elementorCommon$conf3;
2526 if (!this.isMixpanelReady()) {
2527 return;
2528 }
2529 var userId = (_elementorCommon$conf3 = elementorCommon.config.editor_events) === null || _elementorCommon$conf3 === void 0 ? void 0 : _elementorCommon$conf3.user_id;
2530 mixpanelInstance.register({
2531 appType: 'Editor'
2532 });
2533 if (userId) {
2534 var _elementorCommon$conf4;
2535 mixpanelInstance.identify(userId);
2536 mixpanelInstance.people.set_once({
2537 $user_id: userId,
2538 $last_login: new Date().toISOString(),
2539 $plan_type: ((_elementorCommon$conf4 = elementorCommon.config.library_connect) === null || _elementorCommon$conf4 === void 0 ? void 0 : _elementorCommon$conf4.plan_type) || _tiers.TIERS.free
2540 });
2541 }
2542 this.trackingEnabled = true;
2543 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
2544 }
2545 }, {
2546 key: "dispatchEvent",
2547 value: function dispatchEvent(name, data) {
2548 var _elementorCommon$conf5, _elementorCommon$conf6, _elementorCommon$conf7, _elementorCommon$conf8, _elementorCommon$conf9, _elementorCommon$conf0, _elementorCommon$conf1, _elementorCommon$conf10, _elementorCommon$conf11;
2549 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2550 if (!this.canSendEvents()) {
2551 return;
2552 }
2553 if (!this.trackingEnabled) {
2554 this.enableTracking();
2555 }
2556 var eventData = _objectSpread({
2557 user_id: ((_elementorCommon$conf5 = elementorCommon.config.editor_events) === null || _elementorCommon$conf5 === void 0 ? void 0 : _elementorCommon$conf5.user_id) || null,
2558 user_roles: ((_elementorCommon$conf6 = elementorCommon.config.library_connect) === null || _elementorCommon$conf6 === void 0 ? void 0 : _elementorCommon$conf6.user_roles) || [],
2559 subscription_id: ((_elementorCommon$conf7 = elementorCommon.config.editor_events) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.subscription_id) || null,
2560 user_tier: ((_elementorCommon$conf8 = elementorCommon.config.library_connect) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.current_access_tier) || null,
2561 url: (_elementorCommon$conf9 = elementorCommon.config.editor_events) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.site_url,
2562 wp_version: (_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.wp_version,
2563 client_id: (_elementorCommon$conf1 = elementorCommon.config.editor_events) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.site_key,
2564 app_version: (_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.elementor_version,
2565 site_language: (_elementorCommon$conf11 = elementorCommon.config.editor_events) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.site_language,
2566 experiments: this.availableExperiments
2567 }, data);
2568 mixpanelInstance.track(name, eventData, options);
2569 var recordingDecision = (0, _sessionRecording.handleSessionRecording)(name, mixpanelInstance);
2570 if (recordingDecision) {
2571 mixpanelInstance.track(recordingDecision, eventData);
2572 }
2573 }
2574 }, {
2575 key: "featureFlagIsActive",
2576 value: function () {
2577 var _featureFlagIsActive = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(flagName) {
2578 var _mixpanelInstance;
2579 var isEnabled;
2580 return _regenerator.default.wrap(function (_context) {
2581 while (1) switch (_context.prev = _context.next) {
2582 case 0:
2583 if (!('function' !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
2584 _context.next = 1;
2585 break;
2586 }
2587 return _context.abrupt("return", false);
2588 case 1:
2589 _context.next = 2;
2590 return mixpanelInstance.flags.is_enabled(flagName, false);
2591 case 2:
2592 isEnabled = _context.sent;
2593 return _context.abrupt("return", true === isEnabled);
2594 case 3:
2595 case "end":
2596 return _context.stop();
2597 }
2598 }, _callee);
2599 }));
2600 function featureFlagIsActive(_x) {
2601 return _featureFlagIsActive.apply(this, arguments);
2602 }
2603 return featureFlagIsActive;
2604 }()
2605 }, {
2606 key: "getExperimentVariant",
2607 value: function () {
2608 var _getExperimentVariant = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2(experimentName) {
2609 var defaultValue,
2610 _elementorCommon$conf12,
2611 _elementorCommon$conf13,
2612 isAbTestingEnabled,
2613 variant,
2614 _args2 = arguments,
2615 _t;
2616 return _regenerator.default.wrap(function (_context2) {
2617 while (1) switch (_context2.prev = _context2.next) {
2618 case 0:
2619 defaultValue = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 'control';
2620 _context2.prev = 1;
2621 if (this.canSendEvents()) {
2622 _context2.next = 2;
2623 break;
2624 }
2625 return _context2.abrupt("return", defaultValue);
2626 case 2:
2627 isAbTestingEnabled = (_elementorCommon$conf12 = (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.flags_enabled) !== null && _elementorCommon$conf12 !== void 0 ? _elementorCommon$conf12 : false;
2628 if (isAbTestingEnabled) {
2629 _context2.next = 3;
2630 break;
2631 }
2632 return _context2.abrupt("return", defaultValue);
2633 case 3:
2634 if (mixpanelInstance) {
2635 _context2.next = 4;
2636 break;
2637 }
2638 return _context2.abrupt("return", defaultValue);
2639 case 4:
2640 if (!this.trackingEnabled) {
2641 this.enableTracking();
2642 }
2643 if (mixpanelInstance.flags) {
2644 _context2.next = 5;
2645 break;
2646 }
2647 return _context2.abrupt("return", defaultValue);
2648 case 5:
2649 if (!('function' !== typeof mixpanelInstance.flags.get_variant_value)) {
2650 _context2.next = 6;
2651 break;
2652 }
2653 return _context2.abrupt("return", defaultValue);
2654 case 6:
2655 _context2.next = 7;
2656 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
2657 case 7:
2658 variant = _context2.sent;
2659 if (!(undefined === variant || null === variant)) {
2660 _context2.next = 8;
2661 break;
2662 }
2663 return _context2.abrupt("return", defaultValue);
2664 case 8:
2665 return _context2.abrupt("return", variant);
2666 case 9:
2667 _context2.prev = 9;
2668 _t = _context2["catch"](1);
2669 return _context2.abrupt("return", defaultValue);
2670 case 10:
2671 case "end":
2672 return _context2.stop();
2673 }
2674 }, _callee2, this, [[1, 9]]);
2675 }));
2676 function getExperimentVariant(_x2) {
2677 return _getExperimentVariant.apply(this, arguments);
2678 }
2679 return getExperimentVariant;
2680 }()
2681 }, {
2682 key: "startExperiment",
2683 value: function startExperiment(experimentName, experimentVariant) {
2684 if (!this.trackingEnabled) {
2685 return;
2686 }
2687 mixpanelInstance.track('$experiment_started', {
2688 'Experiment name': experimentName,
2689 'Variant name': experimentVariant
2690 });
2691 }
2692 }, {
2693 key: "isMixpanelReady",
2694 value: function isMixpanelReady() {
2695 if ('undefined' === typeof mixpanelInstance || !mixpanelInstance) {
2696 return false;
2697 }
2698 try {
2699 var distinctId = mixpanelInstance.get_distinct_id();
2700 return distinctId !== undefined && distinctId !== null;
2701 } catch (error) {
2702 return false;
2703 }
2704 }
2705 }, {
2706 key: "canSendEvents",
2707 value: function canSendEvents() {
2708 var _elementorCommon;
2709 return !!((_elementorCommon = elementorCommon) !== null && _elementorCommon !== void 0 && (_elementorCommon = _elementorCommon.config) !== null && _elementorCommon !== void 0 && (_elementorCommon = _elementorCommon.editor_events) !== null && _elementorCommon !== void 0 && _elementorCommon.can_send_events);
2710 }
2711 }, {
2712 key: "getMixpanelInstance",
2713 value: function getMixpanelInstance() {
2714 return this.isMixpanelReady() ? mixpanelInstance : undefined;
2715 }
2716 }]);
2717 }(elementorModules.Module);
2718
2719 /***/ }),
2720
2721 /***/ "../core/common/modules/events-manager/assets/js/session-recording.js":
2722 /*!****************************************************************************!*\
2723 !*** ../core/common/modules/events-manager/assets/js/session-recording.js ***!
2724 \****************************************************************************/
2725 /***/ ((__unused_webpack_module, exports) => {
2726
2727 "use strict";
2728
2729
2730 Object.defineProperty(exports, "__esModule", ({
2731 value: true
2732 }));
2733 exports.configureSessionRecording = configureSessionRecording;
2734 exports.getIsRecording = getIsRecording;
2735 exports.handleSessionRecording = handleSessionRecording;
2736 var RECORD_SESSION_PERCENT = 1;
2737 var sessionRecordingPairs = [];
2738 var activeEndEvent = null;
2739 var isRecording = false;
2740 function shouldRecordSession(distinctId, percent) {
2741 var fraction = Math.min(Math.max(percent / 100, 0), 1);
2742 var hash = 0;
2743 for (var i = 0; i < distinctId.length; i++) {
2744 // eslint-disable-next-line no-bitwise
2745 hash = hash * 31 + distinctId.charCodeAt(i) >>> 0;
2746 }
2747 return hash / 4294967295 < fraction;
2748 }
2749
2750 /**
2751 * @param {Array<{start: string, end?: string|null}>} pairs
2752 */
2753 function configureSessionRecording(pairs) {
2754 if (!Array.isArray(pairs)) {
2755 return;
2756 }
2757 sessionRecordingPairs = pairs.filter(function (pair) {
2758 return 'string' === typeof (pair === null || pair === void 0 ? void 0 : pair.start) && pair.start;
2759 });
2760 }
2761
2762 /**
2763 * Evaluates whether to start/stop recording based on the event name.
2764 *
2765 * @param {string} name
2766 * @param {import('mixpanel-browser').Mixpanel} mixpanelInstance
2767 * @return {'recording_started'|'recording_skipped'|'recording_stopped'|null} The recording decision, or null if no action taken.
2768 */
2769 function handleSessionRecording(name, mixpanelInstance) {
2770 var matchedPair = sessionRecordingPairs.find(function (pair) {
2771 return pair.start === name;
2772 });
2773 if (matchedPair) {
2774 var distinctId = mixpanelInstance.get_distinct_id();
2775 if (shouldRecordSession(distinctId, RECORD_SESSION_PERCENT)) {
2776 var _matchedPair$end;
2777 mixpanelInstance.start_session_recording();
2778 isRecording = true;
2779 activeEndEvent = (_matchedPair$end = matchedPair.end) !== null && _matchedPair$end !== void 0 ? _matchedPair$end : null;
2780 return 'recording_started';
2781 }
2782 isRecording = false;
2783 activeEndEvent = null;
2784 return 'recording_skipped';
2785 }
2786 if (activeEndEvent && name === activeEndEvent) {
2787 mixpanelInstance.stop_session_recording();
2788 isRecording = false;
2789 activeEndEvent = null;
2790 return 'recording_stopped';
2791 }
2792 return null;
2793 }
2794 function getIsRecording() {
2795 return isRecording;
2796 }
2797
2798 /***/ }),
2799
2800 /***/ "../core/common/modules/finder/assets/js/commands/index.js":
2801 /*!*****************************************************************!*\
2802 !*** ../core/common/modules/finder/assets/js/commands/index.js ***!
2803 \*****************************************************************/
2804 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2805
2806 "use strict";
2807
2808
2809 Object.defineProperty(exports, "__esModule", ({
2810 value: true
2811 }));
2812 Object.defineProperty(exports, "NavigateDown", ({
2813 enumerable: true,
2814 get: function get() {
2815 return _navigateDown.NavigateDown;
2816 }
2817 }));
2818 Object.defineProperty(exports, "NavigateSelect", ({
2819 enumerable: true,
2820 get: function get() {
2821 return _navigateSelect.NavigateSelect;
2822 }
2823 }));
2824 Object.defineProperty(exports, "NavigateUp", ({
2825 enumerable: true,
2826 get: function get() {
2827 return _navigateUp.NavigateUp;
2828 }
2829 }));
2830 var _navigateDown = __webpack_require__(/*! ./navigate-down */ "../core/common/modules/finder/assets/js/commands/navigate-down.js");
2831 var _navigateSelect = __webpack_require__(/*! ./navigate-select */ "../core/common/modules/finder/assets/js/commands/navigate-select.js");
2832 var _navigateUp = __webpack_require__(/*! ./navigate-up */ "../core/common/modules/finder/assets/js/commands/navigate-up.js");
2833
2834 /***/ }),
2835
2836 /***/ "../core/common/modules/finder/assets/js/commands/navigate-down.js":
2837 /*!*************************************************************************!*\
2838 !*** ../core/common/modules/finder/assets/js/commands/navigate-down.js ***!
2839 \*************************************************************************/
2840 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2841
2842 "use strict";
2843
2844
2845 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2846 Object.defineProperty(exports, "__esModule", ({
2847 value: true
2848 }));
2849 exports["default"] = exports.NavigateDown = void 0;
2850 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2851 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2852 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2853 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2854 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2855 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2856 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2857 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2858 var NavigateDown = exports.NavigateDown = /*#__PURE__*/function (_CommandBase) {
2859 function NavigateDown() {
2860 (0, _classCallCheck2.default)(this, NavigateDown);
2861 return _callSuper(this, NavigateDown, arguments);
2862 }
2863 (0, _inherits2.default)(NavigateDown, _CommandBase);
2864 return (0, _createClass2.default)(NavigateDown, [{
2865 key: "apply",
2866 value: function apply() {
2867 this.component.getItemsView().activateNextItem();
2868 }
2869 }]);
2870 }(_commandBase.default);
2871 var _default = exports["default"] = NavigateDown;
2872
2873 /***/ }),
2874
2875 /***/ "../core/common/modules/finder/assets/js/commands/navigate-select.js":
2876 /*!***************************************************************************!*\
2877 !*** ../core/common/modules/finder/assets/js/commands/navigate-select.js ***!
2878 \***************************************************************************/
2879 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2880
2881 "use strict";
2882
2883
2884 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2885 Object.defineProperty(exports, "__esModule", ({
2886 value: true
2887 }));
2888 exports["default"] = exports.NavigateSelect = void 0;
2889 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2890 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2891 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2892 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2893 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2894 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2895 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2896 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2897 var NavigateSelect = exports.NavigateSelect = /*#__PURE__*/function (_CommandBase) {
2898 function NavigateSelect() {
2899 (0, _classCallCheck2.default)(this, NavigateSelect);
2900 return _callSuper(this, NavigateSelect, arguments);
2901 }
2902 (0, _inherits2.default)(NavigateSelect, _CommandBase);
2903 return (0, _createClass2.default)(NavigateSelect, [{
2904 key: "apply",
2905 value: function apply(args) {
2906 this.component.getItemsView().goToActiveItem(args);
2907 }
2908 }]);
2909 }(_commandBase.default);
2910 var _default = exports["default"] = NavigateSelect;
2911
2912 /***/ }),
2913
2914 /***/ "../core/common/modules/finder/assets/js/commands/navigate-up.js":
2915 /*!***********************************************************************!*\
2916 !*** ../core/common/modules/finder/assets/js/commands/navigate-up.js ***!
2917 \***********************************************************************/
2918 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2919
2920 "use strict";
2921
2922
2923 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2924 Object.defineProperty(exports, "__esModule", ({
2925 value: true
2926 }));
2927 exports["default"] = exports.NavigateUp = void 0;
2928 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2929 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2930 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2931 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2932 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2933 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2934 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2935 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2936 var NavigateUp = exports.NavigateUp = /*#__PURE__*/function (_CommandBase) {
2937 function NavigateUp() {
2938 (0, _classCallCheck2.default)(this, NavigateUp);
2939 return _callSuper(this, NavigateUp, arguments);
2940 }
2941 (0, _inherits2.default)(NavigateUp, _CommandBase);
2942 return (0, _createClass2.default)(NavigateUp, [{
2943 key: "apply",
2944 value: function apply() {
2945 this.component.getItemsView().activateNextItem(true);
2946 }
2947 }]);
2948 }(_commandBase.default);
2949 var _default = exports["default"] = NavigateUp;
2950
2951 /***/ }),
2952
2953 /***/ "../core/common/modules/finder/assets/js/component.js":
2954 /*!************************************************************!*\
2955 !*** ../core/common/modules/finder/assets/js/component.js ***!
2956 \************************************************************/
2957 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2958
2959 "use strict";
2960
2961
2962 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2963 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2964 Object.defineProperty(exports, "__esModule", ({
2965 value: true
2966 }));
2967 exports["default"] = void 0;
2968 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2969 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2970 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2971 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2972 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2973 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
2974 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2975 var _componentModalBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-modal-base */ "../modules/web-cli/assets/js/modules/component-modal-base.js"));
2976 var _layout = _interopRequireDefault(__webpack_require__(/*! ./modal/views/layout */ "../core/common/modules/finder/assets/js/modal/views/layout.js"));
2977 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../core/common/modules/finder/assets/js/commands/index.js"));
2978 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
2979 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2980 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2981 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2982 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2983 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
2984 var Component = exports["default"] = /*#__PURE__*/function (_ComponentModalBase) {
2985 function Component() {
2986 (0, _classCallCheck2.default)(this, Component);
2987 return _callSuper(this, Component, arguments);
2988 }
2989 (0, _inherits2.default)(Component, _ComponentModalBase);
2990 return (0, _createClass2.default)(Component, [{
2991 key: "getNamespace",
2992 value: function getNamespace() {
2993 return 'finder';
2994 }
2995 }, {
2996 key: "defaultShortcuts",
2997 value: function defaultShortcuts() {
2998 var _this = this;
2999 return {
3000 '': {
3001 keys: 'ctrl+e'
3002 },
3003 'navigate-down': {
3004 keys: 'down',
3005 scopes: [this.getNamespace()],
3006 dependency: function dependency() {
3007 return _this.getItemsView();
3008 }
3009 },
3010 'navigate-up': {
3011 keys: 'up',
3012 scopes: [this.getNamespace()],
3013 dependency: function dependency() {
3014 return _this.getItemsView();
3015 }
3016 },
3017 'navigate-select': {
3018 keys: 'enter',
3019 scopes: [this.getNamespace()],
3020 dependency: function dependency() {
3021 return _this.getItemsView().$activeItem;
3022 }
3023 }
3024 };
3025 }
3026 }, {
3027 key: "defaultCommands",
3028 value: function defaultCommands() {
3029 var modalCommands = _superPropGet(Component, "defaultCommands", this, 3)([]);
3030 return _objectSpread(_objectSpread({
3031 'navigate/down': function navigate_down() {
3032 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", '3.0.0', "$e.run( 'finder/navigate-down' )");
3033 $e.run('finder/navigate-down');
3034 },
3035 'navigate/up': function navigate_up() {
3036 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", '3.0.0', "$e.run( 'finder/navigate-up' )");
3037 $e.run('finder/navigate-up');
3038 },
3039 'navigate/select': function navigate_select(event) {
3040 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", '3.0.0', "$e.run( 'finder/navigate-select', event )");
3041
3042 // TODO: Fix $e.shortcuts use args. ( args.event ).
3043 $e.run('finder/navigate-select', event);
3044 }
3045 }, modalCommands), this.importCommands(commands));
3046 }
3047 }, {
3048 key: "getModalLayout",
3049 value: function getModalLayout() {
3050 return _layout.default;
3051 }
3052 }, {
3053 key: "getItemsView",
3054 value: function getItemsView() {
3055 return this.layout.modalContent.currentView.content.currentView;
3056 }
3057 }]);
3058 }(_componentModalBase.default);
3059
3060 /***/ }),
3061
3062 /***/ "../core/common/modules/finder/assets/js/finder.js":
3063 /*!*********************************************************!*\
3064 !*** ../core/common/modules/finder/assets/js/finder.js ***!
3065 \*********************************************************/
3066 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3067
3068 "use strict";
3069
3070
3071 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3072 Object.defineProperty(exports, "__esModule", ({
3073 value: true
3074 }));
3075 exports["default"] = void 0;
3076 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3077 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3078 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3079 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3080 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3081 var _component = _interopRequireDefault(__webpack_require__(/*! ./component */ "../core/common/modules/finder/assets/js/component.js"));
3082 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3083 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3084 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
3085 function _default() {
3086 (0, _classCallCheck2.default)(this, _default);
3087 return _callSuper(this, _default, arguments);
3088 }
3089 (0, _inherits2.default)(_default, _elementorModules$Mod);
3090 return (0, _createClass2.default)(_default, [{
3091 key: "onInit",
3092 value: function onInit() {
3093 // TODO: Temp fix, do not load finder in theme-builder.
3094 // Better to pass into '$e' constructor the app owner. ( admin, editor, preview, iframe ).
3095 if (window.top !== window) {
3096 return;
3097 }
3098 this.channel = Backbone.Radio.channel('ELEMENTOR:finder');
3099 $e.components.register(new _component.default({
3100 manager: this
3101 }));
3102 }
3103 }]);
3104 }(elementorModules.Module);
3105
3106 /***/ }),
3107
3108 /***/ "../core/common/modules/finder/assets/js/modal/model/item.js":
3109 /*!*******************************************************************!*\
3110 !*** ../core/common/modules/finder/assets/js/modal/model/item.js ***!
3111 \*******************************************************************/
3112 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3113
3114 "use strict";
3115
3116
3117 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3118 Object.defineProperty(exports, "__esModule", ({
3119 value: true
3120 }));
3121 exports["default"] = void 0;
3122 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3123 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3124 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3125 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3126 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3127 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3128 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3129 var _default = exports["default"] = /*#__PURE__*/function (_Backbone$Model) {
3130 function _default() {
3131 (0, _classCallCheck2.default)(this, _default);
3132 return _callSuper(this, _default, arguments);
3133 }
3134 (0, _inherits2.default)(_default, _Backbone$Model);
3135 return (0, _createClass2.default)(_default, [{
3136 key: "defaults",
3137 value: function defaults() {
3138 return {
3139 description: '',
3140 icon: 'settings',
3141 url: '',
3142 keywords: [],
3143 actions: [],
3144 lock: null
3145 };
3146 }
3147 }]);
3148 }(Backbone.Model);
3149
3150 /***/ }),
3151
3152 /***/ "../core/common/modules/finder/assets/js/modal/views/categories.js":
3153 /*!*************************************************************************!*\
3154 !*** ../core/common/modules/finder/assets/js/modal/views/categories.js ***!
3155 \*************************************************************************/
3156 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3157
3158 "use strict";
3159
3160
3161 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3162 Object.defineProperty(exports, "__esModule", ({
3163 value: true
3164 }));
3165 exports["default"] = void 0;
3166 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3167 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3168 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3169 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3170 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3171 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3172 var _dynamicCategory = _interopRequireDefault(__webpack_require__(/*! ./dynamic-category */ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js"));
3173 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3174 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3175 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3176 function _default() {
3177 (0, _classCallCheck2.default)(this, _default);
3178 return _callSuper(this, _default, arguments);
3179 }
3180 (0, _inherits2.default)(_default, _Marionette$Composite);
3181 return (0, _createClass2.default)(_default, [{
3182 key: "id",
3183 value: function id() {
3184 return 'elementor-finder__results-container';
3185 }
3186 }, {
3187 key: "ui",
3188 value: function ui() {
3189 this.selectors = {
3190 noResults: '#elementor-finder__no-results',
3191 categoryItem: '.elementor-finder__results__item'
3192 };
3193 return this.selectors;
3194 }
3195 }, {
3196 key: "events",
3197 value: function events() {
3198 return {
3199 'mouseenter @ui.categoryItem': 'onCategoryItemMouseEnter'
3200 };
3201 }
3202 }, {
3203 key: "getTemplate",
3204 value: function getTemplate() {
3205 return '#tmpl-elementor-finder-results-container';
3206 }
3207 }, {
3208 key: "getChildView",
3209 value: function getChildView(childModel) {
3210 return childModel.get('dynamic') ? _dynamicCategory.default : _category.default;
3211 }
3212 }, {
3213 key: "initialize",
3214 value: function initialize() {
3215 this.$activeItem = null;
3216 this.childViewContainer = '#elementor-finder__results';
3217 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings('data')));
3218 }
3219 }, {
3220 key: "activateItem",
3221 value: function activateItem($item) {
3222 if (this.$activeItem) {
3223 this.$activeItem.removeClass('elementor-active');
3224 }
3225 $item.addClass('elementor-active');
3226 this.$activeItem = $item;
3227 }
3228 }, {
3229 key: "activateNextItem",
3230 value: function activateNextItem(reverse) {
3231 var $allItems = jQuery(this.selectors.categoryItem);
3232 var nextItemIndex = 0;
3233 if (this.$activeItem) {
3234 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3235 if (nextItemIndex >= $allItems.length) {
3236 nextItemIndex = 0;
3237 } else if (nextItemIndex < 0) {
3238 nextItemIndex = $allItems.length - 1;
3239 }
3240 }
3241 var $nextItem = $allItems.eq(nextItemIndex);
3242 this.activateItem($nextItem);
3243 $nextItem[0].scrollIntoView({
3244 block: 'nearest'
3245 });
3246 }
3247 }, {
3248 key: "goToActiveItem",
3249 value: function goToActiveItem(event) {
3250 var $a = this.$activeItem.children('a'),
3251 isControlClicked = $e.shortcuts.isControlEvent(event);
3252 if (isControlClicked) {
3253 $a.attr('target', '_blank');
3254 }
3255 $a[0].click();
3256 if (isControlClicked) {
3257 $a.removeAttr('target');
3258 }
3259 }
3260 }, {
3261 key: "onCategoryItemMouseEnter",
3262 value: function onCategoryItemMouseEnter(event) {
3263 this.activateItem(jQuery(event.currentTarget));
3264 }
3265 }, {
3266 key: "onChildviewToggleVisibility",
3267 value: function onChildviewToggleVisibility() {
3268 var allCategoriesAreEmpty = this.children.every(function (child) {
3269 return !child.isVisible;
3270 });
3271 this.ui.noResults.toggle(allCategoriesAreEmpty);
3272 }
3273 }]);
3274 }(Marionette.CompositeView);
3275
3276 /***/ }),
3277
3278 /***/ "../core/common/modules/finder/assets/js/modal/views/category.js":
3279 /*!***********************************************************************!*\
3280 !*** ../core/common/modules/finder/assets/js/modal/views/category.js ***!
3281 \***********************************************************************/
3282 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3283
3284 "use strict";
3285
3286
3287 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3288 Object.defineProperty(exports, "__esModule", ({
3289 value: true
3290 }));
3291 exports["default"] = void 0;
3292 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3293 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3294 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3295 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3296 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3297 var _item = _interopRequireDefault(__webpack_require__(/*! ./item */ "../core/common/modules/finder/assets/js/modal/views/item.js"));
3298 var _item2 = _interopRequireDefault(__webpack_require__(/*! ../model/item */ "../core/common/modules/finder/assets/js/modal/model/item.js"));
3299 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3300 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3301 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3302 function _default() {
3303 (0, _classCallCheck2.default)(this, _default);
3304 return _callSuper(this, _default, arguments);
3305 }
3306 (0, _inherits2.default)(_default, _Marionette$Composite);
3307 return (0, _createClass2.default)(_default, [{
3308 key: "className",
3309 value: function className() {
3310 return 'elementor-finder__results__category';
3311 }
3312 }, {
3313 key: "getTemplate",
3314 value: function getTemplate() {
3315 return '#tmpl-elementor-finder__results__category';
3316 }
3317 }, {
3318 key: "getChildView",
3319 value: function getChildView() {
3320 return _item.default;
3321 }
3322 }, {
3323 key: "initialize",
3324 value: function initialize() {
3325 this.childViewContainer = '.elementor-finder__results__category__items';
3326 this.isVisible = true;
3327 var items = this.model.get('items');
3328 if (items) {
3329 items = Object.values(items);
3330 }
3331 this.collection = new Backbone.Collection(items, {
3332 model: _item2.default
3333 });
3334 }
3335 }, {
3336 key: "filter",
3337 value: function filter(childModel) {
3338 var textFilter = this.getTextFilter();
3339 if (childModel.get('title').toLowerCase().indexOf(textFilter) >= 0) {
3340 return true;
3341 }
3342 return childModel.get('keywords').some(function (keyword) {
3343 return keyword.indexOf(textFilter) >= 0;
3344 });
3345 }
3346 }, {
3347 key: "getTextFilter",
3348 value: function getTextFilter() {
3349 return elementorCommon.finder.channel.request('filter:text').trim().toLowerCase();
3350 }
3351 }, {
3352 key: "toggleElement",
3353 value: function toggleElement() {
3354 var isCurrentlyVisible = !!this.children.length;
3355 if (isCurrentlyVisible !== this.isVisible) {
3356 this.isVisible = isCurrentlyVisible;
3357 this.$el.toggle(isCurrentlyVisible);
3358 this.triggerMethod('toggle:visibility');
3359 }
3360 }
3361 }, {
3362 key: "onRender",
3363 value: function onRender() {
3364 this.listenTo(elementorCommon.finder.channel, 'filter:change', this.onFilterChange.bind(this));
3365 }
3366 }, {
3367 key: "onFilterChange",
3368 value: function onFilterChange() {
3369 this._renderChildren();
3370 }
3371 }, {
3372 key: "onRenderCollection",
3373 value: function onRenderCollection() {
3374 this.toggleElement();
3375 }
3376 }]);
3377 }(Marionette.CompositeView);
3378
3379 /***/ }),
3380
3381 /***/ "../core/common/modules/finder/assets/js/modal/views/content.js":
3382 /*!**********************************************************************!*\
3383 !*** ../core/common/modules/finder/assets/js/modal/views/content.js ***!
3384 \**********************************************************************/
3385 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3386
3387 "use strict";
3388
3389
3390 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3391 Object.defineProperty(exports, "__esModule", ({
3392 value: true
3393 }));
3394 exports["default"] = void 0;
3395 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3396 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3397 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3398 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3399 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3400 var _categories = _interopRequireDefault(__webpack_require__(/*! ./categories */ "../core/common/modules/finder/assets/js/modal/views/categories.js"));
3401 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3402 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3403 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3404 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3405 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$LayoutVie) {
3406 function _default() {
3407 (0, _classCallCheck2.default)(this, _default);
3408 return _callSuper(this, _default, arguments);
3409 }
3410 (0, _inherits2.default)(_default, _Marionette$LayoutVie);
3411 return (0, _createClass2.default)(_default, [{
3412 key: "id",
3413 value: function id() {
3414 return 'elementor-finder';
3415 }
3416 }, {
3417 key: "getTemplate",
3418 value: function getTemplate() {
3419 return '#tmpl-elementor-finder';
3420 }
3421 }, {
3422 key: "ui",
3423 value: function ui() {
3424 return {
3425 searchInput: '#elementor-finder__search__input'
3426 };
3427 }
3428 }, {
3429 key: "events",
3430 value: function events() {
3431 return {
3432 'input @ui.searchInput': 'onSearchInputInput'
3433 };
3434 }
3435 }, {
3436 key: "regions",
3437 value: function regions() {
3438 return {
3439 content: '#elementor-finder__content'
3440 };
3441 }
3442 }, {
3443 key: "initialize",
3444 value: function initialize() {
3445 this.debouncedTrackSearch = (0, _editorOneEvents.createDebouncedFinderSearch)(FINDER_SEARCH_DEBOUNCE_MS);
3446 }
3447 }, {
3448 key: "showCategoriesView",
3449 value: function showCategoriesView() {
3450 this.content.show(new _categories.default());
3451 }
3452 }, {
3453 key: "getResultsCount",
3454 value: function getResultsCount() {
3455 if (!this.content.currentView) {
3456 return 0;
3457 }
3458 var $visibleItems = this.content.currentView.$el.find('.elementor-finder__results__item:visible');
3459 return $visibleItems.length;
3460 }
3461 }, {
3462 key: "onSearchInputInput",
3463 value: function onSearchInputInput() {
3464 var _this = this;
3465 var value = this.ui.searchInput.val();
3466 if (value) {
3467 elementorCommon.finder.channel.reply('filter:text', value).trigger('filter:change');
3468 if (!(this.content.currentView instanceof _categories.default)) {
3469 this.showCategoriesView();
3470 }
3471 setTimeout(function () {
3472 var resultsCount = _this.getResultsCount();
3473 _this.debouncedTrackSearch(resultsCount, value);
3474 }, 50);
3475 }
3476 this.content.currentView.$el.toggle(!!value);
3477 }
3478 }, {
3479 key: "onDestroy",
3480 value: function onDestroy() {
3481 var _this$debouncedTrackS;
3482 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) {
3483 this.debouncedTrackSearch.cancel();
3484 }
3485 }
3486 }]);
3487 }(Marionette.LayoutView);
3488
3489 /***/ }),
3490
3491 /***/ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js":
3492 /*!*******************************************************************************!*\
3493 !*** ../core/common/modules/finder/assets/js/modal/views/dynamic-category.js ***!
3494 \*******************************************************************************/
3495 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3496
3497 "use strict";
3498
3499
3500 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3501 Object.defineProperty(exports, "__esModule", ({
3502 value: true
3503 }));
3504 exports["default"] = void 0;
3505 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3506 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3507 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3508 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3509 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3510 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3511 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3512 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3513 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3514 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
3515 var _default = exports["default"] = /*#__PURE__*/function (_Category) {
3516 function _default() {
3517 (0, _classCallCheck2.default)(this, _default);
3518 return _callSuper(this, _default, arguments);
3519 }
3520 (0, _inherits2.default)(_default, _Category);
3521 return (0, _createClass2.default)(_default, [{
3522 key: "className",
3523 value: function className() {
3524 return _superPropGet(_default, "className", this, 3)([]) + ' elementor-finder__results__category--dynamic';
3525 }
3526 }, {
3527 key: "ui",
3528 value: function ui() {
3529 return {
3530 title: '.elementor-finder__results__category__title'
3531 };
3532 }
3533 }, {
3534 key: "fetchData",
3535 value: function fetchData() {
3536 var _this = this;
3537 this.ui.loadingIcon.show();
3538 elementorCommon.ajax.addRequest('finder_get_category_items', {
3539 data: {
3540 category: this.model.get('name'),
3541 filter: this.getTextFilter()
3542 },
3543 success: function success(data) {
3544 if (_this.isDestroyed) {
3545 return;
3546 }
3547 _this.collection.set(data);
3548 _this.toggleElement();
3549 _this.ui.loadingIcon.hide();
3550 }
3551 });
3552 }
3553 }, {
3554 key: "filter",
3555 value: function filter() {
3556 return true;
3557 }
3558 }, {
3559 key: "onFilterChange",
3560 value: function onFilterChange() {
3561 this.fetchData();
3562 }
3563 }, {
3564 key: "onRender",
3565 value: function onRender() {
3566 _superPropGet(_default, "onRender", this, 3)([]);
3567 this.ui.loadingIcon = jQuery('<i>', {
3568 class: 'eicon-loading eicon-animation-spin'
3569 });
3570 this.ui.title.after(this.ui.loadingIcon);
3571 this.fetchData();
3572 }
3573 }]);
3574 }(_category.default);
3575
3576 /***/ }),
3577
3578 /***/ "../core/common/modules/finder/assets/js/modal/views/item.js":
3579 /*!*******************************************************************!*\
3580 !*** ../core/common/modules/finder/assets/js/modal/views/item.js ***!
3581 \*******************************************************************/
3582 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3583
3584 "use strict";
3585 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3586
3587
3588 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3589 Object.defineProperty(exports, "__esModule", ({
3590 value: true
3591 }));
3592 exports["default"] = void 0;
3593 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3594 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3595 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3596 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3597 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3598 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3599 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3600 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3601 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$ItemView) {
3602 function _default() {
3603 (0, _classCallCheck2.default)(this, _default);
3604 return _callSuper(this, _default, arguments);
3605 }
3606 (0, _inherits2.default)(_default, _Marionette$ItemView);
3607 return (0, _createClass2.default)(_default, [{
3608 key: "className",
3609 value: function className() {
3610 return 'elementor-finder__results__item';
3611 }
3612 }, {
3613 key: "getTemplate",
3614 value: function getTemplate() {
3615 return '#tmpl-elementor-finder__results__item';
3616 }
3617 }, {
3618 key: "events",
3619 value: function events() {
3620 this.$el[0].addEventListener('click', this.onClick.bind(this), true);
3621 }
3622 }, {
3623 key: "trackResultSelect",
3624 value: function trackResultSelect() {
3625 var title = this.model.get('title');
3626 _editorOneEvents.EditorOneEventManager.sendFinderResultSelect(title);
3627 }
3628 }, {
3629 key: "onClick",
3630 value: function onClick(e) {
3631 var _this = this;
3632 var lockOptions = this.model.get('lock');
3633 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
3634 this.trackResultSelect();
3635 return;
3636 }
3637 e.preventDefault();
3638 e.stopImmediatePropagation();
3639 elementorCommon.dialogsManager.createWidget('confirm', {
3640 id: 'elementor-finder__lock-dialog',
3641 headerMessage: lockOptions.content.heading,
3642 message: lockOptions.content.description,
3643 position: {
3644 my: 'center center',
3645 at: 'center center'
3646 },
3647 strings: {
3648 confirm: lockOptions.button.text,
3649 cancel: __('Cancel', 'elementor')
3650 },
3651 onConfirm: function onConfirm() {
3652 _this.trackResultSelect();
3653 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
3654 window.open(link, '_blank');
3655 }
3656 }).show();
3657 }
3658 }, {
3659 key: "replaceLockLinkPlaceholders",
3660 value: function replaceLockLinkPlaceholders(link) {
3661 return link.replace(/%%utm_source%%/g, 'finder').replace(/%%utm_medium%%/g, 'wp-dash');
3662 }
3663 }]);
3664 }(Marionette.ItemView);
3665
3666 /***/ }),
3667
3668 /***/ "../core/common/modules/finder/assets/js/modal/views/layout.js":
3669 /*!*********************************************************************!*\
3670 !*** ../core/common/modules/finder/assets/js/modal/views/layout.js ***!
3671 \*********************************************************************/
3672 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3673
3674 "use strict";
3675 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3676
3677
3678 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3679 Object.defineProperty(exports, "__esModule", ({
3680 value: true
3681 }));
3682 exports["default"] = void 0;
3683 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3684 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3685 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3686 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3687 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3688 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3689 var _content = _interopRequireDefault(__webpack_require__(/*! ./content */ "../core/common/modules/finder/assets/js/modal/views/content.js"));
3690 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3691 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3692 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
3693 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$com) {
3694 function _default() {
3695 (0, _classCallCheck2.default)(this, _default);
3696 return _callSuper(this, _default, arguments);
3697 }
3698 (0, _inherits2.default)(_default, _elementorModules$com);
3699 return (0, _createClass2.default)(_default, [{
3700 key: "getModalOptions",
3701 value: function getModalOptions() {
3702 return {
3703 id: 'elementor-finder__modal',
3704 draggable: true,
3705 effects: {
3706 show: 'show',
3707 hide: 'hide'
3708 },
3709 position: {
3710 enable: false
3711 }
3712 };
3713 }
3714 }, {
3715 key: "getLogoOptions",
3716 value: function getLogoOptions() {
3717 return {
3718 title: __('Finder', 'elementor')
3719 };
3720 }
3721 }, {
3722 key: "initialize",
3723 value: function initialize() {
3724 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3725 args[_key] = arguments[_key];
3726 }
3727 _superPropGet(_default, "initialize", this, 3)(args);
3728 this.showLogo();
3729 this.showContentView();
3730 }
3731 }, {
3732 key: "showContentView",
3733 value: function showContentView() {
3734 this.modalContent.show(new _content.default());
3735 }
3736 }, {
3737 key: "showModal",
3738 value: function showModal() {
3739 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3740 args[_key2] = arguments[_key2];
3741 }
3742 _superPropGet(_default, "showModal", this, 3)(args);
3743 this.modalContent.currentView.ui.searchInput.focus();
3744 }
3745 }]);
3746 }(elementorModules.common.views.modal.Layout);
3747
3748 /***/ }),
3749
3750 /***/ "../modules/web-cli/assets/js/core/data/errors/base-error.js":
3751 /*!*******************************************************************!*\
3752 !*** ../modules/web-cli/assets/js/core/data/errors/base-error.js ***!
3753 \*******************************************************************/
3754 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3755
3756 "use strict";
3757
3758
3759 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3760 Object.defineProperty(exports, "__esModule", ({
3761 value: true
3762 }));
3763 exports["default"] = void 0;
3764 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3765 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3766 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3767 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3768 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3769 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
3770 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
3771 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3772 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../../../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
3773 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3774 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3775 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3776 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3777 var BaseError = exports["default"] = /*#__PURE__*/function (_Error) {
3778 /**
3779 * Error constructor.
3780 *
3781 * @param {string} message
3782 * @param {string} code
3783 * @param {*} data
3784 */
3785 function BaseError() {
3786 var _this;
3787 var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3788 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3789 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3790 (0, _classCallCheck2.default)(this, BaseError);
3791 _this = _callSuper(this, BaseError, [message]);
3792 /**
3793 * The server error code.
3794 *
3795 * @type {string}
3796 */
3797 (0, _defineProperty2.default)(_this, "code", '');
3798 /**
3799 * Additional data about the current error.
3800 *
3801 * @type {*[]}
3802 */
3803 (0, _defineProperty2.default)(_this, "data", []);
3804 _this.code = code;
3805 _this.data = data;
3806 return _this;
3807 }
3808
3809 /**
3810 * Notify a message when the error occurs.
3811 */
3812 (0, _inherits2.default)(BaseError, _Error);
3813 return (0, _createClass2.default)(BaseError, [{
3814 key: "notify",
3815 value: function notify() {
3816 _console.default.error(_objectSpread({
3817 message: this.message
3818 }, this));
3819 }
3820 }], [{
3821 key: "create",
3822 value:
3823 /**
3824 * Static helper function to create the error.
3825 *
3826 * @param {string} message
3827 * @param {string} code
3828 * @param {*} data
3829 * @return {BaseError} error
3830 */
3831 function create(message) {
3832 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3833 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3834 return new this(message, code, data);
3835 }
3836
3837 /**
3838 * Returns the status code of the error.
3839 */
3840 }, {
3841 key: "getHTTPErrorCode",
3842 value: function getHTTPErrorCode() {
3843 (0, _forceMethodImplementation.default)();
3844 }
3845 }]);
3846 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
3847
3848 /***/ }),
3849
3850 /***/ "../modules/web-cli/assets/js/core/data/errors/default-error.js":
3851 /*!**********************************************************************!*\
3852 !*** ../modules/web-cli/assets/js/core/data/errors/default-error.js ***!
3853 \**********************************************************************/
3854 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3855
3856 "use strict";
3857
3858
3859 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3860 Object.defineProperty(exports, "__esModule", ({
3861 value: true
3862 }));
3863 exports["default"] = exports.DefaultError = void 0;
3864 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3865 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3866 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3867 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3868 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3869 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3870 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3871 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3872 var DefaultError = exports.DefaultError = /*#__PURE__*/function (_BaseError) {
3873 function DefaultError() {
3874 (0, _classCallCheck2.default)(this, DefaultError);
3875 return _callSuper(this, DefaultError, arguments);
3876 }
3877 (0, _inherits2.default)(DefaultError, _BaseError);
3878 return (0, _createClass2.default)(DefaultError, null, [{
3879 key: "getHTTPErrorCode",
3880 value: function getHTTPErrorCode() {
3881 return 501;
3882 }
3883 }]);
3884 }(_baseError.default);
3885 var _default = exports["default"] = DefaultError;
3886
3887 /***/ }),
3888
3889 /***/ "../modules/web-cli/assets/js/core/data/errors/error-404.js":
3890 /*!******************************************************************!*\
3891 !*** ../modules/web-cli/assets/js/core/data/errors/error-404.js ***!
3892 \******************************************************************/
3893 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3894
3895 "use strict";
3896
3897
3898 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3899 Object.defineProperty(exports, "__esModule", ({
3900 value: true
3901 }));
3902 exports["default"] = exports.Error404 = void 0;
3903 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3904 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3905 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3906 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3907 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3908 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3909 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3910 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3911 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3912 var Error404 = exports.Error404 = /*#__PURE__*/function (_BaseError) {
3913 function Error404() {
3914 (0, _classCallCheck2.default)(this, Error404);
3915 return _callSuper(this, Error404, arguments);
3916 }
3917 (0, _inherits2.default)(Error404, _BaseError);
3918 return (0, _createClass2.default)(Error404, [{
3919 key: "notify",
3920 value: function notify() {
3921 _console.default.warn(this.message);
3922 }
3923 }], [{
3924 key: "getHTTPErrorCode",
3925 value: function getHTTPErrorCode() {
3926 return 404;
3927 }
3928 }]);
3929 }(_baseError.default);
3930 var _default = exports["default"] = Error404;
3931
3932 /***/ }),
3933
3934 /***/ "../modules/web-cli/assets/js/core/data/errors/index.js":
3935 /*!**************************************************************!*\
3936 !*** ../modules/web-cli/assets/js/core/data/errors/index.js ***!
3937 \**************************************************************/
3938 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3939
3940 "use strict";
3941
3942
3943 Object.defineProperty(exports, "__esModule", ({
3944 value: true
3945 }));
3946 Object.defineProperty(exports, "DefaultError", ({
3947 enumerable: true,
3948 get: function get() {
3949 return _defaultError.DefaultError;
3950 }
3951 }));
3952 Object.defineProperty(exports, "Error404", ({
3953 enumerable: true,
3954 get: function get() {
3955 return _error.Error404;
3956 }
3957 }));
3958 var _defaultError = __webpack_require__(/*! ./default-error */ "../modules/web-cli/assets/js/core/data/errors/default-error.js");
3959 var _error = __webpack_require__(/*! ./error-404 */ "../modules/web-cli/assets/js/core/data/errors/error-404.js");
3960
3961 /***/ }),
3962
3963 /***/ "../modules/web-cli/assets/js/modules/command-base.js":
3964 /*!************************************************************!*\
3965 !*** ../modules/web-cli/assets/js/modules/command-base.js ***!
3966 \************************************************************/
3967 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3968
3969 "use strict";
3970
3971
3972 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3973 Object.defineProperty(exports, "__esModule", ({
3974 value: true
3975 }));
3976 exports["default"] = void 0;
3977 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3978 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3979 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3980 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3981 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3982 var _commandInfra = _interopRequireDefault(__webpack_require__(/*! ./command-infra */ "../modules/web-cli/assets/js/modules/command-infra.js"));
3983 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
3984 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3985 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3986 /**
3987 * @name $e.modules.CommandBase
3988 */
3989 var CommandBase = exports["default"] = /*#__PURE__*/function (_CommandInfra) {
3990 function CommandBase() {
3991 (0, _classCallCheck2.default)(this, CommandBase);
3992 return _callSuper(this, CommandBase, arguments);
3993 }
3994 (0, _inherits2.default)(CommandBase, _CommandInfra);
3995 return (0, _createClass2.default)(CommandBase, [{
3996 key: "onBeforeRun",
3997 value: function onBeforeRun() {
3998 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3999 $e.hooks.runUIBefore(this.command, args);
4000 }
4001 }, {
4002 key: "onAfterRun",
4003 value: function onAfterRun() {
4004 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4005 var result = arguments.length > 1 ? arguments[1] : undefined;
4006 $e.hooks.runUIAfter(this.command, args, result);
4007 }
4008 }, {
4009 key: "onBeforeApply",
4010 value: function onBeforeApply() {
4011 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4012 $e.hooks.runDataDependency(this.command, args);
4013 }
4014 }, {
4015 key: "onAfterApply",
4016 value: function onAfterApply() {
4017 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4018 var result = arguments.length > 1 ? arguments[1] : undefined;
4019 return $e.hooks.runDataAfter(this.command, args, result);
4020 }
4021 }, {
4022 key: "onCatchApply",
4023 value: function onCatchApply(e) {
4024 this.runCatchHooks(e);
4025 }
4026
4027 /**
4028 * Run all the catch hooks.
4029 *
4030 * @param {Error} e
4031 */
4032 }, {
4033 key: "runCatchHooks",
4034 value: function runCatchHooks(e) {
4035 $e.hooks.runDataCatch(this.command, this.args, e);
4036 $e.hooks.runUICatch(this.command, this.args, e);
4037 }
4038
4039 /**
4040 * TODO - Remove - Backwards compatibility.
4041 *
4042 * Function requireContainer().
4043 *
4044 * Validate `arg.container` & `arg.containers`.
4045 *
4046 * @param {{}} args
4047 * @deprecated since 3.7.0, extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase` instead.
4048 *
4049 * @throws {Error}
4050 */
4051 }, {
4052 key: "requireContainer",
4053 value: function requireContainer() {
4054 var _this = this;
4055 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.args;
4056 _deprecation.default.deprecated('requireContainer()', '3.7.0', 'Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`');
4057 if (!args.container && !args.containers) {
4058 throw Error('container or containers are required.');
4059 }
4060 if (args.container && args.containers) {
4061 throw Error('container and containers cannot go together please select one of them.');
4062 }
4063 var containers = args.containers || [args.container];
4064 containers.forEach(function (container) {
4065 _this.requireArgumentInstance('container', elementorModules.editor.Container, {
4066 container: container
4067 });
4068 });
4069 }
4070 }], [{
4071 key: "getInstanceType",
4072 value: function getInstanceType() {
4073 return 'CommandBase';
4074 }
4075 }]);
4076 }(_commandInfra.default);
4077
4078 /***/ }),
4079
4080 /***/ "../modules/web-cli/assets/js/modules/command-callback-base.js":
4081 /*!*********************************************************************!*\
4082 !*** ../modules/web-cli/assets/js/modules/command-callback-base.js ***!
4083 \*********************************************************************/
4084 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4085
4086 "use strict";
4087
4088
4089 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4090 Object.defineProperty(exports, "__esModule", ({
4091 value: true
4092 }));
4093 exports["default"] = void 0;
4094 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4095 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4096 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4097 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4098 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4099 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4100 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4101 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4102 /**
4103 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
4104 */
4105 var CommandCallbackBase = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4106 function CommandCallbackBase() {
4107 (0, _classCallCheck2.default)(this, CommandCallbackBase);
4108 return _callSuper(this, CommandCallbackBase, arguments);
4109 }
4110 (0, _inherits2.default)(CommandCallbackBase, _CommandBase);
4111 return (0, _createClass2.default)(CommandCallbackBase, [{
4112 key: "apply",
4113 value: function apply() {
4114 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4115 return this.constructor.getCallback()(args);
4116 }
4117 }], [{
4118 key: "getInstanceType",
4119 value: function getInstanceType() {
4120 return 'CommandCallbackBase';
4121 }
4122
4123 /**
4124 * Get original callback of the command.
4125 *
4126 * Support pure callbacks ( Non command-base ).
4127 *
4128 * @return {()=>{}} Command Results.
4129 */
4130 }, {
4131 key: "getCallback",
4132 value: function getCallback() {
4133 return this.registerConfig.callback;
4134 }
4135 }]);
4136 }(_commandBase.default);
4137
4138 /***/ }),
4139
4140 /***/ "../modules/web-cli/assets/js/modules/command-data.js":
4141 /*!************************************************************!*\
4142 !*** ../modules/web-cli/assets/js/modules/command-data.js ***!
4143 \************************************************************/
4144 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4145
4146 "use strict";
4147
4148
4149 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4150 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
4151 Object.defineProperty(exports, "__esModule", ({
4152 value: true
4153 }));
4154 exports["default"] = void 0;
4155 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4156 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4157 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4158 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4159 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4160 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4161 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4162 var errors = _interopRequireWildcard(__webpack_require__(/*! ../core/data/errors/ */ "../modules/web-cli/assets/js/core/data/errors/index.js"));
4163 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
4164 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4165 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4166 /**
4167 * @name $e.modules.CommandData
4168 */
4169 /**
4170 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4171 */
4172 /**
4173 * @typedef {{}} RequestData
4174 */
4175 /**
4176 * @typedef {import('../core/data/errors/base-error')} BaseError
4177 */
4178 var CommandData = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4179 function CommandData(args) {
4180 var _this$args$options;
4181 var _this;
4182 var commandsAPI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : $e.data;
4183 (0, _classCallCheck2.default)(this, CommandData);
4184 _this = _callSuper(this, CommandData, [args, commandsAPI]);
4185 /**
4186 * Data returned from remote.
4187 *
4188 * @type {*}
4189 */
4190 (0, _defineProperty2.default)(_this, "data", void 0);
4191 /**
4192 * Fetch type.
4193 *
4194 * @type {DataTypes}
4195 */
4196 (0, _defineProperty2.default)(_this, "type", void 0);
4197 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) {
4198 _this.type = _this.args.options.type;
4199 }
4200 return _this;
4201 }
4202
4203 /**
4204 * Function getEndpointFormat().
4205 *
4206 * @return {null|string} endpoint format
4207 */
4208 (0, _inherits2.default)(CommandData, _CommandBase);
4209 return (0, _createClass2.default)(CommandData, [{
4210 key: "getApplyMethods",
4211 value:
4212 /**
4213 * @param {DataTypes} type
4214 *
4215 * @return {boolean|{before: (function(*=): {}), after: (function({}, *=): {})}} apply methods
4216 */
4217 function getApplyMethods() {
4218 var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.type;
4219 var before, after;
4220 switch (type) {
4221 case 'create':
4222 before = this.applyBeforeCreate;
4223 after = this.applyAfterCreate;
4224 break;
4225 case 'delete':
4226 before = this.applyBeforeDelete;
4227 after = this.applyAfterDelete;
4228 break;
4229 case 'get':
4230 before = this.applyBeforeGet;
4231 after = this.applyAfterGet;
4232 break;
4233 case 'update':
4234 before = this.applyBeforeUpdate;
4235 after = this.applyAfterUpdate;
4236 break;
4237 case 'options':
4238 before = this.applyBeforeOptions;
4239 after = this.applyAfterOptions;
4240 break;
4241 default:
4242 return false;
4243 }
4244 return {
4245 before: before.bind(this),
4246 after: after.bind(this)
4247 };
4248 }
4249
4250 /**
4251 * Function getRequestData().
4252 *
4253 * @return {RequestData} request data
4254 */
4255 }, {
4256 key: "getRequestData",
4257 value: function getRequestData() {
4258 return {
4259 type: this.type,
4260 args: this.args,
4261 timestamp: new Date().getTime(),
4262 component: this.component,
4263 command: this.command,
4264 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4265 };
4266 }
4267 }, {
4268 key: "apply",
4269 value: function apply() {
4270 var _this2 = this;
4271 var applyMethods = this.getApplyMethods();
4272
4273 // Run 'before' method.
4274 this.args = applyMethods.before(this.args);
4275 var requestData = this.getRequestData();
4276 return $e.data.fetch(requestData).then(function (data) {
4277 _this2.data = data;
4278
4279 // Run 'after' method.
4280 _this2.data = applyMethods.after(data, _this2.args);
4281 _this2.data = {
4282 data: _this2.data
4283 };
4284
4285 // Append requestData.
4286 _this2.data = Object.assign({
4287 __requestData__: requestData
4288 }, _this2.data);
4289 return _this2.data;
4290 });
4291 }
4292
4293 /**
4294 * @param {*} [args={}]
4295 * @return {{}} filtered args
4296 */
4297 }, {
4298 key: "applyBeforeCreate",
4299 value: function applyBeforeCreate() {
4300 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4301 return args;
4302 }
4303
4304 /**
4305 * @param {{}} data
4306 * @param {*} [args={}]
4307 * @return {{}} filtered result
4308 */
4309 }, {
4310 key: "applyAfterCreate",
4311 value: function applyAfterCreate(data) {
4312 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4313 // eslint-disable-line no-unused-vars
4314 return data;
4315 }
4316
4317 /**
4318 * @param {*} [args={}]
4319 * @return {{}} filtered args
4320 */
4321 }, {
4322 key: "applyBeforeDelete",
4323 value: function applyBeforeDelete() {
4324 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4325 return args;
4326 }
4327
4328 /**
4329 * @param {{}} data
4330 * @param {*} [args={}]
4331 * @return {{}} filtered result
4332 */
4333 }, {
4334 key: "applyAfterDelete",
4335 value: function applyAfterDelete(data) {
4336 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4337 // eslint-disable-line no-unused-vars
4338 return data;
4339 }
4340
4341 /**
4342 * @param {*} [args={}]
4343 * @return {{}} filtered args
4344 */
4345 }, {
4346 key: "applyBeforeGet",
4347 value: function applyBeforeGet() {
4348 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4349 return args;
4350 }
4351
4352 /**
4353 * @param {{}} data
4354 * @param {*} [args={}]
4355 * @return {{}} filtered result
4356 */
4357 }, {
4358 key: "applyAfterGet",
4359 value: function applyAfterGet(data) {
4360 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4361 // eslint-disable-line no-unused-vars
4362 return data;
4363 }
4364
4365 /**
4366 * @param {*} [args={}]
4367 * @return {{}} filtered args
4368 */
4369 }, {
4370 key: "applyBeforeUpdate",
4371 value: function applyBeforeUpdate() {
4372 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4373 return args;
4374 }
4375
4376 /**
4377 * @param {{}} data
4378 * @param {*} [args={}]
4379 * @return {{}} filtered result
4380 */
4381 }, {
4382 key: "applyAfterUpdate",
4383 value: function applyAfterUpdate(data) {
4384 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4385 // eslint-disable-line no-unused-vars
4386 return data;
4387 }
4388
4389 /**
4390 * @param {*} [args={}]
4391 * @return {{}} filtered args
4392 */
4393 }, {
4394 key: "applyBeforeOptions",
4395 value: function applyBeforeOptions() {
4396 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4397 return args;
4398 }
4399
4400 /**
4401 * @param {{}} data
4402 * @param {*} [args={}]
4403 * @return {{}} filtered result
4404 */
4405 }, {
4406 key: "applyAfterOptions",
4407 value: function applyAfterOptions(data) {
4408 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4409 // eslint-disable-line no-unused-vars
4410 return data;
4411 }
4412
4413 /**
4414 * @param {BaseError} e
4415 */
4416 }, {
4417 key: "applyAfterCatch",
4418 value: function applyAfterCatch(e) {
4419 e.notify();
4420 }
4421 }, {
4422 key: "onCatchApply",
4423 value: function onCatchApply(e) {
4424 var _e;
4425 // TODO: If the errors that returns from the server is consistent remove the '?' from 'e'
4426 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4427 var dataError = Object.values(errors).find(function (error) {
4428 return error.getHTTPErrorCode() === httpErrorCode;
4429 });
4430 if (!dataError) {
4431 dataError = errors.DefaultError;
4432 }
4433 e = dataError.create(e.message, e.code, e.data || []);
4434 this.runCatchHooks(e);
4435 this.applyAfterCatch(e);
4436 }
4437 }], [{
4438 key: "getInstanceType",
4439 value: function getInstanceType() {
4440 return 'CommandData';
4441 }
4442 }, {
4443 key: "getEndpointFormat",
4444 value: function getEndpointFormat() {
4445 return null;
4446 }
4447 }]);
4448 }(_commandBase.default);
4449
4450 /***/ }),
4451
4452 /***/ "../modules/web-cli/assets/js/modules/command-infra.js":
4453 /*!*************************************************************!*\
4454 !*** ../modules/web-cli/assets/js/modules/command-infra.js ***!
4455 \*************************************************************/
4456 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4457
4458 "use strict";
4459
4460
4461 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4462 Object.defineProperty(exports, "__esModule", ({
4463 value: true
4464 }));
4465 exports["default"] = void 0;
4466 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4467 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4468 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4469 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4470 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4471 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4472 var _argsObject = _interopRequireDefault(__webpack_require__(/*! elementor-assets-js/modules/imports/args-object */ "../assets/dev/js/modules/imports/args-object.js"));
4473 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4474 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4475 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4476 /**
4477 * @typedef {import('../modules/component-base')} ComponentBase
4478 */
4479 var CommandInfra = exports["default"] = /*#__PURE__*/function (_ArgsObject) {
4480 /**
4481 * Function constructor().
4482 *
4483 * Create Commands Base.
4484 *
4485 * @param {{}} args
4486 */
4487 function CommandInfra() {
4488 var _this;
4489 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4490 (0, _classCallCheck2.default)(this, CommandInfra);
4491 _this = _callSuper(this, CommandInfra, [args]);
4492 if (!_this.constructor.registerConfig) {
4493 throw RangeError('Doing it wrong: Each command type should have `registerConfig`.');
4494 }
4495
4496 // Acknowledge self about which command it run.
4497 _this.command = _this.constructor.getCommand();
4498
4499 // Assign instance of current component.
4500 _this.component = _this.constructor.getComponent();
4501
4502 // Who ever need do something before without `super` the constructor can use `initialize` method.
4503 _this.initialize(args);
4504
4505 // Refresh args, maybe the changed via `initialize`.
4506 args = _this.args;
4507
4508 // Validate args before run.
4509 _this.validateArgs(args);
4510 return _this;
4511 }
4512
4513 /**
4514 * Function initialize().
4515 *
4516 * Initialize command, called after construction.
4517 *
4518 * @param {{}} args
4519 */
4520 (0, _inherits2.default)(CommandInfra, _ArgsObject);
4521 return (0, _createClass2.default)(CommandInfra, [{
4522 key: "currentCommand",
4523 get:
4524 /**
4525 * @deprecated since 3.7.0, use `this.command` instead.
4526 */
4527 function get() {
4528 _deprecation.default.deprecated('this.currentCommand', '3.7.0', 'this.command');
4529 return this.command;
4530 }
4531 }, {
4532 key: "initialize",
4533 value: function initialize() {
4534 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4535 } // eslint-disable-line no-unused-vars
4536
4537 /**
4538 * Function validateArgs().
4539 *
4540 * Validate command arguments.
4541 *
4542 * @param {{}} args
4543 */
4544 }, {
4545 key: "validateArgs",
4546 value: function validateArgs() {
4547 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4548 } // eslint-disable-line no-unused-vars
4549
4550 // eslint-disable-next-line jsdoc/require-returns-check
4551 /**
4552 * Function apply().
4553 *
4554 * Do the actual command.
4555 *
4556 * @param {{}} args
4557 *
4558 * @return {*} Command results.
4559 */
4560 }, {
4561 key: "apply",
4562 value: function apply() {
4563 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4564 // eslint-disable-line no-unused-vars
4565 elementorModules.ForceMethodImplementation();
4566 }
4567
4568 /**
4569 * Function run().
4570 *
4571 * Run command with history & hooks.
4572 *
4573 * @return {*} Command results.
4574 */
4575 }, {
4576 key: "run",
4577 value: function run() {
4578 return this.apply(this.args);
4579 }
4580
4581 /**
4582 * Function onBeforeRun.
4583 *
4584 * Called before run().
4585 *
4586 * @param {{}} args
4587 */
4588 }, {
4589 key: "onBeforeRun",
4590 value: function onBeforeRun() {
4591 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4592 } // eslint-disable-line no-unused-vars
4593
4594 /**
4595 * Function onAfterRun.
4596 *
4597 * Called after run().
4598 *
4599 * @param {{}} args
4600 * @param {*} result
4601 */
4602 }, {
4603 key: "onAfterRun",
4604 value: function onAfterRun() {
4605 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4606 var result = arguments.length > 1 ? arguments[1] : undefined;
4607 } // eslint-disable-line no-unused-vars
4608
4609 /**
4610 * Function onBeforeApply.
4611 *
4612 * Called before apply().
4613 *
4614 * @param {{}} args
4615 */
4616 }, {
4617 key: "onBeforeApply",
4618 value: function onBeforeApply() {
4619 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4620 } // eslint-disable-line no-unused-vars
4621
4622 /**
4623 * Function onAfterApply.
4624 *
4625 * Called after apply().
4626 *
4627 * @param {{}} args
4628 * @param {*} result
4629 */
4630 }, {
4631 key: "onAfterApply",
4632 value: function onAfterApply() {
4633 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4634 var result = arguments.length > 1 ? arguments[1] : undefined;
4635 } // eslint-disable-line no-unused-vars
4636
4637 /**
4638 * Function onCatchApply.
4639 *
4640 * Called after apply() failed.
4641 *
4642 * @param {Error} e
4643 */
4644 }, {
4645 key: "onCatchApply",
4646 value: function onCatchApply(e) {} // eslint-disable-line no-unused-vars
4647 }], [{
4648 key: "getInstanceType",
4649 value: function getInstanceType() {
4650 return 'CommandInfra';
4651 }
4652
4653 /**
4654 * Get info of command.
4655 *
4656 * @return {Object} Extra information about the command.
4657 */
4658 }, {
4659 key: "getInfo",
4660 value: function getInfo() {
4661 return {};
4662 }
4663
4664 /**
4665 * @return {string} Self command name.
4666 */
4667 }, {
4668 key: "getCommand",
4669 value: function getCommand() {
4670 return this.registerConfig.command;
4671 }
4672
4673 /**
4674 * @return {ComponentBase} Self component
4675 */
4676 }, {
4677 key: "getComponent",
4678 value: function getComponent() {
4679 return this.registerConfig.component;
4680 }
4681 }, {
4682 key: "setRegisterConfig",
4683 value: function setRegisterConfig(config) {
4684 this.registerConfig = Object.freeze(config);
4685 }
4686 }]);
4687 }(_argsObject.default);
4688 /**
4689 * @type {Object}
4690 */
4691 (0, _defineProperty2.default)(CommandInfra, "registerConfig", null);
4692
4693 /***/ }),
4694
4695 /***/ "../modules/web-cli/assets/js/modules/commands/close.js":
4696 /*!**************************************************************!*\
4697 !*** ../modules/web-cli/assets/js/modules/commands/close.js ***!
4698 \**************************************************************/
4699 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4700
4701 "use strict";
4702
4703
4704 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4705 Object.defineProperty(exports, "__esModule", ({
4706 value: true
4707 }));
4708 exports["default"] = exports.Close = void 0;
4709 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4710 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4711 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4712 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4713 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4714 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4715 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4716 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4717 var Close = exports.Close = /*#__PURE__*/function (_CommandBase) {
4718 function Close() {
4719 (0, _classCallCheck2.default)(this, Close);
4720 return _callSuper(this, Close, arguments);
4721 }
4722 (0, _inherits2.default)(Close, _CommandBase);
4723 return (0, _createClass2.default)(Close, [{
4724 key: "apply",
4725 value: function apply() {
4726 this.component.close();
4727 }
4728 }]);
4729 }(_commandBase.default);
4730 var _default = exports["default"] = Close;
4731
4732 /***/ }),
4733
4734 /***/ "../modules/web-cli/assets/js/modules/commands/index.js":
4735 /*!**************************************************************!*\
4736 !*** ../modules/web-cli/assets/js/modules/commands/index.js ***!
4737 \**************************************************************/
4738 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4739
4740 "use strict";
4741
4742
4743 Object.defineProperty(exports, "__esModule", ({
4744 value: true
4745 }));
4746 Object.defineProperty(exports, "Close", ({
4747 enumerable: true,
4748 get: function get() {
4749 return _close.Close;
4750 }
4751 }));
4752 Object.defineProperty(exports, "Open", ({
4753 enumerable: true,
4754 get: function get() {
4755 return _open.Open;
4756 }
4757 }));
4758 Object.defineProperty(exports, "Toggle", ({
4759 enumerable: true,
4760 get: function get() {
4761 return _toggle.Toggle;
4762 }
4763 }));
4764 var _close = __webpack_require__(/*! ./close */ "../modules/web-cli/assets/js/modules/commands/close.js");
4765 var _open = __webpack_require__(/*! ./open */ "../modules/web-cli/assets/js/modules/commands/open.js");
4766 var _toggle = __webpack_require__(/*! ./toggle */ "../modules/web-cli/assets/js/modules/commands/toggle.js");
4767
4768 /***/ }),
4769
4770 /***/ "../modules/web-cli/assets/js/modules/commands/open.js":
4771 /*!*************************************************************!*\
4772 !*** ../modules/web-cli/assets/js/modules/commands/open.js ***!
4773 \*************************************************************/
4774 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4775
4776 "use strict";
4777
4778
4779 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4780 Object.defineProperty(exports, "__esModule", ({
4781 value: true
4782 }));
4783 exports["default"] = exports.Open = void 0;
4784 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4785 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4786 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4787 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4788 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4789 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4790 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4791 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4792 var Open = exports.Open = /*#__PURE__*/function (_CommandBase) {
4793 function Open() {
4794 (0, _classCallCheck2.default)(this, Open);
4795 return _callSuper(this, Open, arguments);
4796 }
4797 (0, _inherits2.default)(Open, _CommandBase);
4798 return (0, _createClass2.default)(Open, [{
4799 key: "apply",
4800 value: function apply() {
4801 $e.route(this.component.getNamespace());
4802 }
4803 }]);
4804 }(_commandBase.default);
4805 var _default = exports["default"] = Open;
4806
4807 /***/ }),
4808
4809 /***/ "../modules/web-cli/assets/js/modules/commands/toggle.js":
4810 /*!***************************************************************!*\
4811 !*** ../modules/web-cli/assets/js/modules/commands/toggle.js ***!
4812 \***************************************************************/
4813 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4814
4815 "use strict";
4816
4817
4818 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4819 Object.defineProperty(exports, "__esModule", ({
4820 value: true
4821 }));
4822 exports["default"] = exports.Toggle = void 0;
4823 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4824 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4825 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4826 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4827 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4828 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4829 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4830 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4831 var Toggle = exports.Toggle = /*#__PURE__*/function (_CommandBase) {
4832 function Toggle() {
4833 (0, _classCallCheck2.default)(this, Toggle);
4834 return _callSuper(this, Toggle, arguments);
4835 }
4836 (0, _inherits2.default)(Toggle, _CommandBase);
4837 return (0, _createClass2.default)(Toggle, [{
4838 key: "apply",
4839 value: function apply() {
4840 if (this.component.isOpen) {
4841 this.component.close();
4842 } else {
4843 $e.route(this.component.getNamespace());
4844 }
4845 }
4846 }]);
4847 }(_commandBase.default);
4848 var _default = exports["default"] = Toggle;
4849
4850 /***/ }),
4851
4852 /***/ "../modules/web-cli/assets/js/modules/component-base.js":
4853 /*!**************************************************************!*\
4854 !*** ../modules/web-cli/assets/js/modules/component-base.js ***!
4855 \**************************************************************/
4856 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4857
4858 "use strict";
4859
4860
4861 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4862 Object.defineProperty(exports, "__esModule", ({
4863 value: true
4864 }));
4865 exports["default"] = void 0;
4866 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4867 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
4868 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4869 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4870 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4871 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4872 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4873 var _commandCallbackBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-callback-base */ "../modules/web-cli/assets/js/modules/command-callback-base.js"));
4874 var _toolkit = __webpack_require__(/*! @reduxjs/toolkit */ "../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js");
4875 var _module = _interopRequireDefault(__webpack_require__(/*! elementor/assets/dev/js/modules/imports/module.js */ "../assets/dev/js/modules/imports/module.js"));
4876 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
4877 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4878 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4879 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4880 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4881 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4882 /**
4883 * @typedef {import('./command-infra')} CommandInfra
4884 * @typedef {import('./hook-base')} HookBase
4885 * @typedef {import('../core/states/ui-state-base')} UiStateBase
4886 */
4887 var ComponentBase = exports["default"] = /*#__PURE__*/function (_Module) {
4888 function ComponentBase() {
4889 (0, _classCallCheck2.default)(this, ComponentBase);
4890 return _callSuper(this, ComponentBase, arguments);
4891 }
4892 (0, _inherits2.default)(ComponentBase, _Module);
4893 return (0, _createClass2.default)(ComponentBase, [{
4894 key: "__construct",
4895 value: function __construct() {
4896 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4897 if (args.manager) {
4898 this.manager = args.manager;
4899 }
4900 this.commands = this.defaultCommands();
4901 this.commandsInternal = this.defaultCommandsInternal();
4902 this.hooks = this.defaultHooks();
4903 this.routes = this.defaultRoutes();
4904 this.tabs = this.defaultTabs();
4905 this.shortcuts = this.defaultShortcuts();
4906 this.utils = this.defaultUtils();
4907 this.data = this.defaultData();
4908 this.uiStates = this.defaultUiStates();
4909 this.states = this.defaultStates();
4910 this.defaultRoute = '';
4911 this.currentTab = '';
4912 }
4913 }, {
4914 key: "registerAPI",
4915 value: function registerAPI() {
4916 var _this = this;
4917 Object.entries(this.getTabs()).forEach(function (tab) {
4918 return _this.registerTabRoute(tab[0]);
4919 });
4920 Object.entries(this.getRoutes()).forEach(function (_ref) {
4921 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
4922 route = _ref2[0],
4923 callback = _ref2[1];
4924 return _this.registerRoute(route, callback);
4925 });
4926 Object.entries(this.getCommands()).forEach(function (_ref3) {
4927 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
4928 command = _ref4[0],
4929 callback = _ref4[1];
4930 return _this.registerCommand(command, callback);
4931 });
4932 Object.entries(this.getCommandsInternal()).forEach(function (_ref5) {
4933 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
4934 command = _ref6[0],
4935 callback = _ref6[1];
4936 return _this.registerCommandInternal(command, callback);
4937 });
4938 Object.values(this.getHooks()).forEach(function (instance) {
4939 return _this.registerHook(instance);
4940 });
4941 Object.entries(this.getData()).forEach(function (_ref7) {
4942 var _ref8 = (0, _slicedToArray2.default)(_ref7, 2),
4943 command = _ref8[0],
4944 callback = _ref8[1];
4945 return _this.registerData(command, callback);
4946 });
4947 Object.values(this.getUiStates()).forEach(function (instance) {
4948 return _this.registerUiState(instance);
4949 });
4950 Object.entries(this.getStates()).forEach(function (_ref9) {
4951 var _ref0 = (0, _slicedToArray2.default)(_ref9, 2),
4952 id = _ref0[0],
4953 state = _ref0[1];
4954 return _this.registerState(id, state);
4955 });
4956 }
4957
4958 // eslint-disable-next-line jsdoc/require-returns-check
4959 /**
4960 * @return {string} namespace
4961 */
4962 }, {
4963 key: "getNamespace",
4964 value: function getNamespace() {
4965 (0, _forceMethodImplementation.default)();
4966 }
4967
4968 /**
4969 * @deprecated since 3.7.0, use `getServiceName()` instead.
4970 */
4971 }, {
4972 key: "getRootContainer",
4973 value: function getRootContainer() {
4974 _deprecation.default.deprecated('getRootContainer()', '3.7.0', 'getServiceName()');
4975 return this.getServiceName();
4976 }
4977 }, {
4978 key: "getServiceName",
4979 value: function getServiceName() {
4980 return this.getNamespace().split('/')[0];
4981 }
4982 }, {
4983 key: "store",
4984 get: function get() {
4985 return $e.store.get(this.getNamespace());
4986 }
4987 }, {
4988 key: "defaultTabs",
4989 value: function defaultTabs() {
4990 return {};
4991 }
4992 }, {
4993 key: "defaultRoutes",
4994 value: function defaultRoutes() {
4995 return {};
4996 }
4997 }, {
4998 key: "defaultCommands",
4999 value: function defaultCommands() {
5000 return {};
5001 }
5002 }, {
5003 key: "defaultCommandsInternal",
5004 value: function defaultCommandsInternal() {
5005 return {};
5006 }
5007 }, {
5008 key: "defaultHooks",
5009 value: function defaultHooks() {
5010 return {};
5011 }
5012
5013 /**
5014 * Get the component's default UI states.
5015 *
5016 * @return {Object} default UI states
5017 */
5018 }, {
5019 key: "defaultUiStates",
5020 value: function defaultUiStates() {
5021 return {};
5022 }
5023
5024 /**
5025 * Get the component's Redux slice settings.
5026 *
5027 * @return {Object} Redux slice settings
5028 */
5029 }, {
5030 key: "defaultStates",
5031 value: function defaultStates() {
5032 return {};
5033 }
5034 }, {
5035 key: "defaultShortcuts",
5036 value: function defaultShortcuts() {
5037 return {};
5038 }
5039 }, {
5040 key: "defaultUtils",
5041 value: function defaultUtils() {
5042 return {};
5043 }
5044 }, {
5045 key: "defaultData",
5046 value: function defaultData() {
5047 return {};
5048 }
5049 }, {
5050 key: "getCommands",
5051 value: function getCommands() {
5052 return this.commands;
5053 }
5054 }, {
5055 key: "getCommandsInternal",
5056 value: function getCommandsInternal() {
5057 return this.commandsInternal;
5058 }
5059 }, {
5060 key: "getHooks",
5061 value: function getHooks() {
5062 return this.hooks;
5063 }
5064
5065 /**
5066 * Retrieve the component's UI states.
5067 *
5068 * @return {Object} UI states
5069 */
5070 }, {
5071 key: "getUiStates",
5072 value: function getUiStates() {
5073 return this.uiStates;
5074 }
5075
5076 /**
5077 * Retrieve the component's Redux Slice.
5078 *
5079 * @return {Object} Redux Slice
5080 */
5081 }, {
5082 key: "getStates",
5083 value: function getStates() {
5084 return this.states;
5085 }
5086 }, {
5087 key: "getRoutes",
5088 value: function getRoutes() {
5089 return this.routes;
5090 }
5091 }, {
5092 key: "getTabs",
5093 value: function getTabs() {
5094 return this.tabs;
5095 }
5096 }, {
5097 key: "getShortcuts",
5098 value: function getShortcuts() {
5099 return this.shortcuts;
5100 }
5101 }, {
5102 key: "getData",
5103 value: function getData() {
5104 return this.data;
5105 }
5106
5107 /**
5108 * @param {string} command
5109 * @param {(()=>{}|CommandInfra)} context
5110 * @param {'default'|'internal'|'data'} commandsType
5111 */
5112 }, {
5113 key: "registerCommand",
5114 value: function registerCommand(command, context) {
5115 var commandsType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';
5116 var commandsManager;
5117 switch (commandsType) {
5118 case 'default':
5119 commandsManager = $e.commands;
5120 break;
5121 case 'internal':
5122 commandsManager = $e.commandsInternal;
5123 break;
5124 case 'data':
5125 commandsManager = $e.data;
5126 break;
5127 default:
5128 throw new Error("Invalid commands type: '".concat(command, "'"));
5129 }
5130 var fullCommand = this.getNamespace() + '/' + command,
5131 instanceType = context.getInstanceType ? context.getInstanceType() : false,
5132 registerConfig = {
5133 command: fullCommand,
5134 component: this
5135 };
5136
5137 // Support pure callback.
5138 if (!instanceType) {
5139 if ($e.devTools) {
5140 $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
5141 }
5142 registerConfig.callback = context;
5143
5144 // Unique class.
5145 context = /*#__PURE__*/function (_CommandCallbackBase) {
5146 function context() {
5147 (0, _classCallCheck2.default)(this, context);
5148 return _callSuper(this, context, arguments);
5149 }
5150 (0, _inherits2.default)(context, _CommandCallbackBase);
5151 return (0, _createClass2.default)(context);
5152 }(_commandCallbackBase.default);
5153 }
5154 context.setRegisterConfig(registerConfig);
5155 commandsManager.register(this, command, context);
5156 }
5157
5158 /**
5159 * @param {HookBase} instance
5160 */
5161 }, {
5162 key: "registerHook",
5163 value: function registerHook(instance) {
5164 return instance.register();
5165 }
5166 }, {
5167 key: "registerCommandInternal",
5168 value: function registerCommandInternal(command, context) {
5169 this.registerCommand(command, context, 'internal');
5170 }
5171
5172 /**
5173 * Register a UI state.
5174 *
5175 * @param {UiStateBase} instance - UI state instance.
5176 *
5177 * @return {void}
5178 */
5179 }, {
5180 key: "registerUiState",
5181 value: function registerUiState(instance) {
5182 $e.uiStates.register(instance);
5183 }
5184
5185 /**
5186 * Register a Redux Slice.
5187 *
5188 * @param {string} id - State id.
5189 * @param {Object} stateConfig - The state config.
5190 *
5191 * @return {void}
5192 */
5193 }, {
5194 key: "registerState",
5195 value: function registerState(id, stateConfig) {
5196 id = this.getNamespace() + (id ? "/".concat(id) : '');
5197 var slice = (0, _toolkit.createSlice)(_objectSpread(_objectSpread({}, stateConfig), {}, {
5198 name: id
5199 }));
5200 $e.store.register(id, slice);
5201 }
5202 }, {
5203 key: "registerRoute",
5204 value: function registerRoute(route, callback) {
5205 $e.routes.register(this, route, callback);
5206 }
5207 }, {
5208 key: "registerData",
5209 value: function registerData(command, context) {
5210 this.registerCommand(command, context, 'data');
5211 }
5212 }, {
5213 key: "unregisterRoute",
5214 value: function unregisterRoute(route) {
5215 $e.routes.unregister(this, route);
5216 }
5217 }, {
5218 key: "registerTabRoute",
5219 value: function registerTabRoute(tab) {
5220 var _this2 = this;
5221 this.registerRoute(tab, function (args) {
5222 return _this2.activateTab(tab, args);
5223 });
5224 }
5225 }, {
5226 key: "dependency",
5227 value: function dependency() {
5228 return true;
5229 }
5230 }, {
5231 key: "open",
5232 value: function open() {
5233 return true;
5234 }
5235 }, {
5236 key: "close",
5237 value: function close() {
5238 if (!this.isOpen) {
5239 return false;
5240 }
5241 this.isOpen = false;
5242 this.inactivate();
5243 $e.routes.clearCurrent(this.getNamespace());
5244 $e.routes.clearHistory(this.getServiceName());
5245 return true;
5246 }
5247 }, {
5248 key: "activate",
5249 value: function activate() {
5250 $e.components.activate(this.getNamespace());
5251 }
5252 }, {
5253 key: "inactivate",
5254 value: function inactivate() {
5255 $e.components.inactivate(this.getNamespace());
5256 }
5257 }, {
5258 key: "isActive",
5259 value: function isActive() {
5260 return $e.components.isActive(this.getNamespace());
5261 }
5262 }, {
5263 key: "onRoute",
5264 value: function onRoute(route) {
5265 this.toggleRouteClass(route, true);
5266 this.toggleHistoryClass();
5267 this.activate();
5268 this.trigger('route/open', route);
5269 }
5270 }, {
5271 key: "onCloseRoute",
5272 value: function onCloseRoute(route) {
5273 this.toggleRouteClass(route, false);
5274 this.inactivate();
5275 this.trigger('route/close', route);
5276 }
5277 }, {
5278 key: "setDefaultRoute",
5279 value: function setDefaultRoute(route) {
5280 this.defaultRoute = this.getNamespace() + '/' + route;
5281 }
5282 }, {
5283 key: "getDefaultRoute",
5284 value: function getDefaultRoute() {
5285 return this.defaultRoute;
5286 }
5287 }, {
5288 key: "removeTab",
5289 value: function removeTab(tab) {
5290 delete this.tabs[tab];
5291 this.unregisterRoute(tab);
5292 }
5293 }, {
5294 key: "hasTab",
5295 value: function hasTab(tab) {
5296 return !!this.tabs[tab];
5297 }
5298 }, {
5299 key: "addTab",
5300 value: function addTab(tab, args, position) {
5301 var _this3 = this;
5302 this.tabs[tab] = args;
5303 // It can be 0.
5304 if ('undefined' !== typeof position) {
5305 var newTabs = {};
5306 var ids = Object.keys(this.tabs);
5307 // Remove new tab
5308 ids.pop();
5309
5310 // Add it to position.
5311 ids.splice(position, 0, tab);
5312 ids.forEach(function (id) {
5313 newTabs[id] = _this3.tabs[id];
5314 });
5315 this.tabs = newTabs;
5316 }
5317 this.registerTabRoute(tab);
5318 }
5319 }, {
5320 key: "getTabsWrapperSelector",
5321 value: function getTabsWrapperSelector() {
5322 return '';
5323 }
5324 }, {
5325 key: "getTabRoute",
5326 value: function getTabRoute(tab) {
5327 return this.getNamespace() + '/' + tab;
5328 }
5329 }, {
5330 key: "renderTab",
5331 value: function renderTab(tab) {} // eslint-disable-line
5332 }, {
5333 key: "activateTab",
5334 value: function activateTab(tab, args) {
5335 var _this4 = this;
5336 this.renderTab(tab, args);
5337 jQuery(this.getTabsWrapperSelector() + ' .elementor-component-tab').off('click').on('click', function (event) {
5338 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
5339 }).removeClass('elementor-active').filter('[data-tab="' + tab + '"]').addClass('elementor-active');
5340 }
5341 }, {
5342 key: "getActiveTabConfig",
5343 value: function getActiveTabConfig() {
5344 return this.tabs[this.currentTab] || {};
5345 }
5346 }, {
5347 key: "getBodyClass",
5348 value: function getBodyClass(route) {
5349 return 'e-route-' + route.replace(/\//g, '-');
5350 }
5351
5352 /**
5353 * If command includes uppercase character convert it to lowercase and add `-`.
5354 * e.g: `CopyAll` is converted to `copy-all`.
5355 *
5356 * @param {string} commandName
5357 */
5358 }, {
5359 key: "normalizeCommandName",
5360 value: function normalizeCommandName(commandName) {
5361 return commandName.replace(/[A-Z]/g, function (match, offset) {
5362 return (offset > 0 ? '-' : '') + match.toLowerCase();
5363 });
5364 }
5365
5366 /**
5367 * @param {{}} commandsFromImport
5368 * @return {{}} imported commands
5369 */
5370 }, {
5371 key: "importCommands",
5372 value: function importCommands(commandsFromImport) {
5373 var _this5 = this;
5374 var commands = {};
5375
5376 // Convert `Commands` to `ComponentBase` workable format.
5377 Object.entries(commandsFromImport).forEach(function (_ref1) {
5378 var _ref10 = (0, _slicedToArray2.default)(_ref1, 2),
5379 className = _ref10[0],
5380 Class = _ref10[1];
5381 var command = _this5.normalizeCommandName(className);
5382 commands[command] = Class;
5383 });
5384 return commands;
5385 }
5386 }, {
5387 key: "importHooks",
5388 value: function importHooks(hooksFromImport) {
5389 var hooks = {};
5390 for (var key in hooksFromImport) {
5391 var hook = new hooksFromImport[key]();
5392 hooks[hook.getId()] = hook;
5393 }
5394 return hooks;
5395 }
5396
5397 /**
5398 * Import & initialize the component's UI states.
5399 * Should be used inside `defaultUiState()`.
5400 *
5401 * @param {Object} statesFromImport - UI states from import.
5402 *
5403 * @return {Object} UI States
5404 */
5405 }, {
5406 key: "importUiStates",
5407 value: function importUiStates(statesFromImport) {
5408 var _this6 = this;
5409 var uiStates = {};
5410 Object.values(statesFromImport).forEach(function (className) {
5411 var uiState = new className(_this6);
5412 uiStates[uiState.getId()] = uiState;
5413 });
5414 return uiStates;
5415 }
5416
5417 /**
5418 * Set a UI state value.
5419 * TODO: Should we provide such function? Maybe the developer should implicitly pass the full state ID?
5420 *
5421 * @param {string} state - Non-prefixed state ID.
5422 * @param {*} value - New state value.
5423 *
5424 * @return {void}
5425 */
5426 }, {
5427 key: "setUiState",
5428 value: function setUiState(state, value) {
5429 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
5430 }
5431 }, {
5432 key: "toggleRouteClass",
5433 value: function toggleRouteClass(route, state) {
5434 document.body.classList.toggle(this.getBodyClass(route), state);
5435 }
5436 }, {
5437 key: "toggleHistoryClass",
5438 value: function toggleHistoryClass() {
5439 document.body.classList.toggle('e-routes-has-history', !!$e.routes.getHistory(this.getServiceName()).length);
5440 }
5441 }]);
5442 }(_module.default);
5443
5444 /***/ }),
5445
5446 /***/ "../modules/web-cli/assets/js/modules/component-modal-base.js":
5447 /*!********************************************************************!*\
5448 !*** ../modules/web-cli/assets/js/modules/component-modal-base.js ***!
5449 \********************************************************************/
5450 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5451
5452 "use strict";
5453
5454
5455 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5456 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
5457 Object.defineProperty(exports, "__esModule", ({
5458 value: true
5459 }));
5460 exports["default"] = void 0;
5461 var _readOnlyError2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/readOnlyError */ "../node_modules/@babel/runtime/helpers/readOnlyError.js"));
5462 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5463 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5464 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5465 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5466 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
5467 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5468 var _componentBase = _interopRequireDefault(__webpack_require__(/*! ./component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
5469 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../modules/web-cli/assets/js/modules/commands/index.js"));
5470 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
5471 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
5472 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
5473 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5474 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
5475 var ComponentModalBase = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
5476 function ComponentModalBase() {
5477 (0, _classCallCheck2.default)(this, ComponentModalBase);
5478 return _callSuper(this, ComponentModalBase, arguments);
5479 }
5480 (0, _inherits2.default)(ComponentModalBase, _ComponentBase);
5481 return (0, _createClass2.default)(ComponentModalBase, [{
5482 key: "registerAPI",
5483 value: function registerAPI() {
5484 var _this = this;
5485 _superPropGet(ComponentModalBase, "registerAPI", this, 3)([]);
5486 $e.shortcuts.register('esc', {
5487 scopes: [this.getNamespace()],
5488 callback: function callback() {
5489 return _this.close();
5490 }
5491 });
5492 }
5493 }, {
5494 key: "defaultCommands",
5495 value: function defaultCommands() {
5496 return this.importCommands(commands);
5497 }
5498 }, {
5499 key: "defaultRoutes",
5500 value: function defaultRoutes() {
5501 return {
5502 '': function _() {/* Nothing to do, it's already rendered. */}
5503 };
5504 }
5505 }, {
5506 key: "open",
5507 value: function open() {
5508 var _this2 = this;
5509 if (!this.layout) {
5510 var layout = this.getModalLayout();
5511 this.layout = new layout({
5512 component: this
5513 });
5514 this.layout.getModal().on('hide', function () {
5515 return _this2.close();
5516 });
5517 }
5518 this.layout.showModal();
5519 return true;
5520 }
5521 }, {
5522 key: "close",
5523 value: function close() {
5524 if (!_superPropGet(ComponentModalBase, "close", this, 3)([])) {
5525 return false;
5526 }
5527 var close = elementor.hooks.applyFilters('component/modal/close', this.layout.getModal().hide.bind(this.layout.getModal()), this);
5528 close();
5529 return true;
5530 }
5531 }, {
5532 key: "getModalLayout",
5533 value: function getModalLayout() {
5534 (0, _forceMethodImplementation.default)();
5535 }
5536 }]);
5537 }(_componentBase.default);
5538
5539 /***/ }),
5540
5541 /***/ "../modules/web-cli/assets/js/utils/console.js":
5542 /*!*****************************************************!*\
5543 !*** ../modules/web-cli/assets/js/utils/console.js ***!
5544 \*****************************************************/
5545 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5546
5547 "use strict";
5548
5549
5550 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5551 Object.defineProperty(exports, "__esModule", ({
5552 value: true
5553 }));
5554 exports["default"] = void 0;
5555 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5556 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5557 var Console = exports["default"] = /*#__PURE__*/function () {
5558 function Console() {
5559 (0, _classCallCheck2.default)(this, Console);
5560 }
5561 return (0, _createClass2.default)(Console, null, [{
5562 key: "error",
5563 value: function error(message) {
5564 // Show an error if devTools is available.
5565 if ($e.devTools) {
5566 $e.devTools.log.error(message);
5567 }
5568
5569 // If not a 'Hook-Break' then show error.
5570 if (!(message instanceof $e.modules.HookBreak)) {
5571 // eslint-disable-next-line no-console
5572 console.error(message);
5573 }
5574 }
5575 }, {
5576 key: "warn",
5577 value: function warn() {
5578 var _console;
5579 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
5580 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5581 args[_key] = arguments[_key];
5582 }
5583 args.unshift('%c %c', style, '');
5584 (_console = console).warn.apply(_console, args); // eslint-disable-line no-console
5585 }
5586 }]);
5587 }();
5588
5589 /***/ }),
5590
5591 /***/ "../modules/web-cli/assets/js/utils/deprecation.js":
5592 /*!*********************************************************!*\
5593 !*** ../modules/web-cli/assets/js/utils/deprecation.js ***!
5594 \*********************************************************/
5595 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5596
5597 "use strict";
5598
5599
5600 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5601 Object.defineProperty(exports, "__esModule", ({
5602 value: true
5603 }));
5604 exports["default"] = void 0;
5605 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
5606 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5607 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5608 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
5609 // Copied from `modules/dev-tools/assets/js/deprecation.js`
5610 /**
5611 * @typedef {Object} Version
5612 * @property {number} major1 The first number
5613 * @property {number} major2 The second number
5614 * @property {number} minor The third number
5615 * @property {string} build The fourth number
5616 */
5617
5618 var softDeprecated = function softDeprecated(name, version, replacement) {
5619 if (elementorWebCliConfig.isDebug) {
5620 deprecatedMessage('soft', name, version, replacement);
5621 }
5622 };
5623 var hardDeprecated = function hardDeprecated(name, version, replacement) {
5624 deprecatedMessage('hard', name, version, replacement);
5625 };
5626 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
5627 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
5628 if (replacement) {
5629 message += " - Use `".concat(replacement, "` instead");
5630 }
5631 _console.default.warn(message);
5632 };
5633 var Deprecation = exports["default"] = /*#__PURE__*/function () {
5634 function Deprecation() {
5635 (0, _classCallCheck2.default)(this, Deprecation);
5636 }
5637 return (0, _createClass2.default)(Deprecation, null, [{
5638 key: "deprecated",
5639 value: function deprecated(name, version, replacement) {
5640 if (this.isHardDeprecated(version)) {
5641 hardDeprecated(name, version, replacement);
5642 } else {
5643 softDeprecated(name, version, replacement);
5644 }
5645 }
5646
5647 /**
5648 * @param {string} version
5649 *
5650 * @return {Version}
5651 */
5652 }, {
5653 key: "parseVersion",
5654 value: function parseVersion(version) {
5655 var versionParts = version.split('.');
5656 if (versionParts.length < 3 || versionParts.length > 4) {
5657 throw new RangeError('Invalid Semantic Version string provided');
5658 }
5659 var _versionParts = (0, _slicedToArray2.default)(versionParts, 4),
5660 major1 = _versionParts[0],
5661 major2 = _versionParts[1],
5662 minor = _versionParts[2],
5663 _versionParts$ = _versionParts[3],
5664 build = _versionParts$ === void 0 ? '' : _versionParts$;
5665 return {
5666 major1: parseInt(major1),
5667 major2: parseInt(major2),
5668 minor: parseInt(minor),
5669 build: build
5670 };
5671 }
5672
5673 /**
5674 * Get total of major.
5675 *
5676 * Since `get_total_major` cannot determine how much really versions between 2.9.0 and 3.3.0 if there is 2.10.0 version for example,
5677 * versions with major2 more then 9 will be added to total.
5678 *
5679 * @param {Version} versionObj
5680 *
5681 * @return {number}
5682 */
5683 }, {
5684 key: "getTotalMajor",
5685 value: function getTotalMajor(versionObj) {
5686 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
5687 total = Number((total / 10).toFixed(0));
5688 if (versionObj.major2 > 9) {
5689 total = versionObj.major2 - 9;
5690 }
5691 return total;
5692 }
5693
5694 /**
5695 * @param {string} version1
5696 * @param {string} version2
5697 *
5698 * @return {number}
5699 */
5700 }, {
5701 key: "compareVersion",
5702 value: function compareVersion(version1, version2) {
5703 var _this = this;
5704 return [this.parseVersion(version1), this.parseVersion(version2)].map(function (versionObj) {
5705 return _this.getTotalMajor(versionObj);
5706 }).reduce(function (acc, major) {
5707 return acc - major;
5708 });
5709 }
5710
5711 /**
5712 * @param {string} version
5713 *
5714 * @return {boolean}
5715 */
5716 }, {
5717 key: "isSoftDeprecated",
5718 value: function isSoftDeprecated(version) {
5719 var total = this.compareVersion(version, elementorWebCliConfig.version);
5720 return total <= 4;
5721 }
5722
5723 /**
5724 * @param {string} version
5725 * @return {boolean}
5726 */
5727 }, {
5728 key: "isHardDeprecated",
5729 value: function isHardDeprecated(version) {
5730 var total = this.compareVersion(version, elementorWebCliConfig.version);
5731 return total < 0 || total >= 8;
5732 }
5733 }]);
5734 }();
5735
5736 /***/ }),
5737
5738 /***/ "../modules/web-cli/assets/js/utils/force-method-implementation.js":
5739 /*!*************************************************************************!*\
5740 !*** ../modules/web-cli/assets/js/utils/force-method-implementation.js ***!
5741 \*************************************************************************/
5742 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5743
5744 "use strict";
5745
5746
5747 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5748 Object.defineProperty(exports, "__esModule", ({
5749 value: true
5750 }));
5751 exports["default"] = exports.ForceMethodImplementation = void 0;
5752 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5753 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5754 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5755 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5756 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5757 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
5758 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
5759 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5760 // TODO: Copied from `assets/dev/js/modules/imports/force-method-implementation.js`;
5761 var ForceMethodImplementation = exports.ForceMethodImplementation = /*#__PURE__*/function (_Error) {
5762 function ForceMethodImplementation() {
5763 var _this;
5764 var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5765 (0, _classCallCheck2.default)(this, ForceMethodImplementation);
5766 _this = _callSuper(this, ForceMethodImplementation, ["".concat(info.isStatic ? 'static ' : '').concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
5767 Error.captureStackTrace(_this, ForceMethodImplementation);
5768 return _this;
5769 }
5770 (0, _inherits2.default)(ForceMethodImplementation, _Error);
5771 return (0, _createClass2.default)(ForceMethodImplementation);
5772 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
5773 var _default = exports["default"] = function _default() {
5774 var stack = Error().stack,
5775 caller = stack.split('\n')[2].trim(),
5776 callerName = caller.startsWith('at new') ? 'constructor' : caller.split(' ')[1],
5777 info = {};
5778 info.functionName = callerName;
5779 info.fullName = callerName;
5780 if (info.functionName.includes('.')) {
5781 var parts = info.functionName.split('.');
5782 info.className = parts[0];
5783 info.functionName = parts[1];
5784 } else {
5785 info.isStatic = true;
5786 }
5787 throw new ForceMethodImplementation(info);
5788 };
5789
5790 /***/ }),
5791
5792 /***/ "../node_modules/@babel/runtime/helpers/OverloadYield.js":
5793 /*!***************************************************************!*\
5794 !*** ../node_modules/@babel/runtime/helpers/OverloadYield.js ***!
5795 \***************************************************************/
5796 /***/ ((module) => {
5797
5798 function _OverloadYield(e, d) {
5799 this.v = e, this.k = d;
5800 }
5801 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
5802
5803 /***/ }),
5804
5805 /***/ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
5806 /*!******************************************************************!*\
5807 !*** ../node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
5808 \******************************************************************/
5809 /***/ ((module) => {
5810
5811 function _arrayLikeToArray(r, a) {
5812 (null == a || a > r.length) && (a = r.length);
5813 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
5814 return n;
5815 }
5816 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
5817
5818 /***/ }),
5819
5820 /***/ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js":
5821 /*!****************************************************************!*\
5822 !*** ../node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
5823 \****************************************************************/
5824 /***/ ((module) => {
5825
5826 function _arrayWithHoles(r) {
5827 if (Array.isArray(r)) return r;
5828 }
5829 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
5830
5831 /***/ }),
5832
5833 /***/ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js":
5834 /*!***********************************************************************!*\
5835 !*** ../node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
5836 \***********************************************************************/
5837 /***/ ((module) => {
5838
5839 function _assertThisInitialized(e) {
5840 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
5841 return e;
5842 }
5843 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
5844
5845 /***/ }),
5846
5847 /***/ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js":
5848 /*!******************************************************************!*\
5849 !*** ../node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
5850 \******************************************************************/
5851 /***/ ((module) => {
5852
5853 function asyncGeneratorStep(n, t, e, r, o, a, c) {
5854 try {
5855 var i = n[a](c),
5856 u = i.value;
5857 } catch (n) {
5858 return void e(n);
5859 }
5860 i.done ? t(u) : Promise.resolve(u).then(r, o);
5861 }
5862 function _asyncToGenerator(n) {
5863 return function () {
5864 var t = this,
5865 e = arguments;
5866 return new Promise(function (r, o) {
5867 var a = n.apply(t, e);
5868 function _next(n) {
5869 asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5870 }
5871 function _throw(n) {
5872 asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5873 }
5874 _next(void 0);
5875 });
5876 };
5877 }
5878 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
5879
5880 /***/ }),
5881
5882 /***/ "../node_modules/@babel/runtime/helpers/classCallCheck.js":
5883 /*!****************************************************************!*\
5884 !*** ../node_modules/@babel/runtime/helpers/classCallCheck.js ***!
5885 \****************************************************************/
5886 /***/ ((module) => {
5887
5888 function _classCallCheck(a, n) {
5889 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
5890 }
5891 module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
5892
5893 /***/ }),
5894
5895 /***/ "../node_modules/@babel/runtime/helpers/construct.js":
5896 /*!***********************************************************!*\
5897 !*** ../node_modules/@babel/runtime/helpers/construct.js ***!
5898 \***********************************************************/
5899 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5900
5901 var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct.js */ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js");
5902 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5903 function _construct(t, e, r) {
5904 if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
5905 var o = [null];
5906 o.push.apply(o, e);
5907 var p = new (t.bind.apply(t, o))();
5908 return r && setPrototypeOf(p, r.prototype), p;
5909 }
5910 module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
5911
5912 /***/ }),
5913
5914 /***/ "../node_modules/@babel/runtime/helpers/createClass.js":
5915 /*!*************************************************************!*\
5916 !*** ../node_modules/@babel/runtime/helpers/createClass.js ***!
5917 \*************************************************************/
5918 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5919
5920 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5921 function _defineProperties(e, r) {
5922 for (var t = 0; t < r.length; t++) {
5923 var o = r[t];
5924 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
5925 }
5926 }
5927 function _createClass(e, r, t) {
5928 return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
5929 writable: !1
5930 }), e;
5931 }
5932 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
5933
5934 /***/ }),
5935
5936 /***/ "../node_modules/@babel/runtime/helpers/defineProperty.js":
5937 /*!****************************************************************!*\
5938 !*** ../node_modules/@babel/runtime/helpers/defineProperty.js ***!
5939 \****************************************************************/
5940 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5941
5942 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5943 function _defineProperty(e, r, t) {
5944 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
5945 value: t,
5946 enumerable: !0,
5947 configurable: !0,
5948 writable: !0
5949 }) : e[r] = t, e;
5950 }
5951 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
5952
5953 /***/ }),
5954
5955 /***/ "../node_modules/@babel/runtime/helpers/esm/defineProperty.js":
5956 /*!********************************************************************!*\
5957 !*** ../node_modules/@babel/runtime/helpers/esm/defineProperty.js ***!
5958 \********************************************************************/
5959 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5960
5961 "use strict";
5962 __webpack_require__.r(__webpack_exports__);
5963 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5964 /* harmony export */ "default": () => (/* binding */ _defineProperty)
5965 /* harmony export */ });
5966 /* harmony import */ var _toPropertyKey_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js");
5967
5968 function _defineProperty(e, r, t) {
5969 return (r = (0,_toPropertyKey_js__WEBPACK_IMPORTED_MODULE_0__["default"])(r)) in e ? Object.defineProperty(e, r, {
5970 value: t,
5971 enumerable: !0,
5972 configurable: !0,
5973 writable: !0
5974 }) : e[r] = t, e;
5975 }
5976
5977
5978 /***/ }),
5979
5980 /***/ "../node_modules/@babel/runtime/helpers/esm/objectSpread2.js":
5981 /*!*******************************************************************!*\
5982 !*** ../node_modules/@babel/runtime/helpers/esm/objectSpread2.js ***!
5983 \*******************************************************************/
5984 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5985
5986 "use strict";
5987 __webpack_require__.r(__webpack_exports__);
5988 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5989 /* harmony export */ "default": () => (/* binding */ _objectSpread2)
5990 /* harmony export */ });
5991 /* harmony import */ var _defineProperty_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defineProperty.js */ "../node_modules/@babel/runtime/helpers/esm/defineProperty.js");
5992
5993 function ownKeys(e, r) {
5994 var t = Object.keys(e);
5995 if (Object.getOwnPropertySymbols) {
5996 var o = Object.getOwnPropertySymbols(e);
5997 r && (o = o.filter(function (r) {
5998 return Object.getOwnPropertyDescriptor(e, r).enumerable;
5999 })), t.push.apply(t, o);
6000 }
6001 return t;
6002 }
6003 function _objectSpread2(e) {
6004 for (var r = 1; r < arguments.length; r++) {
6005 var t = null != arguments[r] ? arguments[r] : {};
6006 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
6007 (0,_defineProperty_js__WEBPACK_IMPORTED_MODULE_0__["default"])(e, r, t[r]);
6008 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
6009 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
6010 });
6011 }
6012 return e;
6013 }
6014
6015
6016 /***/ }),
6017
6018 /***/ "../node_modules/@babel/runtime/helpers/esm/toPrimitive.js":
6019 /*!*****************************************************************!*\
6020 !*** ../node_modules/@babel/runtime/helpers/esm/toPrimitive.js ***!
6021 \*****************************************************************/
6022 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6023
6024 "use strict";
6025 __webpack_require__.r(__webpack_exports__);
6026 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6027 /* harmony export */ "default": () => (/* binding */ toPrimitive)
6028 /* harmony export */ });
6029 /* harmony import */ var _typeof_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/esm/typeof.js");
6030
6031 function toPrimitive(t, r) {
6032 if ("object" != (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(t) || !t) return t;
6033 var e = t[Symbol.toPrimitive];
6034 if (void 0 !== e) {
6035 var i = e.call(t, r || "default");
6036 if ("object" != (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(i)) return i;
6037 throw new TypeError("@@toPrimitive must return a primitive value.");
6038 }
6039 return ("string" === r ? String : Number)(t);
6040 }
6041
6042
6043 /***/ }),
6044
6045 /***/ "../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js":
6046 /*!*******************************************************************!*\
6047 !*** ../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js ***!
6048 \*******************************************************************/
6049 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6050
6051 "use strict";
6052 __webpack_require__.r(__webpack_exports__);
6053 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6054 /* harmony export */ "default": () => (/* binding */ toPropertyKey)
6055 /* harmony export */ });
6056 /* harmony import */ var _typeof_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/esm/typeof.js");
6057 /* harmony import */ var _toPrimitive_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/esm/toPrimitive.js");
6058
6059
6060 function toPropertyKey(t) {
6061 var i = (0,_toPrimitive_js__WEBPACK_IMPORTED_MODULE_1__["default"])(t, "string");
6062 return "symbol" == (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(i) ? i : i + "";
6063 }
6064
6065
6066 /***/ }),
6067
6068 /***/ "../node_modules/@babel/runtime/helpers/esm/typeof.js":
6069 /*!************************************************************!*\
6070 !*** ../node_modules/@babel/runtime/helpers/esm/typeof.js ***!
6071 \************************************************************/
6072 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6073
6074 "use strict";
6075 __webpack_require__.r(__webpack_exports__);
6076 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6077 /* harmony export */ "default": () => (/* binding */ _typeof)
6078 /* harmony export */ });
6079 function _typeof(o) {
6080 "@babel/helpers - typeof";
6081
6082 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6083 return typeof o;
6084 } : function (o) {
6085 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6086 }, _typeof(o);
6087 }
6088
6089
6090 /***/ }),
6091
6092 /***/ "../node_modules/@babel/runtime/helpers/get.js":
6093 /*!*****************************************************!*\
6094 !*** ../node_modules/@babel/runtime/helpers/get.js ***!
6095 \*****************************************************/
6096 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6097
6098 var superPropBase = __webpack_require__(/*! ./superPropBase.js */ "../node_modules/@babel/runtime/helpers/superPropBase.js");
6099 function _get() {
6100 return module.exports = _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
6101 var p = superPropBase(e, t);
6102 if (p) {
6103 var n = Object.getOwnPropertyDescriptor(p, t);
6104 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
6105 }
6106 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _get.apply(null, arguments);
6107 }
6108 module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
6109
6110 /***/ }),
6111
6112 /***/ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js":
6113 /*!****************************************************************!*\
6114 !*** ../node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
6115 \****************************************************************/
6116 /***/ ((module) => {
6117
6118 function _getPrototypeOf(t) {
6119 return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
6120 return t.__proto__ || Object.getPrototypeOf(t);
6121 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _getPrototypeOf(t);
6122 }
6123 module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6124
6125 /***/ }),
6126
6127 /***/ "../node_modules/@babel/runtime/helpers/inherits.js":
6128 /*!**********************************************************!*\
6129 !*** ../node_modules/@babel/runtime/helpers/inherits.js ***!
6130 \**********************************************************/
6131 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6132
6133 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6134 function _inherits(t, e) {
6135 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
6136 t.prototype = Object.create(e && e.prototype, {
6137 constructor: {
6138 value: t,
6139 writable: !0,
6140 configurable: !0
6141 }
6142 }), Object.defineProperty(t, "prototype", {
6143 writable: !1
6144 }), e && setPrototypeOf(t, e);
6145 }
6146 module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
6147
6148 /***/ }),
6149
6150 /***/ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js":
6151 /*!***********************************************************************!*\
6152 !*** ../node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
6153 \***********************************************************************/
6154 /***/ ((module) => {
6155
6156 function _interopRequireDefault(e) {
6157 return e && e.__esModule ? e : {
6158 "default": e
6159 };
6160 }
6161 module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
6162
6163 /***/ }),
6164
6165 /***/ "../node_modules/@babel/runtime/helpers/isNativeFunction.js":
6166 /*!******************************************************************!*\
6167 !*** ../node_modules/@babel/runtime/helpers/isNativeFunction.js ***!
6168 \******************************************************************/
6169 /***/ ((module) => {
6170
6171 function _isNativeFunction(t) {
6172 try {
6173 return -1 !== Function.toString.call(t).indexOf("[native code]");
6174 } catch (n) {
6175 return "function" == typeof t;
6176 }
6177 }
6178 module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports;
6179
6180 /***/ }),
6181
6182 /***/ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
6183 /*!**************************************************************************!*\
6184 !*** ../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
6185 \**************************************************************************/
6186 /***/ ((module) => {
6187
6188 function _isNativeReflectConstruct() {
6189 try {
6190 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
6191 } catch (t) {}
6192 return (module.exports = _isNativeReflectConstruct = function _isNativeReflectConstruct() {
6193 return !!t;
6194 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6195 }
6196 module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
6197
6198 /***/ }),
6199
6200 /***/ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
6201 /*!**********************************************************************!*\
6202 !*** ../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
6203 \**********************************************************************/
6204 /***/ ((module) => {
6205
6206 function _iterableToArrayLimit(r, l) {
6207 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
6208 if (null != t) {
6209 var e,
6210 n,
6211 i,
6212 u,
6213 a = [],
6214 f = !0,
6215 o = !1;
6216 try {
6217 if (i = (t = t.call(r)).next, 0 === l) {
6218 if (Object(t) !== t) return;
6219 f = !1;
6220 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
6221 } catch (r) {
6222 o = !0, n = r;
6223 } finally {
6224 try {
6225 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
6226 } finally {
6227 if (o) throw n;
6228 }
6229 }
6230 return a;
6231 }
6232 }
6233 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
6234
6235 /***/ }),
6236
6237 /***/ "../node_modules/@babel/runtime/helpers/nonIterableRest.js":
6238 /*!*****************************************************************!*\
6239 !*** ../node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
6240 \*****************************************************************/
6241 /***/ ((module) => {
6242
6243 function _nonIterableRest() {
6244 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6245 }
6246 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
6247
6248 /***/ }),
6249
6250 /***/ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
6251 /*!***************************************************************************!*\
6252 !*** ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
6253 \***************************************************************************/
6254 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6255
6256 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6257 var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized.js */ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js");
6258 function _possibleConstructorReturn(t, e) {
6259 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
6260 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
6261 return assertThisInitialized(t);
6262 }
6263 module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
6264
6265 /***/ }),
6266
6267 /***/ "../node_modules/@babel/runtime/helpers/readOnlyError.js":
6268 /*!***************************************************************!*\
6269 !*** ../node_modules/@babel/runtime/helpers/readOnlyError.js ***!
6270 \***************************************************************/
6271 /***/ ((module) => {
6272
6273 function _readOnlyError(r) {
6274 throw new TypeError('"' + r + '" is read-only');
6275 }
6276 module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;
6277
6278 /***/ }),
6279
6280 /***/ "../node_modules/@babel/runtime/helpers/regenerator.js":
6281 /*!*************************************************************!*\
6282 !*** ../node_modules/@babel/runtime/helpers/regenerator.js ***!
6283 \*************************************************************/
6284 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6285
6286 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6287 function _regenerator() {
6288 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
6289 var e,
6290 t,
6291 r = "function" == typeof Symbol ? Symbol : {},
6292 n = r.iterator || "@@iterator",
6293 o = r.toStringTag || "@@toStringTag";
6294 function i(r, n, o, i) {
6295 var c = n && n.prototype instanceof Generator ? n : Generator,
6296 u = Object.create(c.prototype);
6297 return regeneratorDefine(u, "_invoke", function (r, n, o) {
6298 var i,
6299 c,
6300 u,
6301 f = 0,
6302 p = o || [],
6303 y = !1,
6304 G = {
6305 p: 0,
6306 n: 0,
6307 v: e,
6308 a: d,
6309 f: d.bind(e, 4),
6310 d: function d(t, r) {
6311 return i = t, c = 0, u = e, G.n = r, a;
6312 }
6313 };
6314 function d(r, n) {
6315 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
6316 var o,
6317 i = p[t],
6318 d = G.p,
6319 l = i[2];
6320 r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
6321 }
6322 if (o || r > 1) return a;
6323 throw y = !0, n;
6324 }
6325 return function (o, p, l) {
6326 if (f > 1) throw TypeError("Generator is already running");
6327 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
6328 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
6329 try {
6330 if (f = 2, i) {
6331 if (c || (o = "next"), t = i[o]) {
6332 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
6333 if (!t.done) return t;
6334 u = t.value, c < 2 && (c = 0);
6335 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
6336 i = e;
6337 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
6338 } catch (t) {
6339 i = e, c = 1, u = t;
6340 } finally {
6341 f = 1;
6342 }
6343 }
6344 return {
6345 value: t,
6346 done: y
6347 };
6348 };
6349 }(r, o, i), !0), u;
6350 }
6351 var a = {};
6352 function Generator() {}
6353 function GeneratorFunction() {}
6354 function GeneratorFunctionPrototype() {}
6355 t = Object.getPrototypeOf;
6356 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () {
6357 return this;
6358 }), t),
6359 u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
6360 function f(e) {
6361 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
6362 }
6363 return GeneratorFunction.prototype = GeneratorFunctionPrototype, regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), regeneratorDefine(u), regeneratorDefine(u, o, "Generator"), regeneratorDefine(u, n, function () {
6364 return this;
6365 }), regeneratorDefine(u, "toString", function () {
6366 return "[object Generator]";
6367 }), (module.exports = _regenerator = function _regenerator() {
6368 return {
6369 w: i,
6370 m: f
6371 };
6372 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6373 }
6374 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6375
6376 /***/ }),
6377
6378 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js":
6379 /*!******************************************************************!*\
6380 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsync.js ***!
6381 \******************************************************************/
6382 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6383
6384 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6385 function _regeneratorAsync(n, e, r, t, o) {
6386 var a = regeneratorAsyncGen(n, e, r, t, o);
6387 return a.next().then(function (n) {
6388 return n.done ? n.value : a.next();
6389 });
6390 }
6391 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
6392
6393 /***/ }),
6394
6395 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js":
6396 /*!*********************************************************************!*\
6397 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js ***!
6398 \*********************************************************************/
6399 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6400
6401 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6402 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6403 function _regeneratorAsyncGen(r, e, t, o, n) {
6404 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
6405 }
6406 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
6407
6408 /***/ }),
6409
6410 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js":
6411 /*!**************************************************************************!*\
6412 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js ***!
6413 \**************************************************************************/
6414 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6415
6416 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6417 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6418 function AsyncIterator(t, e) {
6419 function n(r, o, i, f) {
6420 try {
6421 var c = t[r](o),
6422 u = c.value;
6423 return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
6424 n("next", t, i, f);
6425 }, function (t) {
6426 n("throw", t, i, f);
6427 }) : e.resolve(u).then(function (t) {
6428 c.value = t, i(c);
6429 }, function (t) {
6430 return n("throw", t, i, f);
6431 });
6432 } catch (t) {
6433 f(t);
6434 }
6435 }
6436 var r;
6437 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
6438 return this;
6439 })), regeneratorDefine(this, "_invoke", function (t, o, i) {
6440 function f() {
6441 return new e(function (e, r) {
6442 n(t, i, e, r);
6443 });
6444 }
6445 return r = r ? r.then(f, f) : f();
6446 }, !0);
6447 }
6448 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6449
6450 /***/ }),
6451
6452 /***/ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js":
6453 /*!*******************************************************************!*\
6454 !*** ../node_modules/@babel/runtime/helpers/regeneratorDefine.js ***!
6455 \*******************************************************************/
6456 /***/ ((module) => {
6457
6458 function _regeneratorDefine(e, r, n, t) {
6459 var i = Object.defineProperty;
6460 try {
6461 i({}, "", {});
6462 } catch (e) {
6463 i = 0;
6464 }
6465 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
6466 function o(r, n) {
6467 _regeneratorDefine(e, r, function (e) {
6468 return this._invoke(r, n, e);
6469 });
6470 }
6471 r ? i ? i(e, r, {
6472 value: n,
6473 enumerable: !t,
6474 configurable: !t,
6475 writable: !t
6476 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
6477 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
6478 }
6479 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
6480
6481 /***/ }),
6482
6483 /***/ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js":
6484 /*!*****************************************************************!*\
6485 !*** ../node_modules/@babel/runtime/helpers/regeneratorKeys.js ***!
6486 \*****************************************************************/
6487 /***/ ((module) => {
6488
6489 function _regeneratorKeys(e) {
6490 var n = Object(e),
6491 r = [];
6492 for (var t in n) r.unshift(t);
6493 return function e() {
6494 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
6495 return e.done = !0, e;
6496 };
6497 }
6498 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
6499
6500 /***/ }),
6501
6502 /***/ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js":
6503 /*!********************************************************************!*\
6504 !*** ../node_modules/@babel/runtime/helpers/regeneratorRuntime.js ***!
6505 \********************************************************************/
6506 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6507
6508 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6509 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6510 var regeneratorAsync = __webpack_require__(/*! ./regeneratorAsync.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js");
6511 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6512 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6513 var regeneratorKeys = __webpack_require__(/*! ./regeneratorKeys.js */ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js");
6514 var regeneratorValues = __webpack_require__(/*! ./regeneratorValues.js */ "../node_modules/@babel/runtime/helpers/regeneratorValues.js");
6515 function _regeneratorRuntime() {
6516 "use strict";
6517
6518 var r = regenerator(),
6519 e = r.m(_regeneratorRuntime),
6520 t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
6521 function n(r) {
6522 var e = "function" == typeof r && r.constructor;
6523 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
6524 }
6525 var o = {
6526 "throw": 1,
6527 "return": 2,
6528 "break": 3,
6529 "continue": 3
6530 };
6531 function a(r) {
6532 var e, t;
6533 return function (n) {
6534 e || (e = {
6535 stop: function stop() {
6536 return t(n.a, 2);
6537 },
6538 "catch": function _catch() {
6539 return n.v;
6540 },
6541 abrupt: function abrupt(r, e) {
6542 return t(n.a, o[r], e);
6543 },
6544 delegateYield: function delegateYield(r, o, a) {
6545 return e.resultName = o, t(n.d, regeneratorValues(r), a);
6546 },
6547 finish: function finish(r) {
6548 return t(n.f, r);
6549 }
6550 }, t = function t(r, _t, o) {
6551 n.p = e.prev, n.n = e.next;
6552 try {
6553 return r(_t, o);
6554 } finally {
6555 e.next = n.n;
6556 }
6557 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
6558 try {
6559 return r.call(this, e);
6560 } finally {
6561 n.p = e.prev, n.n = e.next;
6562 }
6563 };
6564 }
6565 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
6566 return {
6567 wrap: function wrap(e, t, n, o) {
6568 return r.w(a(e), t, n, o && o.reverse());
6569 },
6570 isGeneratorFunction: n,
6571 mark: r.m,
6572 awrap: function awrap(r, e) {
6573 return new OverloadYield(r, e);
6574 },
6575 AsyncIterator: regeneratorAsyncIterator,
6576 async: function async(r, e, t, o, u) {
6577 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
6578 },
6579 keys: regeneratorKeys,
6580 values: regeneratorValues
6581 };
6582 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6583 }
6584 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
6585
6586 /***/ }),
6587
6588 /***/ "../node_modules/@babel/runtime/helpers/regeneratorValues.js":
6589 /*!*******************************************************************!*\
6590 !*** ../node_modules/@babel/runtime/helpers/regeneratorValues.js ***!
6591 \*******************************************************************/
6592 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6593
6594 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6595 function _regeneratorValues(e) {
6596 if (null != e) {
6597 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
6598 r = 0;
6599 if (t) return t.call(e);
6600 if ("function" == typeof e.next) return e;
6601 if (!isNaN(e.length)) return {
6602 next: function next() {
6603 return e && r >= e.length && (e = void 0), {
6604 value: e && e[r++],
6605 done: !e
6606 };
6607 }
6608 };
6609 }
6610 throw new TypeError(_typeof(e) + " is not iterable");
6611 }
6612 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
6613
6614 /***/ }),
6615
6616 /***/ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js":
6617 /*!****************************************************************!*\
6618 !*** ../node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
6619 \****************************************************************/
6620 /***/ ((module) => {
6621
6622 function _setPrototypeOf(t, e) {
6623 return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
6624 return t.__proto__ = e, t;
6625 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _setPrototypeOf(t, e);
6626 }
6627 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6628
6629 /***/ }),
6630
6631 /***/ "../node_modules/@babel/runtime/helpers/slicedToArray.js":
6632 /*!***************************************************************!*\
6633 !*** ../node_modules/@babel/runtime/helpers/slicedToArray.js ***!
6634 \***************************************************************/
6635 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6636
6637 var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js");
6638 var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit.js */ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js");
6639 var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
6640 var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ "../node_modules/@babel/runtime/helpers/nonIterableRest.js");
6641 function _slicedToArray(r, e) {
6642 return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();
6643 }
6644 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6645
6646 /***/ }),
6647
6648 /***/ "../node_modules/@babel/runtime/helpers/superPropBase.js":
6649 /*!***************************************************************!*\
6650 !*** ../node_modules/@babel/runtime/helpers/superPropBase.js ***!
6651 \***************************************************************/
6652 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6653
6654 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6655 function _superPropBase(t, o) {
6656 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = getPrototypeOf(t)););
6657 return t;
6658 }
6659 module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
6660
6661 /***/ }),
6662
6663 /***/ "../node_modules/@babel/runtime/helpers/toPrimitive.js":
6664 /*!*************************************************************!*\
6665 !*** ../node_modules/@babel/runtime/helpers/toPrimitive.js ***!
6666 \*************************************************************/
6667 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6668
6669 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6670 function toPrimitive(t, r) {
6671 if ("object" != _typeof(t) || !t) return t;
6672 var e = t[Symbol.toPrimitive];
6673 if (void 0 !== e) {
6674 var i = e.call(t, r || "default");
6675 if ("object" != _typeof(i)) return i;
6676 throw new TypeError("@@toPrimitive must return a primitive value.");
6677 }
6678 return ("string" === r ? String : Number)(t);
6679 }
6680 module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
6681
6682 /***/ }),
6683
6684 /***/ "../node_modules/@babel/runtime/helpers/toPropertyKey.js":
6685 /*!***************************************************************!*\
6686 !*** ../node_modules/@babel/runtime/helpers/toPropertyKey.js ***!
6687 \***************************************************************/
6688 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6689
6690 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6691 var toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/toPrimitive.js");
6692 function toPropertyKey(t) {
6693 var i = toPrimitive(t, "string");
6694 return "symbol" == _typeof(i) ? i : i + "";
6695 }
6696 module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
6697
6698 /***/ }),
6699
6700 /***/ "../node_modules/@babel/runtime/helpers/typeof.js":
6701 /*!********************************************************!*\
6702 !*** ../node_modules/@babel/runtime/helpers/typeof.js ***!
6703 \********************************************************/
6704 /***/ ((module) => {
6705
6706 function _typeof(o) {
6707 "@babel/helpers - typeof";
6708
6709 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6710 return typeof o;
6711 } : function (o) {
6712 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6713 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
6714 }
6715 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
6716
6717 /***/ }),
6718
6719 /***/ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
6720 /*!****************************************************************************!*\
6721 !*** ../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
6722 \****************************************************************************/
6723 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6724
6725 var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
6726 function _unsupportedIterableToArray(r, a) {
6727 if (r) {
6728 if ("string" == typeof r) return arrayLikeToArray(r, a);
6729 var t = {}.toString.call(r).slice(8, -1);
6730 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;
6731 }
6732 }
6733 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6734
6735 /***/ }),
6736
6737 /***/ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js":
6738 /*!*****************************************************************!*\
6739 !*** ../node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***!
6740 \*****************************************************************/
6741 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6742
6743 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6744 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6745 var isNativeFunction = __webpack_require__(/*! ./isNativeFunction.js */ "../node_modules/@babel/runtime/helpers/isNativeFunction.js");
6746 var construct = __webpack_require__(/*! ./construct.js */ "../node_modules/@babel/runtime/helpers/construct.js");
6747 function _wrapNativeSuper(t) {
6748 var r = "function" == typeof Map ? new Map() : void 0;
6749 return module.exports = _wrapNativeSuper = function _wrapNativeSuper(t) {
6750 if (null === t || !isNativeFunction(t)) return t;
6751 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
6752 if (void 0 !== r) {
6753 if (r.has(t)) return r.get(t);
6754 r.set(t, Wrapper);
6755 }
6756 function Wrapper() {
6757 return construct(t, arguments, getPrototypeOf(this).constructor);
6758 }
6759 return Wrapper.prototype = Object.create(t.prototype, {
6760 constructor: {
6761 value: Wrapper,
6762 enumerable: !1,
6763 writable: !0,
6764 configurable: !0
6765 }
6766 }), setPrototypeOf(Wrapper, t);
6767 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _wrapNativeSuper(t);
6768 }
6769 module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports;
6770
6771 /***/ }),
6772
6773 /***/ "../node_modules/@babel/runtime/regenerator/index.js":
6774 /*!***********************************************************!*\
6775 !*** ../node_modules/@babel/runtime/regenerator/index.js ***!
6776 \***********************************************************/
6777 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6778
6779 // TODO(Babel 8): Remove this file.
6780
6781 var runtime = __webpack_require__(/*! ../helpers/regeneratorRuntime */ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js")();
6782 module.exports = runtime;
6783
6784 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
6785 try {
6786 regeneratorRuntime = runtime;
6787 } catch (accidentalStrictMode) {
6788 if (typeof globalThis === "object") {
6789 globalThis.regeneratorRuntime = runtime;
6790 } else {
6791 Function("r", "regeneratorRuntime = r")(runtime);
6792 }
6793 }
6794
6795
6796 /***/ }),
6797
6798 /***/ "../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js":
6799 /*!******************************************************************!*\
6800 !*** ../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js ***!
6801 \******************************************************************/
6802 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
6803
6804 "use strict";
6805 __webpack_require__.r(__webpack_exports__);
6806 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6807 /* harmony export */ EnhancerArray: () => (/* binding */ EnhancerArray),
6808 /* harmony export */ MiddlewareArray: () => (/* binding */ MiddlewareArray),
6809 /* harmony export */ SHOULD_AUTOBATCH: () => (/* binding */ SHOULD_AUTOBATCH),
6810 /* harmony export */ TaskAbortError: () => (/* binding */ TaskAbortError),
6811 /* harmony export */ __DO_NOT_USE__ActionTypes: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.__DO_NOT_USE__ActionTypes),
6812 /* harmony export */ addListener: () => (/* binding */ addListener),
6813 /* harmony export */ applyMiddleware: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.applyMiddleware),
6814 /* harmony export */ autoBatchEnhancer: () => (/* binding */ autoBatchEnhancer),
6815 /* harmony export */ bindActionCreators: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.bindActionCreators),
6816 /* harmony export */ clearAllListeners: () => (/* binding */ clearAllListeners),
6817 /* harmony export */ combineReducers: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.combineReducers),
6818 /* harmony export */ compose: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.compose),
6819 /* harmony export */ configureStore: () => (/* binding */ configureStore),
6820 /* harmony export */ createAction: () => (/* binding */ createAction),
6821 /* harmony export */ createActionCreatorInvariantMiddleware: () => (/* binding */ createActionCreatorInvariantMiddleware),
6822 /* harmony export */ createAsyncThunk: () => (/* binding */ createAsyncThunk),
6823 /* harmony export */ createDraftSafeSelector: () => (/* binding */ createDraftSafeSelector),
6824 /* harmony export */ createEntityAdapter: () => (/* binding */ createEntityAdapter),
6825 /* harmony export */ createImmutableStateInvariantMiddleware: () => (/* binding */ createImmutableStateInvariantMiddleware),
6826 /* harmony export */ createListenerMiddleware: () => (/* binding */ createListenerMiddleware),
6827 /* harmony export */ createNextState: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__["default"]),
6828 /* harmony export */ createReducer: () => (/* binding */ createReducer),
6829 /* harmony export */ createSelector: () => (/* reexport safe */ reselect__WEBPACK_IMPORTED_MODULE_2__.createSelector),
6830 /* harmony export */ createSerializableStateInvariantMiddleware: () => (/* binding */ createSerializableStateInvariantMiddleware),
6831 /* harmony export */ createSlice: () => (/* binding */ createSlice),
6832 /* harmony export */ createStore: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.createStore),
6833 /* harmony export */ current: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.current),
6834 /* harmony export */ findNonSerializableValue: () => (/* binding */ findNonSerializableValue),
6835 /* harmony export */ freeze: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.freeze),
6836 /* harmony export */ getDefaultMiddleware: () => (/* binding */ getDefaultMiddleware),
6837 /* harmony export */ getType: () => (/* binding */ getType),
6838 /* harmony export */ isAction: () => (/* binding */ isAction),
6839 /* harmony export */ isActionCreator: () => (/* binding */ isActionCreator),
6840 /* harmony export */ isAllOf: () => (/* binding */ isAllOf),
6841 /* harmony export */ isAnyOf: () => (/* binding */ isAnyOf),
6842 /* harmony export */ isAsyncThunkAction: () => (/* binding */ isAsyncThunkAction),
6843 /* harmony export */ isDraft: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.isDraft),
6844 /* harmony export */ isFluxStandardAction: () => (/* binding */ isFSA),
6845 /* harmony export */ isFulfilled: () => (/* binding */ isFulfilled),
6846 /* harmony export */ isImmutableDefault: () => (/* binding */ isImmutableDefault),
6847 /* harmony export */ isPending: () => (/* binding */ isPending),
6848 /* harmony export */ isPlain: () => (/* binding */ isPlain),
6849 /* harmony export */ isPlainObject: () => (/* binding */ isPlainObject),
6850 /* harmony export */ isRejected: () => (/* binding */ isRejected),
6851 /* harmony export */ isRejectedWithValue: () => (/* binding */ isRejectedWithValue),
6852 /* harmony export */ legacy_createStore: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.legacy_createStore),
6853 /* harmony export */ miniSerializeError: () => (/* binding */ miniSerializeError),
6854 /* harmony export */ nanoid: () => (/* binding */ nanoid),
6855 /* harmony export */ original: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.original),
6856 /* harmony export */ prepareAutoBatched: () => (/* binding */ prepareAutoBatched),
6857 /* harmony export */ removeListener: () => (/* binding */ removeListener),
6858 /* harmony export */ unwrapResult: () => (/* binding */ unwrapResult)
6859 /* harmony export */ });
6860 /* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! immer */ "../node_modules/immer/dist/immer.esm.mjs");
6861 /* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! redux */ "../node_modules/redux/es/redux.js");
6862 /* harmony import */ var reselect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! reselect */ "../node_modules/reselect/es/index.js");
6863 /* harmony import */ var redux_thunk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! redux-thunk */ "../node_modules/redux-thunk/es/index.js");
6864 var __extends = (undefined && undefined.__extends) || (function () {
6865 var extendStatics = function (d, b) {
6866 extendStatics = Object.setPrototypeOf ||
6867 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6868 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6869 return extendStatics(d, b);
6870 };
6871 return function (d, b) {
6872 if (typeof b !== "function" && b !== null)
6873 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
6874 extendStatics(d, b);
6875 function __() { this.constructor = d; }
6876 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6877 };
6878 })();
6879 var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
6880 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
6881 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
6882 function verb(n) { return function (v) { return step([n, v]); }; }
6883 function step(op) {
6884 if (f) throw new TypeError("Generator is already executing.");
6885 while (_) try {
6886 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
6887 if (y = 0, t) op = [op[0] & 2, t.value];
6888 switch (op[0]) {
6889 case 0: case 1: t = op; break;
6890 case 4: _.label++; return { value: op[1], done: false };
6891 case 5: _.label++; y = op[1]; op = [0]; continue;
6892 case 7: op = _.ops.pop(); _.trys.pop(); continue;
6893 default:
6894 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
6895 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
6896 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
6897 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
6898 if (t[2]) _.ops.pop();
6899 _.trys.pop(); continue;
6900 }
6901 op = body.call(thisArg, _);
6902 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
6903 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6904 }
6905 };
6906 var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from) {
6907 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
6908 to[j] = from[i];
6909 return to;
6910 };
6911 var __defProp = Object.defineProperty;
6912 var __defProps = Object.defineProperties;
6913 var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6914 var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6915 var __hasOwnProp = Object.prototype.hasOwnProperty;
6916 var __propIsEnum = Object.prototype.propertyIsEnumerable;
6917 var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
6918 var __spreadValues = function (a, b) {
6919 for (var prop in b || (b = {}))
6920 if (__hasOwnProp.call(b, prop))
6921 __defNormalProp(a, prop, b[prop]);
6922 if (__getOwnPropSymbols)
6923 for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
6924 var prop = _c[_i];
6925 if (__propIsEnum.call(b, prop))
6926 __defNormalProp(a, prop, b[prop]);
6927 }
6928 return a;
6929 };
6930 var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
6931 var __async = function (__this, __arguments, generator) {
6932 return new Promise(function (resolve, reject) {
6933 var fulfilled = function (value) {
6934 try {
6935 step(generator.next(value));
6936 }
6937 catch (e) {
6938 reject(e);
6939 }
6940 };
6941 var rejected = function (value) {
6942 try {
6943 step(generator.throw(value));
6944 }
6945 catch (e) {
6946 reject(e);
6947 }
6948 };
6949 var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };
6950 step((generator = generator.apply(__this, __arguments)).next());
6951 });
6952 };
6953 // src/index.ts
6954
6955
6956
6957
6958 // src/createDraftSafeSelector.ts
6959
6960
6961 var createDraftSafeSelector = function () {
6962 var args = [];
6963 for (var _i = 0; _i < arguments.length; _i++) {
6964 args[_i] = arguments[_i];
6965 }
6966 var selector = reselect__WEBPACK_IMPORTED_MODULE_2__.createSelector.apply(void 0, args);
6967 var wrappedSelector = function (value) {
6968 var rest = [];
6969 for (var _i = 1; _i < arguments.length; _i++) {
6970 rest[_i - 1] = arguments[_i];
6971 }
6972 return selector.apply(void 0, __spreadArray([(0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(value) ? (0,immer__WEBPACK_IMPORTED_MODULE_0__.current)(value) : value], rest));
6973 };
6974 return wrappedSelector;
6975 };
6976 // src/configureStore.ts
6977
6978 // src/devtoolsExtension.ts
6979
6980 var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {
6981 if (arguments.length === 0)
6982 return void 0;
6983 if (typeof arguments[0] === "object")
6984 return redux__WEBPACK_IMPORTED_MODULE_1__.compose;
6985 return redux__WEBPACK_IMPORTED_MODULE_1__.compose.apply(null, arguments);
6986 };
6987 var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {
6988 return function (noop2) {
6989 return noop2;
6990 };
6991 };
6992 // src/isPlainObject.ts
6993 function isPlainObject(value) {
6994 if (typeof value !== "object" || value === null)
6995 return false;
6996 var proto = Object.getPrototypeOf(value);
6997 if (proto === null)
6998 return true;
6999 var baseProto = proto;
7000 while (Object.getPrototypeOf(baseProto) !== null) {
7001 baseProto = Object.getPrototypeOf(baseProto);
7002 }
7003 return proto === baseProto;
7004 }
7005 // src/getDefaultMiddleware.ts
7006
7007 // src/tsHelpers.ts
7008 var hasMatchFunction = function (v) {
7009 return v && typeof v.match === "function";
7010 };
7011 // src/createAction.ts
7012 function createAction(type, prepareAction) {
7013 function actionCreator() {
7014 var args = [];
7015 for (var _i = 0; _i < arguments.length; _i++) {
7016 args[_i] = arguments[_i];
7017 }
7018 if (prepareAction) {
7019 var prepared = prepareAction.apply(void 0, args);
7020 if (!prepared) {
7021 throw new Error("prepareAction did not return an object");
7022 }
7023 return __spreadValues(__spreadValues({
7024 type: type,
7025 payload: prepared.payload
7026 }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
7027 }
7028 return { type: type, payload: args[0] };
7029 }
7030 actionCreator.toString = function () { return "" + type; };
7031 actionCreator.type = type;
7032 actionCreator.match = function (action) { return action.type === type; };
7033 return actionCreator;
7034 }
7035 function isAction(action) {
7036 return isPlainObject(action) && "type" in action;
7037 }
7038 function isActionCreator(action) {
7039 return typeof action === "function" && "type" in action && hasMatchFunction(action);
7040 }
7041 function isFSA(action) {
7042 return isAction(action) && typeof action.type === "string" && Object.keys(action).every(isValidKey);
7043 }
7044 function isValidKey(key) {
7045 return ["type", "payload", "error", "meta"].indexOf(key) > -1;
7046 }
7047 function getType(actionCreator) {
7048 return "" + actionCreator;
7049 }
7050 // src/actionCreatorInvariantMiddleware.ts
7051 function getMessage(type) {
7052 var splitType = type ? ("" + type).split("/") : [];
7053 var actionName = splitType[splitType.length - 1] || "actionCreator";
7054 return "Detected an action creator with type \"" + (type || "unknown") + "\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. `dispatch(" + actionName + "())` instead of `dispatch(" + actionName + ")`. This is necessary even if the action has no payload.";
7055 }
7056 function createActionCreatorInvariantMiddleware(options) {
7057 if (options === void 0) { options = {}; }
7058 if (false) // removed by dead control flow
7059 {}
7060 var _c = options.isActionCreator, isActionCreator2 = _c === void 0 ? isActionCreator : _c;
7061 return function () { return function (next) { return function (action) {
7062 if (isActionCreator2(action)) {
7063 console.warn(getMessage(action.type));
7064 }
7065 return next(action);
7066 }; }; };
7067 }
7068 // src/utils.ts
7069
7070 function getTimeMeasureUtils(maxDelay, fnName) {
7071 var elapsed = 0;
7072 return {
7073 measureTime: function (fn) {
7074 var started = Date.now();
7075 try {
7076 return fn();
7077 }
7078 finally {
7079 var finished = Date.now();
7080 elapsed += finished - started;
7081 }
7082 },
7083 warnIfExceeded: function () {
7084 if (elapsed > maxDelay) {
7085 console.warn(fnName + " took " + elapsed + "ms, which is more than the warning threshold of " + maxDelay + "ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.");
7086 }
7087 }
7088 };
7089 }
7090 var MiddlewareArray = /** @class */ (function (_super) {
7091 __extends(MiddlewareArray, _super);
7092 function MiddlewareArray() {
7093 var args = [];
7094 for (var _i = 0; _i < arguments.length; _i++) {
7095 args[_i] = arguments[_i];
7096 }
7097 var _this = _super.apply(this, args) || this;
7098 Object.setPrototypeOf(_this, MiddlewareArray.prototype);
7099 return _this;
7100 }
7101 Object.defineProperty(MiddlewareArray, Symbol.species, {
7102 get: function () {
7103 return MiddlewareArray;
7104 },
7105 enumerable: false,
7106 configurable: true
7107 });
7108 MiddlewareArray.prototype.concat = function () {
7109 var arr = [];
7110 for (var _i = 0; _i < arguments.length; _i++) {
7111 arr[_i] = arguments[_i];
7112 }
7113 return _super.prototype.concat.apply(this, arr);
7114 };
7115 MiddlewareArray.prototype.prepend = function () {
7116 var arr = [];
7117 for (var _i = 0; _i < arguments.length; _i++) {
7118 arr[_i] = arguments[_i];
7119 }
7120 if (arr.length === 1 && Array.isArray(arr[0])) {
7121 return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))();
7122 }
7123 return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))();
7124 };
7125 return MiddlewareArray;
7126 }(Array));
7127 var EnhancerArray = /** @class */ (function (_super) {
7128 __extends(EnhancerArray, _super);
7129 function EnhancerArray() {
7130 var args = [];
7131 for (var _i = 0; _i < arguments.length; _i++) {
7132 args[_i] = arguments[_i];
7133 }
7134 var _this = _super.apply(this, args) || this;
7135 Object.setPrototypeOf(_this, EnhancerArray.prototype);
7136 return _this;
7137 }
7138 Object.defineProperty(EnhancerArray, Symbol.species, {
7139 get: function () {
7140 return EnhancerArray;
7141 },
7142 enumerable: false,
7143 configurable: true
7144 });
7145 EnhancerArray.prototype.concat = function () {
7146 var arr = [];
7147 for (var _i = 0; _i < arguments.length; _i++) {
7148 arr[_i] = arguments[_i];
7149 }
7150 return _super.prototype.concat.apply(this, arr);
7151 };
7152 EnhancerArray.prototype.prepend = function () {
7153 var arr = [];
7154 for (var _i = 0; _i < arguments.length; _i++) {
7155 arr[_i] = arguments[_i];
7156 }
7157 if (arr.length === 1 && Array.isArray(arr[0])) {
7158 return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr[0].concat(this))))();
7159 }
7160 return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr.concat(this))))();
7161 };
7162 return EnhancerArray;
7163 }(Array));
7164 function freezeDraftable(val) {
7165 return (0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraftable)(val) ? (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(val, function () {
7166 }) : val;
7167 }
7168 // src/immutableStateInvariantMiddleware.ts
7169 var isProduction = "development" === "production";
7170 var prefix = "Invariant failed";
7171 function invariant(condition, message) {
7172 if (condition) {
7173 return;
7174 }
7175 if (isProduction) {
7176 throw new Error(prefix);
7177 }
7178 throw new Error(prefix + ": " + (message || ""));
7179 }
7180 function stringify(obj, serializer, indent, decycler) {
7181 return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
7182 }
7183 function getSerialize(serializer, decycler) {
7184 var stack = [], keys = [];
7185 if (!decycler)
7186 decycler = function (_, value) {
7187 if (stack[0] === value)
7188 return "[Circular ~]";
7189 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
7190 };
7191 return function (key, value) {
7192 if (stack.length > 0) {
7193 var thisPos = stack.indexOf(this);
7194 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
7195 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
7196 if (~stack.indexOf(value))
7197 value = decycler.call(this, key, value);
7198 }
7199 else
7200 stack.push(value);
7201 return serializer == null ? value : serializer.call(this, key, value);
7202 };
7203 }
7204 function isImmutableDefault(value) {
7205 return typeof value !== "object" || value == null || Object.isFrozen(value);
7206 }
7207 function trackForMutations(isImmutable, ignorePaths, obj) {
7208 var trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
7209 return {
7210 detectMutations: function () {
7211 return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
7212 }
7213 };
7214 }
7215 function trackProperties(isImmutable, ignorePaths, obj, path, checkedObjects) {
7216 if (ignorePaths === void 0) { ignorePaths = []; }
7217 if (path === void 0) { path = ""; }
7218 if (checkedObjects === void 0) { checkedObjects = new Set(); }
7219 var tracked = { value: obj };
7220 if (!isImmutable(obj) && !checkedObjects.has(obj)) {
7221 checkedObjects.add(obj);
7222 tracked.children = {};
7223 for (var key in obj) {
7224 var childPath = path ? path + "." + key : key;
7225 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
7226 continue;
7227 }
7228 tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
7229 }
7230 }
7231 return tracked;
7232 }
7233 function detectMutations(isImmutable, ignoredPaths, trackedProperty, obj, sameParentRef, path) {
7234 if (ignoredPaths === void 0) { ignoredPaths = []; }
7235 if (sameParentRef === void 0) { sameParentRef = false; }
7236 if (path === void 0) { path = ""; }
7237 var prevObj = trackedProperty ? trackedProperty.value : void 0;
7238 var sameRef = prevObj === obj;
7239 if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
7240 return { wasMutated: true, path: path };
7241 }
7242 if (isImmutable(prevObj) || isImmutable(obj)) {
7243 return { wasMutated: false };
7244 }
7245 var keysToDetect = {};
7246 for (var key in trackedProperty.children) {
7247 keysToDetect[key] = true;
7248 }
7249 for (var key in obj) {
7250 keysToDetect[key] = true;
7251 }
7252 var hasIgnoredPaths = ignoredPaths.length > 0;
7253 var _loop_1 = function (key) {
7254 var nestedPath = path ? path + "." + key : key;
7255 if (hasIgnoredPaths) {
7256 var hasMatches = ignoredPaths.some(function (ignored) {
7257 if (ignored instanceof RegExp) {
7258 return ignored.test(nestedPath);
7259 }
7260 return nestedPath === ignored;
7261 });
7262 if (hasMatches) {
7263 return "continue";
7264 }
7265 }
7266 var result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
7267 if (result.wasMutated) {
7268 return { value: result };
7269 }
7270 };
7271 for (var key in keysToDetect) {
7272 var state_1 = _loop_1(key);
7273 if (typeof state_1 === "object")
7274 return state_1.value;
7275 }
7276 return { wasMutated: false };
7277 }
7278 function createImmutableStateInvariantMiddleware(options) {
7279 if (options === void 0) { options = {}; }
7280 if (false) // removed by dead control flow
7281 {}
7282 var _c = options.isImmutable, isImmutable = _c === void 0 ? isImmutableDefault : _c, ignoredPaths = options.ignoredPaths, _d = options.warnAfter, warnAfter = _d === void 0 ? 32 : _d, ignore = options.ignore;
7283 ignoredPaths = ignoredPaths || ignore;
7284 var track = trackForMutations.bind(null, isImmutable, ignoredPaths);
7285 return function (_c) {
7286 var getState = _c.getState;
7287 var state = getState();
7288 var tracker = track(state);
7289 var result;
7290 return function (next) { return function (action) {
7291 var measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
7292 measureUtils.measureTime(function () {
7293 state = getState();
7294 result = tracker.detectMutations();
7295 tracker = track(state);
7296 invariant(!result.wasMutated, "A state mutation was detected between dispatches, in the path '" + (result.path || "") + "'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)");
7297 });
7298 var dispatchedAction = next(action);
7299 measureUtils.measureTime(function () {
7300 state = getState();
7301 result = tracker.detectMutations();
7302 tracker = track(state);
7303 result.wasMutated && invariant(!result.wasMutated, "A state mutation was detected inside a dispatch, in the path: " + (result.path || "") + ". Take a look at the reducer(s) handling the action " + stringify(action) + ". (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)");
7304 });
7305 measureUtils.warnIfExceeded();
7306 return dispatchedAction;
7307 }; };
7308 };
7309 }
7310 // src/serializableStateInvariantMiddleware.ts
7311 function isPlain(val) {
7312 var type = typeof val;
7313 return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
7314 }
7315 function findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths, cache) {
7316 if (path === void 0) { path = ""; }
7317 if (isSerializable === void 0) { isSerializable = isPlain; }
7318 if (ignoredPaths === void 0) { ignoredPaths = []; }
7319 var foundNestedSerializable;
7320 if (!isSerializable(value)) {
7321 return {
7322 keyPath: path || "<root>",
7323 value: value
7324 };
7325 }
7326 if (typeof value !== "object" || value === null) {
7327 return false;
7328 }
7329 if (cache == null ? void 0 : cache.has(value))
7330 return false;
7331 var entries = getEntries != null ? getEntries(value) : Object.entries(value);
7332 var hasIgnoredPaths = ignoredPaths.length > 0;
7333 var _loop_2 = function (key, nestedValue) {
7334 var nestedPath = path ? path + "." + key : key;
7335 if (hasIgnoredPaths) {
7336 var hasMatches = ignoredPaths.some(function (ignored) {
7337 if (ignored instanceof RegExp) {
7338 return ignored.test(nestedPath);
7339 }
7340 return nestedPath === ignored;
7341 });
7342 if (hasMatches) {
7343 return "continue";
7344 }
7345 }
7346 if (!isSerializable(nestedValue)) {
7347 return { value: {
7348 keyPath: nestedPath,
7349 value: nestedValue
7350 } };
7351 }
7352 if (typeof nestedValue === "object") {
7353 foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
7354 if (foundNestedSerializable) {
7355 return { value: foundNestedSerializable };
7356 }
7357 }
7358 };
7359 for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7360 var _c = entries_1[_i], key = _c[0], nestedValue = _c[1];
7361 var state_2 = _loop_2(key, nestedValue);
7362 if (typeof state_2 === "object")
7363 return state_2.value;
7364 }
7365 if (cache && isNestedFrozen(value))
7366 cache.add(value);
7367 return false;
7368 }
7369 function isNestedFrozen(value) {
7370 if (!Object.isFrozen(value))
7371 return false;
7372 for (var _i = 0, _c = Object.values(value); _i < _c.length; _i++) {
7373 var nestedValue = _c[_i];
7374 if (typeof nestedValue !== "object" || nestedValue === null)
7375 continue;
7376 if (!isNestedFrozen(nestedValue))
7377 return false;
7378 }
7379 return true;
7380 }
7381 function createSerializableStateInvariantMiddleware(options) {
7382 if (options === void 0) { options = {}; }
7383 if (false) // removed by dead control flow
7384 {}
7385 var _c = options.isSerializable, isSerializable = _c === void 0 ? isPlain : _c, getEntries = options.getEntries, _d = options.ignoredActions, ignoredActions = _d === void 0 ? [] : _d, _e = options.ignoredActionPaths, ignoredActionPaths = _e === void 0 ? ["meta.arg", "meta.baseQueryMeta"] : _e, _f = options.ignoredPaths, ignoredPaths = _f === void 0 ? [] : _f, _g = options.warnAfter, warnAfter = _g === void 0 ? 32 : _g, _h = options.ignoreState, ignoreState = _h === void 0 ? false : _h, _j = options.ignoreActions, ignoreActions = _j === void 0 ? false : _j, _k = options.disableCache, disableCache = _k === void 0 ? false : _k;
7386 var cache = !disableCache && WeakSet ? new WeakSet() : void 0;
7387 return function (storeAPI) { return function (next) { return function (action) {
7388 var result = next(action);
7389 var measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
7390 if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
7391 measureUtils.measureTime(function () {
7392 var foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
7393 if (foundActionNonSerializableValue) {
7394 var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value;
7395 console.error("A non-serializable value was detected in an action, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
7396 }
7397 });
7398 }
7399 if (!ignoreState) {
7400 measureUtils.measureTime(function () {
7401 var state = storeAPI.getState();
7402 var foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
7403 if (foundStateNonSerializableValue) {
7404 var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value;
7405 console.error("A non-serializable value was detected in the state, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the reducer(s) handling this action type: " + action.type + ".\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)");
7406 }
7407 });
7408 measureUtils.warnIfExceeded();
7409 }
7410 return result;
7411 }; }; };
7412 }
7413 // src/getDefaultMiddleware.ts
7414 function isBoolean(x) {
7415 return typeof x === "boolean";
7416 }
7417 function curryGetDefaultMiddleware() {
7418 return function curriedGetDefaultMiddleware(options) {
7419 return getDefaultMiddleware(options);
7420 };
7421 }
7422 function getDefaultMiddleware(options) {
7423 if (options === void 0) { options = {}; }
7424 var _c = options.thunk, thunk = _c === void 0 ? true : _c, _d = options.immutableCheck, immutableCheck = _d === void 0 ? true : _d, _e = options.serializableCheck, serializableCheck = _e === void 0 ? true : _e, _f = options.actionCreatorCheck, actionCreatorCheck = _f === void 0 ? true : _f;
7425 var middlewareArray = new MiddlewareArray();
7426 if (thunk) {
7427 if (isBoolean(thunk)) {
7428 middlewareArray.push(redux_thunk__WEBPACK_IMPORTED_MODULE_3__["default"]);
7429 }
7430 else {
7431 middlewareArray.push(redux_thunk__WEBPACK_IMPORTED_MODULE_3__["default"].withExtraArgument(thunk.extraArgument));
7432 }
7433 }
7434 if (true) {
7435 if (immutableCheck) {
7436 var immutableOptions = {};
7437 if (!isBoolean(immutableCheck)) {
7438 immutableOptions = immutableCheck;
7439 }
7440 middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
7441 }
7442 if (serializableCheck) {
7443 var serializableOptions = {};
7444 if (!isBoolean(serializableCheck)) {
7445 serializableOptions = serializableCheck;
7446 }
7447 middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
7448 }
7449 if (actionCreatorCheck) {
7450 var actionCreatorOptions = {};
7451 if (!isBoolean(actionCreatorCheck)) {
7452 actionCreatorOptions = actionCreatorCheck;
7453 }
7454 middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
7455 }
7456 }
7457 return middlewareArray;
7458 }
7459 // src/configureStore.ts
7460 var IS_PRODUCTION = "development" === "production";
7461 function configureStore(options) {
7462 var curriedGetDefaultMiddleware = curryGetDefaultMiddleware();
7463 var _c = options || {}, _d = _c.reducer, reducer = _d === void 0 ? void 0 : _d, _e = _c.middleware, middleware = _e === void 0 ? curriedGetDefaultMiddleware() : _e, _f = _c.devTools, devTools = _f === void 0 ? true : _f, _g = _c.preloadedState, preloadedState = _g === void 0 ? void 0 : _g, _h = _c.enhancers, enhancers = _h === void 0 ? void 0 : _h;
7464 var rootReducer;
7465 if (typeof reducer === "function") {
7466 rootReducer = reducer;
7467 }
7468 else if (isPlainObject(reducer)) {
7469 rootReducer = (0,redux__WEBPACK_IMPORTED_MODULE_1__.combineReducers)(reducer);
7470 }
7471 else {
7472 throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');
7473 }
7474 var finalMiddleware = middleware;
7475 if (typeof finalMiddleware === "function") {
7476 finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);
7477 if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
7478 throw new Error("when using a middleware builder function, an array of middleware must be returned");
7479 }
7480 }
7481 if (!IS_PRODUCTION && finalMiddleware.some(function (item) { return typeof item !== "function"; })) {
7482 throw new Error("each middleware provided to configureStore must be a function");
7483 }
7484 var middlewareEnhancer = redux__WEBPACK_IMPORTED_MODULE_1__.applyMiddleware.apply(void 0, finalMiddleware);
7485 var finalCompose = redux__WEBPACK_IMPORTED_MODULE_1__.compose;
7486 if (devTools) {
7487 finalCompose = composeWithDevTools(__spreadValues({
7488 trace: !IS_PRODUCTION
7489 }, typeof devTools === "object" && devTools));
7490 }
7491 var defaultEnhancers = new EnhancerArray(middlewareEnhancer);
7492 var storeEnhancers = defaultEnhancers;
7493 if (Array.isArray(enhancers)) {
7494 storeEnhancers = __spreadArray([middlewareEnhancer], enhancers);
7495 }
7496 else if (typeof enhancers === "function") {
7497 storeEnhancers = enhancers(defaultEnhancers);
7498 }
7499 var composedEnhancer = finalCompose.apply(void 0, storeEnhancers);
7500 return (0,redux__WEBPACK_IMPORTED_MODULE_1__.createStore)(rootReducer, preloadedState, composedEnhancer);
7501 }
7502 // src/createReducer.ts
7503
7504 // src/mapBuilders.ts
7505 function executeReducerBuilderCallback(builderCallback) {
7506 var actionsMap = {};
7507 var actionMatchers = [];
7508 var defaultCaseReducer;
7509 var builder = {
7510 addCase: function (typeOrActionCreator, reducer) {
7511 if (true) {
7512 if (actionMatchers.length > 0) {
7513 throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");
7514 }
7515 if (defaultCaseReducer) {
7516 throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");
7517 }
7518 }
7519 var type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
7520 if (!type) {
7521 throw new Error("`builder.addCase` cannot be called with an empty action type");
7522 }
7523 if (type in actionsMap) {
7524 throw new Error("`builder.addCase` cannot be called with two reducers for the same action type");
7525 }
7526 actionsMap[type] = reducer;
7527 return builder;
7528 },
7529 addMatcher: function (matcher, reducer) {
7530 if (true) {
7531 if (defaultCaseReducer) {
7532 throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
7533 }
7534 }
7535 actionMatchers.push({ matcher: matcher, reducer: reducer });
7536 return builder;
7537 },
7538 addDefaultCase: function (reducer) {
7539 if (true) {
7540 if (defaultCaseReducer) {
7541 throw new Error("`builder.addDefaultCase` can only be called once");
7542 }
7543 }
7544 defaultCaseReducer = reducer;
7545 return builder;
7546 }
7547 };
7548 builderCallback(builder);
7549 return [actionsMap, actionMatchers, defaultCaseReducer];
7550 }
7551 // src/createReducer.ts
7552 function isStateFunction(x) {
7553 return typeof x === "function";
7554 }
7555 var hasWarnedAboutObjectNotation = false;
7556 function createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) {
7557 if (actionMatchers === void 0) { actionMatchers = []; }
7558 if (true) {
7559 if (typeof mapOrBuilderCallback === "object") {
7560 if (!hasWarnedAboutObjectNotation) {
7561 hasWarnedAboutObjectNotation = true;
7562 console.warn("The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
7563 }
7564 }
7565 }
7566 var _c = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2];
7567 var getInitialState;
7568 if (isStateFunction(initialState)) {
7569 getInitialState = function () { return freezeDraftable(initialState()); };
7570 }
7571 else {
7572 var frozenInitialState_1 = freezeDraftable(initialState);
7573 getInitialState = function () { return frozenInitialState_1; };
7574 }
7575 function reducer(state, action) {
7576 if (state === void 0) { state = getInitialState(); }
7577 var caseReducers = __spreadArray([
7578 actionsMap[action.type]
7579 ], finalActionMatchers.filter(function (_c) {
7580 var matcher = _c.matcher;
7581 return matcher(action);
7582 }).map(function (_c) {
7583 var reducer2 = _c.reducer;
7584 return reducer2;
7585 }));
7586 if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) {
7587 caseReducers = [finalDefaultCaseReducer];
7588 }
7589 return caseReducers.reduce(function (previousState, caseReducer) {
7590 if (caseReducer) {
7591 if ((0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(previousState)) {
7592 var draft = previousState;
7593 var result = caseReducer(draft, action);
7594 if (result === void 0) {
7595 return previousState;
7596 }
7597 return result;
7598 }
7599 else if (!(0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraftable)(previousState)) {
7600 var result = caseReducer(previousState, action);
7601 if (result === void 0) {
7602 if (previousState === null) {
7603 return previousState;
7604 }
7605 throw Error("A case reducer on a non-draftable value must not return undefined");
7606 }
7607 return result;
7608 }
7609 else {
7610 return (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(previousState, function (draft) {
7611 return caseReducer(draft, action);
7612 });
7613 }
7614 }
7615 return previousState;
7616 }, state);
7617 }
7618 reducer.getInitialState = getInitialState;
7619 return reducer;
7620 }
7621 // src/createSlice.ts
7622 var hasWarnedAboutObjectNotation2 = false;
7623 function getType2(slice, actionKey) {
7624 return slice + "/" + actionKey;
7625 }
7626 function createSlice(options) {
7627 var name = options.name;
7628 if (!name) {
7629 throw new Error("`name` is a required option for createSlice");
7630 }
7631 if (typeof process !== "undefined" && "development" === "development") {
7632 if (options.initialState === void 0) {
7633 console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
7634 }
7635 }
7636 var initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState);
7637 var reducers = options.reducers || {};
7638 var reducerNames = Object.keys(reducers);
7639 var sliceCaseReducersByName = {};
7640 var sliceCaseReducersByType = {};
7641 var actionCreators = {};
7642 reducerNames.forEach(function (reducerName) {
7643 var maybeReducerWithPrepare = reducers[reducerName];
7644 var type = getType2(name, reducerName);
7645 var caseReducer;
7646 var prepareCallback;
7647 if ("reducer" in maybeReducerWithPrepare) {
7648 caseReducer = maybeReducerWithPrepare.reducer;
7649 prepareCallback = maybeReducerWithPrepare.prepare;
7650 }
7651 else {
7652 caseReducer = maybeReducerWithPrepare;
7653 }
7654 sliceCaseReducersByName[reducerName] = caseReducer;
7655 sliceCaseReducersByType[type] = caseReducer;
7656 actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);
7657 });
7658 function buildReducer() {
7659 if (true) {
7660 if (typeof options.extraReducers === "object") {
7661 if (!hasWarnedAboutObjectNotation2) {
7662 hasWarnedAboutObjectNotation2 = true;
7663 console.warn("The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
7664 }
7665 }
7666 }
7667 var _c = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _d = _c[0], extraReducers = _d === void 0 ? {} : _d, _e = _c[1], actionMatchers = _e === void 0 ? [] : _e, _f = _c[2], defaultCaseReducer = _f === void 0 ? void 0 : _f;
7668 var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);
7669 return createReducer(initialState, function (builder) {
7670 for (var key in finalCaseReducers) {
7671 builder.addCase(key, finalCaseReducers[key]);
7672 }
7673 for (var _i = 0, actionMatchers_1 = actionMatchers; _i < actionMatchers_1.length; _i++) {
7674 var m = actionMatchers_1[_i];
7675 builder.addMatcher(m.matcher, m.reducer);
7676 }
7677 if (defaultCaseReducer) {
7678 builder.addDefaultCase(defaultCaseReducer);
7679 }
7680 });
7681 }
7682 var _reducer;
7683 return {
7684 name: name,
7685 reducer: function (state, action) {
7686 if (!_reducer)
7687 _reducer = buildReducer();
7688 return _reducer(state, action);
7689 },
7690 actions: actionCreators,
7691 caseReducers: sliceCaseReducersByName,
7692 getInitialState: function () {
7693 if (!_reducer)
7694 _reducer = buildReducer();
7695 return _reducer.getInitialState();
7696 }
7697 };
7698 }
7699 // src/entities/entity_state.ts
7700 function getInitialEntityState() {
7701 return {
7702 ids: [],
7703 entities: {}
7704 };
7705 }
7706 function createInitialStateFactory() {
7707 function getInitialState(additionalState) {
7708 if (additionalState === void 0) { additionalState = {}; }
7709 return Object.assign(getInitialEntityState(), additionalState);
7710 }
7711 return { getInitialState: getInitialState };
7712 }
7713 // src/entities/state_selectors.ts
7714 function createSelectorsFactory() {
7715 function getSelectors(selectState) {
7716 var selectIds = function (state) { return state.ids; };
7717 var selectEntities = function (state) { return state.entities; };
7718 var selectAll = createDraftSafeSelector(selectIds, selectEntities, function (ids, entities) { return ids.map(function (id) { return entities[id]; }); });
7719 var selectId = function (_, id) { return id; };
7720 var selectById = function (entities, id) { return entities[id]; };
7721 var selectTotal = createDraftSafeSelector(selectIds, function (ids) { return ids.length; });
7722 if (!selectState) {
7723 return {
7724 selectIds: selectIds,
7725 selectEntities: selectEntities,
7726 selectAll: selectAll,
7727 selectTotal: selectTotal,
7728 selectById: createDraftSafeSelector(selectEntities, selectId, selectById)
7729 };
7730 }
7731 var selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);
7732 return {
7733 selectIds: createDraftSafeSelector(selectState, selectIds),
7734 selectEntities: selectGlobalizedEntities,
7735 selectAll: createDraftSafeSelector(selectState, selectAll),
7736 selectTotal: createDraftSafeSelector(selectState, selectTotal),
7737 selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)
7738 };
7739 }
7740 return { getSelectors: getSelectors };
7741 }
7742 // src/entities/state_adapter.ts
7743
7744 function createSingleArgumentStateOperator(mutator) {
7745 var operator = createStateOperator(function (_, state) { return mutator(state); });
7746 return function operation(state) {
7747 return operator(state, void 0);
7748 };
7749 }
7750 function createStateOperator(mutator) {
7751 return function operation(state, arg) {
7752 function isPayloadActionArgument(arg2) {
7753 return isFSA(arg2);
7754 }
7755 var runMutator = function (draft) {
7756 if (isPayloadActionArgument(arg)) {
7757 mutator(arg.payload, draft);
7758 }
7759 else {
7760 mutator(arg, draft);
7761 }
7762 };
7763 if ((0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(state)) {
7764 runMutator(state);
7765 return state;
7766 }
7767 else {
7768 return (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(state, runMutator);
7769 }
7770 };
7771 }
7772 // src/entities/utils.ts
7773 function selectIdValue(entity, selectId) {
7774 var key = selectId(entity);
7775 if ( true && key === void 0) {
7776 console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
7777 }
7778 return key;
7779 }
7780 function ensureEntitiesArray(entities) {
7781 if (!Array.isArray(entities)) {
7782 entities = Object.values(entities);
7783 }
7784 return entities;
7785 }
7786 function splitAddedUpdatedEntities(newEntities, selectId, state) {
7787 newEntities = ensureEntitiesArray(newEntities);
7788 var added = [];
7789 var updated = [];
7790 for (var _i = 0, newEntities_1 = newEntities; _i < newEntities_1.length; _i++) {
7791 var entity = newEntities_1[_i];
7792 var id = selectIdValue(entity, selectId);
7793 if (id in state.entities) {
7794 updated.push({ id: id, changes: entity });
7795 }
7796 else {
7797 added.push(entity);
7798 }
7799 }
7800 return [added, updated];
7801 }
7802 // src/entities/unsorted_state_adapter.ts
7803 function createUnsortedStateAdapter(selectId) {
7804 function addOneMutably(entity, state) {
7805 var key = selectIdValue(entity, selectId);
7806 if (key in state.entities) {
7807 return;
7808 }
7809 state.ids.push(key);
7810 state.entities[key] = entity;
7811 }
7812 function addManyMutably(newEntities, state) {
7813 newEntities = ensureEntitiesArray(newEntities);
7814 for (var _i = 0, newEntities_2 = newEntities; _i < newEntities_2.length; _i++) {
7815 var entity = newEntities_2[_i];
7816 addOneMutably(entity, state);
7817 }
7818 }
7819 function setOneMutably(entity, state) {
7820 var key = selectIdValue(entity, selectId);
7821 if (!(key in state.entities)) {
7822 state.ids.push(key);
7823 }
7824 state.entities[key] = entity;
7825 }
7826 function setManyMutably(newEntities, state) {
7827 newEntities = ensureEntitiesArray(newEntities);
7828 for (var _i = 0, newEntities_3 = newEntities; _i < newEntities_3.length; _i++) {
7829 var entity = newEntities_3[_i];
7830 setOneMutably(entity, state);
7831 }
7832 }
7833 function setAllMutably(newEntities, state) {
7834 newEntities = ensureEntitiesArray(newEntities);
7835 state.ids = [];
7836 state.entities = {};
7837 addManyMutably(newEntities, state);
7838 }
7839 function removeOneMutably(key, state) {
7840 return removeManyMutably([key], state);
7841 }
7842 function removeManyMutably(keys, state) {
7843 var didMutate = false;
7844 keys.forEach(function (key) {
7845 if (key in state.entities) {
7846 delete state.entities[key];
7847 didMutate = true;
7848 }
7849 });
7850 if (didMutate) {
7851 state.ids = state.ids.filter(function (id) { return id in state.entities; });
7852 }
7853 }
7854 function removeAllMutably(state) {
7855 Object.assign(state, {
7856 ids: [],
7857 entities: {}
7858 });
7859 }
7860 function takeNewKey(keys, update, state) {
7861 var original2 = state.entities[update.id];
7862 var updated = Object.assign({}, original2, update.changes);
7863 var newKey = selectIdValue(updated, selectId);
7864 var hasNewKey = newKey !== update.id;
7865 if (hasNewKey) {
7866 keys[update.id] = newKey;
7867 delete state.entities[update.id];
7868 }
7869 state.entities[newKey] = updated;
7870 return hasNewKey;
7871 }
7872 function updateOneMutably(update, state) {
7873 return updateManyMutably([update], state);
7874 }
7875 function updateManyMutably(updates, state) {
7876 var newKeys = {};
7877 var updatesPerEntity = {};
7878 updates.forEach(function (update) {
7879 if (update.id in state.entities) {
7880 updatesPerEntity[update.id] = {
7881 id: update.id,
7882 changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)
7883 };
7884 }
7885 });
7886 updates = Object.values(updatesPerEntity);
7887 var didMutateEntities = updates.length > 0;
7888 if (didMutateEntities) {
7889 var didMutateIds = updates.filter(function (update) { return takeNewKey(newKeys, update, state); }).length > 0;
7890 if (didMutateIds) {
7891 state.ids = Object.keys(state.entities);
7892 }
7893 }
7894 }
7895 function upsertOneMutably(entity, state) {
7896 return upsertManyMutably([entity], state);
7897 }
7898 function upsertManyMutably(newEntities, state) {
7899 var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];
7900 updateManyMutably(updated, state);
7901 addManyMutably(added, state);
7902 }
7903 return {
7904 removeAll: createSingleArgumentStateOperator(removeAllMutably),
7905 addOne: createStateOperator(addOneMutably),
7906 addMany: createStateOperator(addManyMutably),
7907 setOne: createStateOperator(setOneMutably),
7908 setMany: createStateOperator(setManyMutably),
7909 setAll: createStateOperator(setAllMutably),
7910 updateOne: createStateOperator(updateOneMutably),
7911 updateMany: createStateOperator(updateManyMutably),
7912 upsertOne: createStateOperator(upsertOneMutably),
7913 upsertMany: createStateOperator(upsertManyMutably),
7914 removeOne: createStateOperator(removeOneMutably),
7915 removeMany: createStateOperator(removeManyMutably)
7916 };
7917 }
7918 // src/entities/sorted_state_adapter.ts
7919 function createSortedStateAdapter(selectId, sort) {
7920 var _c = createUnsortedStateAdapter(selectId), removeOne = _c.removeOne, removeMany = _c.removeMany, removeAll = _c.removeAll;
7921 function addOneMutably(entity, state) {
7922 return addManyMutably([entity], state);
7923 }
7924 function addManyMutably(newEntities, state) {
7925 newEntities = ensureEntitiesArray(newEntities);
7926 var models = newEntities.filter(function (model) { return !(selectIdValue(model, selectId) in state.entities); });
7927 if (models.length !== 0) {
7928 merge(models, state);
7929 }
7930 }
7931 function setOneMutably(entity, state) {
7932 return setManyMutably([entity], state);
7933 }
7934 function setManyMutably(newEntities, state) {
7935 newEntities = ensureEntitiesArray(newEntities);
7936 if (newEntities.length !== 0) {
7937 merge(newEntities, state);
7938 }
7939 }
7940 function setAllMutably(newEntities, state) {
7941 newEntities = ensureEntitiesArray(newEntities);
7942 state.entities = {};
7943 state.ids = [];
7944 addManyMutably(newEntities, state);
7945 }
7946 function updateOneMutably(update, state) {
7947 return updateManyMutably([update], state);
7948 }
7949 function updateManyMutably(updates, state) {
7950 var appliedUpdates = false;
7951 for (var _i = 0, updates_1 = updates; _i < updates_1.length; _i++) {
7952 var update = updates_1[_i];
7953 var entity = state.entities[update.id];
7954 if (!entity) {
7955 continue;
7956 }
7957 appliedUpdates = true;
7958 Object.assign(entity, update.changes);
7959 var newId = selectId(entity);
7960 if (update.id !== newId) {
7961 delete state.entities[update.id];
7962 state.entities[newId] = entity;
7963 }
7964 }
7965 if (appliedUpdates) {
7966 resortEntities(state);
7967 }
7968 }
7969 function upsertOneMutably(entity, state) {
7970 return upsertManyMutably([entity], state);
7971 }
7972 function upsertManyMutably(newEntities, state) {
7973 var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];
7974 updateManyMutably(updated, state);
7975 addManyMutably(added, state);
7976 }
7977 function areArraysEqual(a, b) {
7978 if (a.length !== b.length) {
7979 return false;
7980 }
7981 for (var i = 0; i < a.length && i < b.length; i++) {
7982 if (a[i] === b[i]) {
7983 continue;
7984 }
7985 return false;
7986 }
7987 return true;
7988 }
7989 function merge(models, state) {
7990 models.forEach(function (model) {
7991 state.entities[selectId(model)] = model;
7992 });
7993 resortEntities(state);
7994 }
7995 function resortEntities(state) {
7996 var allEntities = Object.values(state.entities);
7997 allEntities.sort(sort);
7998 var newSortedIds = allEntities.map(selectId);
7999 var ids = state.ids;
8000 if (!areArraysEqual(ids, newSortedIds)) {
8001 state.ids = newSortedIds;
8002 }
8003 }
8004 return {
8005 removeOne: removeOne,
8006 removeMany: removeMany,
8007 removeAll: removeAll,
8008 addOne: createStateOperator(addOneMutably),
8009 updateOne: createStateOperator(updateOneMutably),
8010 upsertOne: createStateOperator(upsertOneMutably),
8011 setOne: createStateOperator(setOneMutably),
8012 setMany: createStateOperator(setManyMutably),
8013 setAll: createStateOperator(setAllMutably),
8014 addMany: createStateOperator(addManyMutably),
8015 updateMany: createStateOperator(updateManyMutably),
8016 upsertMany: createStateOperator(upsertManyMutably)
8017 };
8018 }
8019 // src/entities/create_adapter.ts
8020 function createEntityAdapter(options) {
8021 if (options === void 0) { options = {}; }
8022 var _c = __spreadValues({
8023 sortComparer: false,
8024 selectId: function (instance) { return instance.id; }
8025 }, options), selectId = _c.selectId, sortComparer = _c.sortComparer;
8026 var stateFactory = createInitialStateFactory();
8027 var selectorsFactory = createSelectorsFactory();
8028 var stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
8029 return __spreadValues(__spreadValues(__spreadValues({
8030 selectId: selectId,
8031 sortComparer: sortComparer
8032 }, stateFactory), selectorsFactory), stateAdapter);
8033 }
8034 // src/nanoid.ts
8035 var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
8036 var nanoid = function (size) {
8037 if (size === void 0) { size = 21; }
8038 var id = "";
8039 var i = size;
8040 while (i--) {
8041 id += urlAlphabet[Math.random() * 64 | 0];
8042 }
8043 return id;
8044 };
8045 // src/createAsyncThunk.ts
8046 var commonProperties = [
8047 "name",
8048 "message",
8049 "stack",
8050 "code"
8051 ];
8052 var RejectWithValue = /** @class */ (function () {
8053 function RejectWithValue(payload, meta) {
8054 this.payload = payload;
8055 this.meta = meta;
8056 }
8057 return RejectWithValue;
8058 }());
8059 var FulfillWithMeta = /** @class */ (function () {
8060 function FulfillWithMeta(payload, meta) {
8061 this.payload = payload;
8062 this.meta = meta;
8063 }
8064 return FulfillWithMeta;
8065 }());
8066 var miniSerializeError = function (value) {
8067 if (typeof value === "object" && value !== null) {
8068 var simpleError = {};
8069 for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) {
8070 var property = commonProperties_1[_i];
8071 if (typeof value[property] === "string") {
8072 simpleError[property] = value[property];
8073 }
8074 }
8075 return simpleError;
8076 }
8077 return { message: String(value) };
8078 };
8079 var createAsyncThunk = (function () {
8080 function createAsyncThunk2(typePrefix, payloadCreator, options) {
8081 var fulfilled = createAction(typePrefix + "/fulfilled", function (payload, requestId, arg, meta) { return ({
8082 payload: payload,
8083 meta: __spreadProps(__spreadValues({}, meta || {}), {
8084 arg: arg,
8085 requestId: requestId,
8086 requestStatus: "fulfilled"
8087 })
8088 }); });
8089 var pending = createAction(typePrefix + "/pending", function (requestId, arg, meta) { return ({
8090 payload: void 0,
8091 meta: __spreadProps(__spreadValues({}, meta || {}), {
8092 arg: arg,
8093 requestId: requestId,
8094 requestStatus: "pending"
8095 })
8096 }); });
8097 var rejected = createAction(typePrefix + "/rejected", function (error, requestId, arg, payload, meta) { return ({
8098 payload: payload,
8099 error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
8100 meta: __spreadProps(__spreadValues({}, meta || {}), {
8101 arg: arg,
8102 requestId: requestId,
8103 rejectedWithValue: !!payload,
8104 requestStatus: "rejected",
8105 aborted: (error == null ? void 0 : error.name) === "AbortError",
8106 condition: (error == null ? void 0 : error.name) === "ConditionError"
8107 })
8108 }); });
8109 var displayedWarning = false;
8110 var AC = typeof AbortController !== "undefined" ? AbortController : /** @class */ (function () {
8111 function class_1() {
8112 this.signal = {
8113 aborted: false,
8114 addEventListener: function () {
8115 },
8116 dispatchEvent: function () {
8117 return false;
8118 },
8119 onabort: function () {
8120 },
8121 removeEventListener: function () {
8122 },
8123 reason: void 0,
8124 throwIfAborted: function () {
8125 }
8126 };
8127 }
8128 class_1.prototype.abort = function () {
8129 if (true) {
8130 if (!displayedWarning) {
8131 displayedWarning = true;
8132 console.info("This platform does not implement AbortController. \nIf you want to use the AbortController to react to `abort` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.");
8133 }
8134 }
8135 };
8136 return class_1;
8137 }());
8138 function actionCreator(arg) {
8139 return function (dispatch, getState, extra) {
8140 var requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
8141 var abortController = new AC();
8142 var abortReason;
8143 var started = false;
8144 function abort(reason) {
8145 abortReason = reason;
8146 abortController.abort();
8147 }
8148 var promise2 = function () {
8149 return __async(this, null, function () {
8150 var _a, _b, finalAction, conditionResult, abortedPromise, err_1, skipDispatch;
8151 return __generator(this, function (_c) {
8152 switch (_c.label) {
8153 case 0:
8154 _c.trys.push([0, 4, , 5]);
8155 conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState: getState, extra: extra });
8156 if (!isThenable(conditionResult)) return [3 /*break*/, 2];
8157 return [4 /*yield*/, conditionResult];
8158 case 1:
8159 conditionResult = _c.sent();
8160 _c.label = 2;
8161 case 2:
8162 if (conditionResult === false || abortController.signal.aborted) {
8163 throw {
8164 name: "ConditionError",
8165 message: "Aborted due to condition callback returning false."
8166 };
8167 }
8168 started = true;
8169 abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener("abort", function () { return reject({
8170 name: "AbortError",
8171 message: abortReason || "Aborted"
8172 }); }); });
8173 dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId: requestId, arg: arg }, { getState: getState, extra: extra })));
8174 return [4 /*yield*/, Promise.race([
8175 abortedPromise,
8176 Promise.resolve(payloadCreator(arg, {
8177 dispatch: dispatch,
8178 getState: getState,
8179 extra: extra,
8180 requestId: requestId,
8181 signal: abortController.signal,
8182 abort: abort,
8183 rejectWithValue: function (value, meta) {
8184 return new RejectWithValue(value, meta);
8185 },
8186 fulfillWithValue: function (value, meta) {
8187 return new FulfillWithMeta(value, meta);
8188 }
8189 })).then(function (result) {
8190 if (result instanceof RejectWithValue) {
8191 throw result;
8192 }
8193 if (result instanceof FulfillWithMeta) {
8194 return fulfilled(result.payload, requestId, arg, result.meta);
8195 }
8196 return fulfilled(result, requestId, arg);
8197 })
8198 ])];
8199 case 3:
8200 finalAction = _c.sent();
8201 return [3 /*break*/, 5];
8202 case 4:
8203 err_1 = _c.sent();
8204 finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg);
8205 return [3 /*break*/, 5];
8206 case 5:
8207 skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
8208 if (!skipDispatch) {
8209 dispatch(finalAction);
8210 }
8211 return [2 /*return*/, finalAction];
8212 }
8213 });
8214 });
8215 }();
8216 return Object.assign(promise2, {
8217 abort: abort,
8218 requestId: requestId,
8219 arg: arg,
8220 unwrap: function () {
8221 return promise2.then(unwrapResult);
8222 }
8223 });
8224 };
8225 }
8226 return Object.assign(actionCreator, {
8227 pending: pending,
8228 rejected: rejected,
8229 fulfilled: fulfilled,
8230 typePrefix: typePrefix
8231 });
8232 }
8233 createAsyncThunk2.withTypes = function () { return createAsyncThunk2; };
8234 return createAsyncThunk2;
8235 })();
8236 function unwrapResult(action) {
8237 if (action.meta && action.meta.rejectedWithValue) {
8238 throw action.payload;
8239 }
8240 if (action.error) {
8241 throw action.error;
8242 }
8243 return action.payload;
8244 }
8245 function isThenable(value) {
8246 return value !== null && typeof value === "object" && typeof value.then === "function";
8247 }
8248 // src/matchers.ts
8249 var matches = function (matcher, action) {
8250 if (hasMatchFunction(matcher)) {
8251 return matcher.match(action);
8252 }
8253 else {
8254 return matcher(action);
8255 }
8256 };
8257 function isAnyOf() {
8258 var matchers = [];
8259 for (var _i = 0; _i < arguments.length; _i++) {
8260 matchers[_i] = arguments[_i];
8261 }
8262 return function (action) {
8263 return matchers.some(function (matcher) { return matches(matcher, action); });
8264 };
8265 }
8266 function isAllOf() {
8267 var matchers = [];
8268 for (var _i = 0; _i < arguments.length; _i++) {
8269 matchers[_i] = arguments[_i];
8270 }
8271 return function (action) {
8272 return matchers.every(function (matcher) { return matches(matcher, action); });
8273 };
8274 }
8275 function hasExpectedRequestMetadata(action, validStatus) {
8276 if (!action || !action.meta)
8277 return false;
8278 var hasValidRequestId = typeof action.meta.requestId === "string";
8279 var hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
8280 return hasValidRequestId && hasValidRequestStatus;
8281 }
8282 function isAsyncThunkArray(a) {
8283 return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
8284 }
8285 function isPending() {
8286 var asyncThunks = [];
8287 for (var _i = 0; _i < arguments.length; _i++) {
8288 asyncThunks[_i] = arguments[_i];
8289 }
8290 if (asyncThunks.length === 0) {
8291 return function (action) { return hasExpectedRequestMetadata(action, ["pending"]); };
8292 }
8293 if (!isAsyncThunkArray(asyncThunks)) {
8294 return isPending()(asyncThunks[0]);
8295 }
8296 return function (action) {
8297 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.pending; });
8298 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8299 return combinedMatcher(action);
8300 };
8301 }
8302 function isRejected() {
8303 var asyncThunks = [];
8304 for (var _i = 0; _i < arguments.length; _i++) {
8305 asyncThunks[_i] = arguments[_i];
8306 }
8307 if (asyncThunks.length === 0) {
8308 return function (action) { return hasExpectedRequestMetadata(action, ["rejected"]); };
8309 }
8310 if (!isAsyncThunkArray(asyncThunks)) {
8311 return isRejected()(asyncThunks[0]);
8312 }
8313 return function (action) {
8314 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.rejected; });
8315 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8316 return combinedMatcher(action);
8317 };
8318 }
8319 function isRejectedWithValue() {
8320 var asyncThunks = [];
8321 for (var _i = 0; _i < arguments.length; _i++) {
8322 asyncThunks[_i] = arguments[_i];
8323 }
8324 var hasFlag = function (action) {
8325 return action && action.meta && action.meta.rejectedWithValue;
8326 };
8327 if (asyncThunks.length === 0) {
8328 return function (action) {
8329 var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);
8330 return combinedMatcher(action);
8331 };
8332 }
8333 if (!isAsyncThunkArray(asyncThunks)) {
8334 return isRejectedWithValue()(asyncThunks[0]);
8335 }
8336 return function (action) {
8337 var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);
8338 return combinedMatcher(action);
8339 };
8340 }
8341 function isFulfilled() {
8342 var asyncThunks = [];
8343 for (var _i = 0; _i < arguments.length; _i++) {
8344 asyncThunks[_i] = arguments[_i];
8345 }
8346 if (asyncThunks.length === 0) {
8347 return function (action) { return hasExpectedRequestMetadata(action, ["fulfilled"]); };
8348 }
8349 if (!isAsyncThunkArray(asyncThunks)) {
8350 return isFulfilled()(asyncThunks[0]);
8351 }
8352 return function (action) {
8353 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.fulfilled; });
8354 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8355 return combinedMatcher(action);
8356 };
8357 }
8358 function isAsyncThunkAction() {
8359 var asyncThunks = [];
8360 for (var _i = 0; _i < arguments.length; _i++) {
8361 asyncThunks[_i] = arguments[_i];
8362 }
8363 if (asyncThunks.length === 0) {
8364 return function (action) { return hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]); };
8365 }
8366 if (!isAsyncThunkArray(asyncThunks)) {
8367 return isAsyncThunkAction()(asyncThunks[0]);
8368 }
8369 return function (action) {
8370 var matchers = [];
8371 for (var _i = 0, asyncThunks_1 = asyncThunks; _i < asyncThunks_1.length; _i++) {
8372 var asyncThunk = asyncThunks_1[_i];
8373 matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
8374 }
8375 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8376 return combinedMatcher(action);
8377 };
8378 }
8379 // src/listenerMiddleware/utils.ts
8380 var assertFunction = function (func, expected) {
8381 if (typeof func !== "function") {
8382 throw new TypeError(expected + " is not a function");
8383 }
8384 };
8385 var noop = function () {
8386 };
8387 var catchRejection = function (promise2, onError) {
8388 if (onError === void 0) { onError = noop; }
8389 promise2.catch(onError);
8390 return promise2;
8391 };
8392 var addAbortSignalListener = function (abortSignal, callback) {
8393 abortSignal.addEventListener("abort", callback, { once: true });
8394 return function () { return abortSignal.removeEventListener("abort", callback); };
8395 };
8396 var abortControllerWithReason = function (abortController, reason) {
8397 var signal = abortController.signal;
8398 if (signal.aborted) {
8399 return;
8400 }
8401 if (!("reason" in signal)) {
8402 Object.defineProperty(signal, "reason", {
8403 enumerable: true,
8404 value: reason,
8405 configurable: true,
8406 writable: true
8407 });
8408 }
8409 ;
8410 abortController.abort(reason);
8411 };
8412 // src/listenerMiddleware/exceptions.ts
8413 var task = "task";
8414 var listener = "listener";
8415 var completed = "completed";
8416 var cancelled = "cancelled";
8417 var taskCancelled = "task-" + cancelled;
8418 var taskCompleted = "task-" + completed;
8419 var listenerCancelled = listener + "-" + cancelled;
8420 var listenerCompleted = listener + "-" + completed;
8421 var TaskAbortError = /** @class */ (function () {
8422 function TaskAbortError(code) {
8423 this.code = code;
8424 this.name = "TaskAbortError";
8425 this.message = task + " " + cancelled + " (reason: " + code + ")";
8426 }
8427 return TaskAbortError;
8428 }());
8429 // src/listenerMiddleware/task.ts
8430 var validateActive = function (signal) {
8431 if (signal.aborted) {
8432 throw new TaskAbortError(signal.reason);
8433 }
8434 };
8435 function raceWithSignal(signal, promise2) {
8436 var cleanup = noop;
8437 return new Promise(function (resolve, reject) {
8438 var notifyRejection = function () { return reject(new TaskAbortError(signal.reason)); };
8439 if (signal.aborted) {
8440 notifyRejection();
8441 return;
8442 }
8443 cleanup = addAbortSignalListener(signal, notifyRejection);
8444 promise2.finally(function () { return cleanup(); }).then(resolve, reject);
8445 }).finally(function () {
8446 cleanup = noop;
8447 });
8448 }
8449 var runTask = function (task2, cleanUp) { return __async(void 0, null, function () {
8450 var value, error_1;
8451 return __generator(this, function (_c) {
8452 switch (_c.label) {
8453 case 0:
8454 _c.trys.push([0, 3, 4, 5]);
8455 return [4 /*yield*/, Promise.resolve()];
8456 case 1:
8457 _c.sent();
8458 return [4 /*yield*/, task2()];
8459 case 2:
8460 value = _c.sent();
8461 return [2 /*return*/, {
8462 status: "ok",
8463 value: value
8464 }];
8465 case 3:
8466 error_1 = _c.sent();
8467 return [2 /*return*/, {
8468 status: error_1 instanceof TaskAbortError ? "cancelled" : "rejected",
8469 error: error_1
8470 }];
8471 case 4:
8472 cleanUp == null ? void 0 : cleanUp();
8473 return [7 /*endfinally*/];
8474 case 5: return [2 /*return*/];
8475 }
8476 });
8477 }); };
8478 var createPause = function (signal) {
8479 return function (promise2) {
8480 return catchRejection(raceWithSignal(signal, promise2).then(function (output) {
8481 validateActive(signal);
8482 return output;
8483 }));
8484 };
8485 };
8486 var createDelay = function (signal) {
8487 var pause = createPause(signal);
8488 return function (timeoutMs) {
8489 return pause(new Promise(function (resolve) { return setTimeout(resolve, timeoutMs); }));
8490 };
8491 };
8492 // src/listenerMiddleware/index.ts
8493 var assign = Object.assign;
8494 var INTERNAL_NIL_TOKEN = {};
8495 var alm = "listenerMiddleware";
8496 var createFork = function (parentAbortSignal, parentBlockingPromises) {
8497 var linkControllers = function (controller) { return addAbortSignalListener(parentAbortSignal, function () { return abortControllerWithReason(controller, parentAbortSignal.reason); }); };
8498 return function (taskExecutor, opts) {
8499 assertFunction(taskExecutor, "taskExecutor");
8500 var childAbortController = new AbortController();
8501 linkControllers(childAbortController);
8502 var result = runTask(function () { return __async(void 0, null, function () {
8503 var result2;
8504 return __generator(this, function (_c) {
8505 switch (_c.label) {
8506 case 0:
8507 validateActive(parentAbortSignal);
8508 validateActive(childAbortController.signal);
8509 return [4 /*yield*/, taskExecutor({
8510 pause: createPause(childAbortController.signal),
8511 delay: createDelay(childAbortController.signal),
8512 signal: childAbortController.signal
8513 })];
8514 case 1:
8515 result2 = _c.sent();
8516 validateActive(childAbortController.signal);
8517 return [2 /*return*/, result2];
8518 }
8519 });
8520 }); }, function () { return abortControllerWithReason(childAbortController, taskCompleted); });
8521 if (opts == null ? void 0 : opts.autoJoin) {
8522 parentBlockingPromises.push(result);
8523 }
8524 return {
8525 result: createPause(parentAbortSignal)(result),
8526 cancel: function () {
8527 abortControllerWithReason(childAbortController, taskCancelled);
8528 }
8529 };
8530 };
8531 };
8532 var createTakePattern = function (startListening, signal) {
8533 var take = function (predicate, timeout) { return __async(void 0, null, function () {
8534 var unsubscribe, tuplePromise, promises, output;
8535 return __generator(this, function (_c) {
8536 switch (_c.label) {
8537 case 0:
8538 validateActive(signal);
8539 unsubscribe = function () {
8540 };
8541 tuplePromise = new Promise(function (resolve, reject) {
8542 var stopListening = startListening({
8543 predicate: predicate,
8544 effect: function (action, listenerApi) {
8545 listenerApi.unsubscribe();
8546 resolve([
8547 action,
8548 listenerApi.getState(),
8549 listenerApi.getOriginalState()
8550 ]);
8551 }
8552 });
8553 unsubscribe = function () {
8554 stopListening();
8555 reject();
8556 };
8557 });
8558 promises = [
8559 tuplePromise
8560 ];
8561 if (timeout != null) {
8562 promises.push(new Promise(function (resolve) { return setTimeout(resolve, timeout, null); }));
8563 }
8564 _c.label = 1;
8565 case 1:
8566 _c.trys.push([1, , 3, 4]);
8567 return [4 /*yield*/, raceWithSignal(signal, Promise.race(promises))];
8568 case 2:
8569 output = _c.sent();
8570 validateActive(signal);
8571 return [2 /*return*/, output];
8572 case 3:
8573 unsubscribe();
8574 return [7 /*endfinally*/];
8575 case 4: return [2 /*return*/];
8576 }
8577 });
8578 }); };
8579 return function (predicate, timeout) { return catchRejection(take(predicate, timeout)); };
8580 };
8581 var getListenerEntryPropsFrom = function (options) {
8582 var type = options.type, actionCreator = options.actionCreator, matcher = options.matcher, predicate = options.predicate, effect = options.effect;
8583 if (type) {
8584 predicate = createAction(type).match;
8585 }
8586 else if (actionCreator) {
8587 type = actionCreator.type;
8588 predicate = actionCreator.match;
8589 }
8590 else if (matcher) {
8591 predicate = matcher;
8592 }
8593 else if (predicate) {
8594 }
8595 else {
8596 throw new Error("Creating or removing a listener requires one of the known fields for matching an action");
8597 }
8598 assertFunction(effect, "options.listener");
8599 return { predicate: predicate, type: type, effect: effect };
8600 };
8601 var createListenerEntry = function (options) {
8602 var _c = getListenerEntryPropsFrom(options), type = _c.type, predicate = _c.predicate, effect = _c.effect;
8603 var id = nanoid();
8604 var entry = {
8605 id: id,
8606 effect: effect,
8607 type: type,
8608 predicate: predicate,
8609 pending: new Set(),
8610 unsubscribe: function () {
8611 throw new Error("Unsubscribe not initialized");
8612 }
8613 };
8614 return entry;
8615 };
8616 var cancelActiveListeners = function (entry) {
8617 entry.pending.forEach(function (controller) {
8618 abortControllerWithReason(controller, listenerCancelled);
8619 });
8620 };
8621 var createClearListenerMiddleware = function (listenerMap) {
8622 return function () {
8623 listenerMap.forEach(cancelActiveListeners);
8624 listenerMap.clear();
8625 };
8626 };
8627 var safelyNotifyError = function (errorHandler, errorToNotify, errorInfo) {
8628 try {
8629 errorHandler(errorToNotify, errorInfo);
8630 }
8631 catch (errorHandlerError) {
8632 setTimeout(function () {
8633 throw errorHandlerError;
8634 }, 0);
8635 }
8636 };
8637 var addListener = createAction(alm + "/add");
8638 var clearAllListeners = createAction(alm + "/removeAll");
8639 var removeListener = createAction(alm + "/remove");
8640 var defaultErrorHandler = function () {
8641 var args = [];
8642 for (var _i = 0; _i < arguments.length; _i++) {
8643 args[_i] = arguments[_i];
8644 }
8645 console.error.apply(console, __spreadArray([alm + "/error"], args));
8646 };
8647 function createListenerMiddleware(middlewareOptions) {
8648 var _this = this;
8649 if (middlewareOptions === void 0) { middlewareOptions = {}; }
8650 var listenerMap = new Map();
8651 var extra = middlewareOptions.extra, _c = middlewareOptions.onError, onError = _c === void 0 ? defaultErrorHandler : _c;
8652 assertFunction(onError, "onError");
8653 var insertEntry = function (entry) {
8654 entry.unsubscribe = function () { return listenerMap.delete(entry.id); };
8655 listenerMap.set(entry.id, entry);
8656 return function (cancelOptions) {
8657 entry.unsubscribe();
8658 if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
8659 cancelActiveListeners(entry);
8660 }
8661 };
8662 };
8663 var findListenerEntry = function (comparator) {
8664 for (var _i = 0, _c = Array.from(listenerMap.values()); _i < _c.length; _i++) {
8665 var entry = _c[_i];
8666 if (comparator(entry)) {
8667 return entry;
8668 }
8669 }
8670 return void 0;
8671 };
8672 var startListening = function (options) {
8673 var entry = findListenerEntry(function (existingEntry) { return existingEntry.effect === options.effect; });
8674 if (!entry) {
8675 entry = createListenerEntry(options);
8676 }
8677 return insertEntry(entry);
8678 };
8679 var stopListening = function (options) {
8680 var _c = getListenerEntryPropsFrom(options), type = _c.type, effect = _c.effect, predicate = _c.predicate;
8681 var entry = findListenerEntry(function (entry2) {
8682 var matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
8683 return matchPredicateOrType && entry2.effect === effect;
8684 });
8685 if (entry) {
8686 entry.unsubscribe();
8687 if (options.cancelActive) {
8688 cancelActiveListeners(entry);
8689 }
8690 }
8691 return !!entry;
8692 };
8693 var notifyListener = function (entry, action, api, getOriginalState) { return __async(_this, null, function () {
8694 var internalTaskController, take, autoJoinPromises, listenerError_1;
8695 return __generator(this, function (_c) {
8696 switch (_c.label) {
8697 case 0:
8698 internalTaskController = new AbortController();
8699 take = createTakePattern(startListening, internalTaskController.signal);
8700 autoJoinPromises = [];
8701 _c.label = 1;
8702 case 1:
8703 _c.trys.push([1, 3, 4, 6]);
8704 entry.pending.add(internalTaskController);
8705 return [4 /*yield*/, Promise.resolve(entry.effect(action, assign({}, api, {
8706 getOriginalState: getOriginalState,
8707 condition: function (predicate, timeout) { return take(predicate, timeout).then(Boolean); },
8708 take: take,
8709 delay: createDelay(internalTaskController.signal),
8710 pause: createPause(internalTaskController.signal),
8711 extra: extra,
8712 signal: internalTaskController.signal,
8713 fork: createFork(internalTaskController.signal, autoJoinPromises),
8714 unsubscribe: entry.unsubscribe,
8715 subscribe: function () {
8716 listenerMap.set(entry.id, entry);
8717 },
8718 cancelActiveListeners: function () {
8719 entry.pending.forEach(function (controller, _, set) {
8720 if (controller !== internalTaskController) {
8721 abortControllerWithReason(controller, listenerCancelled);
8722 set.delete(controller);
8723 }
8724 });
8725 }
8726 })))];
8727 case 2:
8728 _c.sent();
8729 return [3 /*break*/, 6];
8730 case 3:
8731 listenerError_1 = _c.sent();
8732 if (!(listenerError_1 instanceof TaskAbortError)) {
8733 safelyNotifyError(onError, listenerError_1, {
8734 raisedBy: "effect"
8735 });
8736 }
8737 return [3 /*break*/, 6];
8738 case 4: return [4 /*yield*/, Promise.allSettled(autoJoinPromises)];
8739 case 5:
8740 _c.sent();
8741 abortControllerWithReason(internalTaskController, listenerCompleted);
8742 entry.pending.delete(internalTaskController);
8743 return [7 /*endfinally*/];
8744 case 6: return [2 /*return*/];
8745 }
8746 });
8747 }); };
8748 var clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
8749 var middleware = function (api) { return function (next) { return function (action) {
8750 if (!isAction(action)) {
8751 return next(action);
8752 }
8753 if (addListener.match(action)) {
8754 return startListening(action.payload);
8755 }
8756 if (clearAllListeners.match(action)) {
8757 clearListenerMiddleware();
8758 return;
8759 }
8760 if (removeListener.match(action)) {
8761 return stopListening(action.payload);
8762 }
8763 var originalState = api.getState();
8764 var getOriginalState = function () {
8765 if (originalState === INTERNAL_NIL_TOKEN) {
8766 throw new Error(alm + ": getOriginalState can only be called synchronously");
8767 }
8768 return originalState;
8769 };
8770 var result;
8771 try {
8772 result = next(action);
8773 if (listenerMap.size > 0) {
8774 var currentState = api.getState();
8775 var listenerEntries = Array.from(listenerMap.values());
8776 for (var _i = 0, listenerEntries_1 = listenerEntries; _i < listenerEntries_1.length; _i++) {
8777 var entry = listenerEntries_1[_i];
8778 var runListener = false;
8779 try {
8780 runListener = entry.predicate(action, currentState, originalState);
8781 }
8782 catch (predicateError) {
8783 runListener = false;
8784 safelyNotifyError(onError, predicateError, {
8785 raisedBy: "predicate"
8786 });
8787 }
8788 if (!runListener) {
8789 continue;
8790 }
8791 notifyListener(entry, action, api, getOriginalState);
8792 }
8793 }
8794 }
8795 finally {
8796 originalState = INTERNAL_NIL_TOKEN;
8797 }
8798 return result;
8799 }; }; };
8800 return {
8801 middleware: middleware,
8802 startListening: startListening,
8803 stopListening: stopListening,
8804 clearListeners: clearListenerMiddleware
8805 };
8806 }
8807 // src/autoBatchEnhancer.ts
8808 var SHOULD_AUTOBATCH = "RTK_autoBatch";
8809 var prepareAutoBatched = function () { return function (payload) {
8810 var _c;
8811 return ({
8812 payload: payload,
8813 meta: (_c = {}, _c[SHOULD_AUTOBATCH] = true, _c)
8814 });
8815 }; };
8816 var promise;
8817 var queueMicrotaskShim = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : globalThis) : function (cb) { return (promise || (promise = Promise.resolve())).then(cb).catch(function (err) { return setTimeout(function () {
8818 throw err;
8819 }, 0); }); };
8820 var createQueueWithTimer = function (timeout) {
8821 return function (notify) {
8822 setTimeout(notify, timeout);
8823 };
8824 };
8825 var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
8826 var autoBatchEnhancer = function (options) {
8827 if (options === void 0) { options = { type: "raf" }; }
8828 return function (next) { return function () {
8829 var args = [];
8830 for (var _i = 0; _i < arguments.length; _i++) {
8831 args[_i] = arguments[_i];
8832 }
8833 var store = next.apply(void 0, args);
8834 var notifying = true;
8835 var shouldNotifyAtEndOfTick = false;
8836 var notificationQueued = false;
8837 var listeners = new Set();
8838 var queueCallback = options.type === "tick" ? queueMicrotaskShim : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
8839 var notifyListeners = function () {
8840 notificationQueued = false;
8841 if (shouldNotifyAtEndOfTick) {
8842 shouldNotifyAtEndOfTick = false;
8843 listeners.forEach(function (l) { return l(); });
8844 }
8845 };
8846 return Object.assign({}, store, {
8847 subscribe: function (listener2) {
8848 var wrappedListener = function () { return notifying && listener2(); };
8849 var unsubscribe = store.subscribe(wrappedListener);
8850 listeners.add(listener2);
8851 return function () {
8852 unsubscribe();
8853 listeners.delete(listener2);
8854 };
8855 },
8856 dispatch: function (action) {
8857 var _a;
8858 try {
8859 notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
8860 shouldNotifyAtEndOfTick = !notifying;
8861 if (shouldNotifyAtEndOfTick) {
8862 if (!notificationQueued) {
8863 notificationQueued = true;
8864 queueCallback(notifyListeners);
8865 }
8866 }
8867 return store.dispatch(action);
8868 }
8869 finally {
8870 notifying = true;
8871 }
8872 }
8873 });
8874 }; };
8875 };
8876 // src/index.ts
8877 (0,immer__WEBPACK_IMPORTED_MODULE_0__.enableES5)();
8878
8879 //# sourceMappingURL=redux-toolkit.esm.js.map
8880
8881 /***/ }),
8882
8883 /***/ "../node_modules/immer/dist/immer.esm.mjs":
8884 /*!************************************************!*\
8885 !*** ../node_modules/immer/dist/immer.esm.mjs ***!
8886 \************************************************/
8887 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
8888
8889 "use strict";
8890 __webpack_require__.r(__webpack_exports__);
8891 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
8892 /* harmony export */ Immer: () => (/* binding */ un),
8893 /* harmony export */ applyPatches: () => (/* binding */ pn),
8894 /* harmony export */ castDraft: () => (/* binding */ K),
8895 /* harmony export */ castImmutable: () => (/* binding */ $),
8896 /* harmony export */ createDraft: () => (/* binding */ ln),
8897 /* harmony export */ current: () => (/* binding */ R),
8898 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
8899 /* harmony export */ enableAllPlugins: () => (/* binding */ J),
8900 /* harmony export */ enableES5: () => (/* binding */ F),
8901 /* harmony export */ enableMapSet: () => (/* binding */ C),
8902 /* harmony export */ enablePatches: () => (/* binding */ T),
8903 /* harmony export */ finishDraft: () => (/* binding */ dn),
8904 /* harmony export */ freeze: () => (/* binding */ d),
8905 /* harmony export */ immerable: () => (/* binding */ L),
8906 /* harmony export */ isDraft: () => (/* binding */ r),
8907 /* harmony export */ isDraftable: () => (/* binding */ t),
8908 /* harmony export */ nothing: () => (/* binding */ H),
8909 /* harmony export */ original: () => (/* binding */ e),
8910 /* harmony export */ produce: () => (/* binding */ fn),
8911 /* harmony export */ produceWithPatches: () => (/* binding */ cn),
8912 /* harmony export */ setAutoFreeze: () => (/* binding */ sn),
8913 /* harmony export */ setUseProxies: () => (/* binding */ vn)
8914 /* harmony export */ });
8915 function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e<r;e++)t[e-1]=arguments[e];if(true){var i=Y[n],o=i?"function"==typeof i?i.apply(null,t):i:"unknown error nr: "+n;throw Error("[Immer] "+o)}// removed by dead control flow
8916 }function r(n){return!!n&&!!n[Q]}function t(n){var r;return!!n&&(function(n){if(!n||"object"!=typeof n)return!1;var r=Object.getPrototypeOf(n);if(null===r)return!0;var t=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;return t===Object||"function"==typeof t&&Function.toString.call(t)===Z}(n)||Array.isArray(n)||!!n[L]||!!(null===(r=n.constructor)||void 0===r?void 0:r[L])||s(n)||v(n))}function e(t){return r(t)||n(23,t),t[Q].t}function i(n,r,t){void 0===t&&(t=!1),0===o(n)?(t?Object.keys:nn)(n).forEach((function(e){t&&"symbol"==typeof e||r(e,n[e],n)})):n.forEach((function(t,e){return r(e,t,n)}))}function o(n){var r=n[Q];return r?r.i>3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?n.add(t):n[r]=t}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e<t.length;e++){var i=t[e],o=r[i];!1===o.writable&&(o.writable=!0,o.configurable=!0),(o.get||o.set)&&(r[i]={configurable:!0,writable:!0,enumerable:o.enumerable,value:n[i]})}return Object.create(Object.getPrototypeOf(n),r)}function d(n,e){return void 0===e&&(e=!1),y(n)||r(n)||!t(n)||(o(n)>1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i(n,(function(n,r){return d(r,!0)}),!0)),n}function h(){n(2)}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function m(n,r){tn[n]||(tn[n]=r)}function _(){return false||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r)}function g(n){O(n),n.p.forEach(S),n.p=null}function O(n){n===U&&(U=n.l)}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.g=!0}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.O||b("ES5").S(e,r,o),o?(i[Q].P&&(g(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),g(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o,u=o,a=!1;3===e.i&&(u=new Set(o),o.clear(),a=!0),i(u,(function(r,i){return A(n,e,o,r,i,t,a)})),x(n,o,!1),t&&n.u&&b("Patches").N(e,t,n.u,n.s)}return e.o}function A(e,i,o,a,c,s,v){if( true&&c===o&&n(5),r(c)){var p=M(e,c,s&&i&&3!==i.i&&!u(i.R,a)?s.concat(a):void 0);if(f(o,a,p),!r(p))return;e.m=!1}else v&&o.add(c);if(t(c)&&!y(c)){if(!e.h.D&&e._<1)return;M(e,c),i&&i.A.l||x(e,c)}}function x(n,r,t){void 0===t&&(t=!1),!n.l&&n.h.D&&n.m&&d(r,t)}function z(n,r){var t=n[Q];return(t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t)}}function k(n){n.P||(n.P=!0,n.l&&k(n.l))}function E(n){n.o||(n.o=l(n.t))}function N(n,r,t){var e=s(r)?b("MapSet").F(r,t):v(r)?b("MapSet").T(r,t):n.O?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,R:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return(t?t.A:_()).p.push(e),e}function R(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=D(r,c),u.I=!1}else e=D(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t))})),3===c?new Set(e):e}(e)}function D(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}function F(){function t(n,r){var t=s[n];return t?t.enumerable=r:s[n]=t={configurable:!0,enumerable:r,get:function(){var r=this[Q];return true&&f(r),en.get(r,n)},set:function(r){var t=this[Q]; true&&f(t),en.set(t,n,r)}},t}function e(n){for(var r=n.length-1;r>=0;r--){var t=n[r][Q];if(!t.P)switch(t.i){case 5:a(t)&&k(t);break;case 4:o(t)&&k(t)}}}function o(n){for(var r=n.t,t=n.k,e=nn(t),i=e.length-1;i>=0;i--){var o=e[i];if(o!==Q){var a=r[o];if(void 0===a&&!u(r,o))return!0;var f=t[o],s=f&&f[Q];if(s?s.t!==a:!c(f,a))return!0}}var v=!!r[Q];return e.length!==nn(r).length+(v?0:1)}function a(n){var r=n.k;if(r.length!==n.t.length)return!0;var t=Object.getOwnPropertyDescriptor(r,r.length-1);if(t&&!t.get)return!0;for(var e=0;e<r.length;e++)if(!r.hasOwnProperty(e))return!0;return!1}function f(r){r.g&&n(3,JSON.stringify(p(r)))}var s={};m("ES5",{J:function(n,r){var e=Array.isArray(n),i=function(n,r){if(n){for(var e=Array(r.length),i=0;i<r.length;i++)Object.defineProperty(e,""+i,t(i,!0));return e}var o=rn(r);delete o[Q];for(var u=nn(o),a=0;a<u.length;a++){var f=u[a];o[f]=t(f,n||!!o[f].enumerable)}return Object.create(Object.getPrototypeOf(r),o)}(e,n),o={i:e?5:4,A:r?r.A:_(),P:!1,I:!1,R:{},l:r,t:n,k:i,o:null,g:!1,C:!1};return Object.defineProperty(i,Q,{value:o,writable:!0}),i},S:function(n,t,o){o?r(t)&&t[Q].A===n&&e(n.p):(n.u&&function n(r){if(r&&"object"==typeof r){var t=r[Q];if(t){var e=t.t,o=t.k,f=t.R,c=t.i;if(4===c)i(o,(function(r){r!==Q&&(void 0!==e[r]||u(e,r)?f[r]||n(o[r]):(f[r]=!0,k(t)))})),i(e,(function(n){void 0!==o[n]||u(o,n)||(f[n]=!1,k(t))}));else if(5===c){if(a(t)&&(k(t),f.length=!0),o.length<e.length)for(var s=o.length;s<e.length;s++)f[s]=!1;else for(var v=e.length;v<o.length;v++)f[v]=!0;for(var p=Math.min(o.length,e.length),l=0;l<p;l++)o.hasOwnProperty(l)||(f[l]=!0),void 0===f[l]&&n(o[l])}}}}(n.p[0]),e(n.p))},K:function(n){return 4===n.i?o(n):a(n)}})}function T(){function e(n){if(!t(n))return n;if(Array.isArray(n))return n.map(e);if(s(n))return new Map(Array.from(n.entries()).map((function(n){return[n[0],e(n[1])]})));if(v(n))return new Set(Array.from(n).map(e));var r=Object.create(Object.getPrototypeOf(n));for(var i in n)r[i]=e(n[i]);return u(n,L)&&(r[L]=n[L]),r}function f(n){return r(n)?e(n):n}var c="add";m("Patches",{$:function(r,t){return t.forEach((function(t){for(var i=t.path,u=t.op,f=r,s=0;s<i.length-1;s++){var v=o(f),p=i[s];"string"!=typeof p&&"number"!=typeof p&&(p=""+p),0!==v&&1!==v||"__proto__"!==p&&"constructor"!==p||n(24),"function"==typeof f&&"prototype"===p&&n(24),"object"!=typeof(f=a(f,p))&&n(15,i.join("/"))}var l=o(f),d=e(t.value),h=i[i.length-1];switch(u){case"replace":switch(l){case 2:return f.set(h,d);case 3:n(16);default:return f[h]=d}case c:switch(l){case 1:return"-"===h?f.push(d):f.splice(h,0,d);case 2:return f.set(h,d);case 3:return f.add(d);default:return f[h]=d}case"remove":switch(l){case 1:return f.splice(h,1);case 2:return f.delete(h);case 3:return f.delete(t.value);default:return delete f[h]}default:n(17,u)}})),r},N:function(n,r,t,e){switch(n.i){case 0:case 4:case 2:return function(n,r,t,e){var o=n.t,s=n.o;i(n.R,(function(n,i){var v=a(o,n),p=a(s,n),l=i?u(o,n)?"replace":c:"remove";if(v!==p||"replace"!==l){var d=r.concat(n);t.push("remove"===l?{op:l,path:d}:{op:l,path:d,value:p}),e.push(l===c?{op:"remove",path:d}:"remove"===l?{op:c,path:d,value:f(v)}:{op:"replace",path:d,value:f(v)})}}))}(n,r,t,e);case 5:case 1:return function(n,r,t,e){var i=n.t,o=n.R,u=n.o;if(u.length<i.length){var a=[u,i];i=a[0],u=a[1];var s=[e,t];t=s[0],e=s[1]}for(var v=0;v<i.length;v++)if(o[v]&&u[v]!==i[v]){var p=r.concat([v]);t.push({op:"replace",path:p,value:f(u[v])}),e.push({op:"replace",path:p,value:f(i[v])})}for(var l=i.length;l<u.length;l++){var d=r.concat([l]);t.push({op:c,path:d,value:f(u[l])})}i.length<u.length&&e.push({op:"replace",path:r.concat(["length"]),value:i.length})}(n,r,t,e);case 3:return function(n,r,t,e){var i=n.t,o=n.o,u=0;i.forEach((function(n){if(!o.has(n)){var i=r.concat([u]);t.push({op:"remove",path:i,value:n}),e.unshift({op:c,path:i,value:n})}u++})),u=0,o.forEach((function(n){if(!i.has(n)){var o=r.concat([u]);t.push({op:c,path:o,value:n}),e.unshift({op:"remove",path:o,value:n})}u++}))}(n,r,t,e)}},M:function(n,r,t,e){t.push({op:"replace",path:[],value:r===H?void 0:r}),e.push({op:"replace",path:[],value:n})}})}function C(){function r(n,r){function t(){this.constructor=n}a(n,r),n.prototype=(t.prototype=r.prototype,new t)}function e(n){n.o||(n.R=new Map,n.o=new Map(n.t))}function o(n){n.o||(n.o=new Set,n.t.forEach((function(r){if(t(r)){var e=N(n.A.h,r,n);n.p.set(r,e),n.o.add(e)}else n.o.add(r)})))}function u(r){r.g&&n(3,JSON.stringify(p(r)))}var a=function(n,r){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var t in r)r.hasOwnProperty(t)&&(n[t]=r[t])})(n,r)},f=function(){function n(n,r){return this[Q]={i:2,l:r,A:r?r.A:_(),P:!1,I:!1,o:void 0,R:void 0,t:n,k:this,C:!1,g:!1},this}r(n,Map);var o=n.prototype;return Object.defineProperty(o,"size",{get:function(){return p(this[Q]).size}}),o.has=function(n){return p(this[Q]).has(n)},o.set=function(n,r){var t=this[Q];return u(t),p(t).has(n)&&p(t).get(n)===r||(e(t),k(t),t.R.set(n,!0),t.o.set(n,r),t.R.set(n,!0)),this},o.delete=function(n){if(!this.has(n))return!1;var r=this[Q];return u(r),e(r),k(r),r.t.has(n)?r.R.set(n,!1):r.R.delete(n),r.o.delete(n),!0},o.clear=function(){var n=this[Q];u(n),p(n).size&&(e(n),k(n),n.R=new Map,i(n.t,(function(r){n.R.set(r,!1)})),n.o.clear())},o.forEach=function(n,r){var t=this;p(this[Q]).forEach((function(e,i){n.call(r,t.get(i),i,t)}))},o.get=function(n){var r=this[Q];u(r);var i=p(r).get(n);if(r.I||!t(i))return i;if(i!==r.t.get(n))return i;var o=N(r.A.h,i,r);return e(r),r.o.set(n,o),o},o.keys=function(){return p(this[Q]).keys()},o.values=function(){var n,r=this,t=this.keys();return(n={})[V]=function(){return r.values()},n.next=function(){var n=t.next();return n.done?n:{done:!1,value:r.get(n.value)}},n},o.entries=function(){var n,r=this,t=this.keys();return(n={})[V]=function(){return r.entries()},n.next=function(){var n=t.next();if(n.done)return n;var e=r.get(n.value);return{done:!1,value:[n.value,e]}},n},o[V]=function(){return this.entries()},n}(),c=function(){function n(n,r){return this[Q]={i:3,l:r,A:r?r.A:_(),P:!1,I:!1,o:void 0,t:n,k:this,p:new Map,g:!1,C:!1},this}r(n,Set);var t=n.prototype;return Object.defineProperty(t,"size",{get:function(){return p(this[Q]).size}}),t.has=function(n){var r=this[Q];return u(r),r.o?!!r.o.has(n)||!(!r.p.has(n)||!r.o.has(r.p.get(n))):r.t.has(n)},t.add=function(n){var r=this[Q];return u(r),this.has(n)||(o(r),k(r),r.o.add(n)),this},t.delete=function(n){if(!this.has(n))return!1;var r=this[Q];return u(r),o(r),k(r),r.o.delete(n)||!!r.p.has(n)&&r.o.delete(r.p.get(n))},t.clear=function(){var n=this[Q];u(n),p(n).size&&(o(n),k(n),n.o.clear())},t.values=function(){var n=this[Q];return u(n),o(n),n.o.values()},t.entries=function(){var n=this[Q];return u(n),o(n),n.o.entries()},t.keys=function(){return this.values()},t[V]=function(){return this.values()},t.forEach=function(n,r){for(var t=this.values(),e=t.next();!e.done;)n.call(r,e.value,e.value,this),e=t.next()},n}();m("MapSet",{F:function(n,r){return new f(n,r)},T:function(n,r){return new c(n,r)}})}function J(){F(),C(),T()}function K(n){return n}function $(n){return n}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",V="undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return"Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return"Unsupported patch operation: "+n},18:function(n){return"The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return"'current' expects a draft, got: "+n},23:function(n){return"'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t)})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=N(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.R[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return!0;E(n),k(n)}return n.o[r]===t&&(void 0!==t||r in n.o)||Number.isNaN(t)&&Number.isNaN(n.o[r])||(n.o[r]=t,n.R[r]=!0),!0},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.R[r]=!1,E(n),k(n)):delete n.R[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11)},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12)}},on={};i(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}})),on.deleteProperty=function(r,t){return true&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return true&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.O=B,this.D=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o<t;o++)e[o-1]=arguments[o];return a.produce(n,(function(n){var t;return(t=i).call.apply(t,[r,n].concat(e))}))}}var f;if("function"!=typeof i&&n(6),void 0!==o&&"function"!=typeof o&&n(7),t(r)){var c=w(e),s=N(e,r,void 0),v=!0;try{f=i(s),v=!1}finally{v?g(c):O(c)}return"undefined"!=typeof Promise&&f instanceof Promise?f.then((function(n){return j(c,o),P(n,c)}),(function(n){throw g(c),n})):(j(c,o),P(f,c))}if(!r||"object"!=typeof r){if(void 0===(f=i(r))&&(f=r),f===H&&(f=void 0),e.D&&d(f,!0),o){var p=[],l=[];b("Patches").M(r,f,p,l),o(p,l)}return f}n(21,r)},this.produceWithPatches=function(n,r){if("function"==typeof n)return function(r){for(var t=arguments.length,i=Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];return e.produceWithPatches(r,(function(r){return n.apply(void 0,[r].concat(i))}))};var t,i,o=e.produce(n,r,(function(n,r){t=n,i=r}));return"undefined"!=typeof Promise&&o instanceof Promise?o.then((function(n){return[n,t,i]})):[o,t,i]},"boolean"==typeof(null==r?void 0:r.useProxies)&&this.setUseProxies(r.useProxies),"boolean"==typeof(null==r?void 0:r.autoFreeze)&&this.setAutoFreeze(r.autoFreeze)}var i=e.prototype;return i.createDraft=function(e){t(e)||n(8),r(e)&&(e=R(e));var i=w(this),o=N(this,e,void 0);return o[Q].C=!0,O(i),o},i.finishDraft=function(r,t){var e=r&&r[Q]; true&&(e&&e.C||n(9),e.I&&n(10));var i=e.A;return j(i,t),P(void 0,i)},i.setAutoFreeze=function(n){this.D=n},i.setUseProxies=function(r){r&&!B&&n(20),this.O=r},i.applyPatches=function(n,t){var e;for(e=t.length-1;e>=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce,cn=an.produceWithPatches.bind(an),sn=an.setAutoFreeze.bind(an),vn=an.setUseProxies.bind(an),pn=an.applyPatches.bind(an),ln=an.createDraft.bind(an),dn=an.finishDraft.bind(an);/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (fn);
8917 //# sourceMappingURL=immer.esm.js.map
8918
8919
8920 /***/ }),
8921
8922 /***/ "../node_modules/mixpanel-browser/dist/mixpanel.module.js":
8923 /*!****************************************************************!*\
8924 !*** ../node_modules/mixpanel-browser/dist/mixpanel.module.js ***!
8925 \****************************************************************/
8926 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
8927
8928 "use strict";
8929 __webpack_require__.r(__webpack_exports__);
8930 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
8931 /* harmony export */ "default": () => (/* binding */ mixpanel)
8932 /* harmony export */ });
8933 // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
8934 var win;
8935 if (typeof(window) === 'undefined') {
8936 var loc = {
8937 hostname: ''
8938 };
8939 win = {
8940 crypto: {randomUUID: function() {throw Error('unsupported');}},
8941 navigator: { userAgent: '', onLine: true },
8942 document: {
8943 createElement: function() { return {}; },
8944 location: loc,
8945 referrer: ''
8946 },
8947 screen: { width: 0, height: 0 },
8948 location: loc,
8949 addEventListener: function() {},
8950 removeEventListener: function() {}
8951 };
8952 } else {
8953 win = window;
8954 }
8955
8956 function _array_like_to_array(arr, len) {
8957 if (len == null || len > arr.length) len = arr.length;
8958 for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
8959 return arr2;
8960 }
8961 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
8962 try {
8963 var info = gen[key](arg);
8964 var value = info.value;
8965 } catch (error) {
8966 reject(error);
8967 return;
8968 }
8969 if (info.done) {
8970 resolve(value);
8971 } else {
8972 Promise.resolve(value).then(_next, _throw);
8973 }
8974 }
8975 function _async_to_generator(fn) {
8976 return function() {
8977 var self = this, args = arguments;
8978 return new Promise(function(resolve, reject) {
8979 var gen = fn.apply(self, args);
8980 function _next(value) {
8981 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
8982 }
8983 function _throw(err) {
8984 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
8985 }
8986 _next(undefined);
8987 });
8988 };
8989 }
8990 function _construct(Parent, args, Class) {
8991 if (_is_native_reflect_construct()) {
8992 _construct = Reflect.construct;
8993 } else {
8994 _construct = function construct(Parent, args, Class) {
8995 var a = [
8996 null
8997 ];
8998 a.push.apply(a, args);
8999 var Constructor = Function.bind.apply(Parent, a);
9000 var instance = new Constructor();
9001 if (Class) _set_prototype_of(instance, Class.prototype);
9002 return instance;
9003 };
9004 }
9005 return _construct.apply(null, arguments);
9006 }
9007 function _defineProperties(target, props) {
9008 for(var i = 0; i < props.length; i++){
9009 var descriptor = props[i];
9010 descriptor.enumerable = descriptor.enumerable || false;
9011 descriptor.configurable = true;
9012 if ("value" in descriptor) descriptor.writable = true;
9013 Object.defineProperty(target, descriptor.key, descriptor);
9014 }
9015 }
9016 function _create_class(Constructor, protoProps, staticProps) {
9017 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
9018 return Constructor;
9019 }
9020 function _extends() {
9021 _extends = Object.assign || function(target) {
9022 for(var i = 1; i < arguments.length; i++){
9023 var source = arguments[i];
9024 for(var key in source){
9025 if (Object.prototype.hasOwnProperty.call(source, key)) {
9026 target[key] = source[key];
9027 }
9028 }
9029 }
9030 return target;
9031 };
9032 return _extends.apply(this, arguments);
9033 }
9034 function _get_prototype_of(o) {
9035 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
9036 return o.__proto__ || Object.getPrototypeOf(o);
9037 };
9038 return _get_prototype_of(o);
9039 }
9040 function _inherits(subClass, superClass) {
9041 if (typeof superClass !== "function" && superClass !== null) {
9042 throw new TypeError("Super expression must either be null or a function");
9043 }
9044 subClass.prototype = Object.create(superClass && superClass.prototype, {
9045 constructor: {
9046 value: subClass,
9047 writable: true,
9048 configurable: true
9049 }
9050 });
9051 if (superClass) _set_prototype_of(subClass, superClass);
9052 }
9053 function _instanceof(left, right) {
9054 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
9055 return !!right[Symbol.hasInstance](left);
9056 } else {
9057 return left instanceof right;
9058 }
9059 }
9060 function _is_native_function(fn) {
9061 return Function.toString.call(fn).indexOf("[native code]") !== -1;
9062 }
9063 function _object_without_properties_loose(source, excluded) {
9064 if (source == null) return {};
9065 var target = {};
9066 var sourceKeys = Object.keys(source);
9067 var key, i;
9068 for(i = 0; i < sourceKeys.length; i++){
9069 key = sourceKeys[i];
9070 if (excluded.indexOf(key) >= 0) continue;
9071 target[key] = source[key];
9072 }
9073 return target;
9074 }
9075 function _set_prototype_of(o, p) {
9076 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
9077 o.__proto__ = p;
9078 return o;
9079 };
9080 return _set_prototype_of(o, p);
9081 }
9082 function _type_of(obj) {
9083 "@swc/helpers - typeof";
9084 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
9085 }
9086 function _unsupported_iterable_to_array(o, minLen) {
9087 if (!o) return;
9088 if (typeof o === "string") return _array_like_to_array(o, minLen);
9089 var n = Object.prototype.toString.call(o).slice(8, -1);
9090 if (n === "Object" && o.constructor) n = o.constructor.name;
9091 if (n === "Map" || n === "Set") return Array.from(n);
9092 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
9093 }
9094 function _wrap_native_super(Class) {
9095 var _cache = typeof Map === "function" ? new Map() : undefined;
9096 _wrap_native_super = function wrapNativeSuper(Class) {
9097 if (Class === null || !_is_native_function(Class)) return Class;
9098 if (typeof Class !== "function") {
9099 throw new TypeError("Super expression must either be null or a function");
9100 }
9101 if (typeof _cache !== "undefined") {
9102 if (_cache.has(Class)) return _cache.get(Class);
9103 _cache.set(Class, Wrapper);
9104 }
9105 function Wrapper() {
9106 return _construct(Class, arguments, _get_prototype_of(this).constructor);
9107 }
9108 Wrapper.prototype = Object.create(Class.prototype, {
9109 constructor: {
9110 value: Wrapper,
9111 enumerable: false,
9112 writable: true,
9113 configurable: true
9114 }
9115 });
9116 return _set_prototype_of(Wrapper, Class);
9117 };
9118 return _wrap_native_super(Class);
9119 }
9120 function _is_native_reflect_construct() {
9121 try {
9122 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
9123 } catch (_) {}
9124 return (_is_native_reflect_construct = function() {
9125 return !!result;
9126 })();
9127 }
9128 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
9129 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
9130 if (it) return (it = it.call(o)).next.bind(it);
9131 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
9132 if (it) o = it;
9133 var i = 0;
9134 return function() {
9135 if (i >= o.length) {
9136 return {
9137 done: true
9138 };
9139 }
9140 return {
9141 done: false,
9142 value: o[i++]
9143 };
9144 };
9145 }
9146 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
9147 }
9148 function _ts_generator(thisArg, body) {
9149 var f, y, t, g, _ = {
9150 label: 0,
9151 sent: function() {
9152 if (t[0] & 1) throw t[1];
9153 return t[1];
9154 },
9155 trys: [],
9156 ops: []
9157 };
9158 return g = {
9159 next: verb(0),
9160 "throw": verb(1),
9161 "return": verb(2)
9162 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
9163 return this;
9164 }), g;
9165 function verb(n) {
9166 return function(v) {
9167 return step([
9168 n,
9169 v
9170 ]);
9171 };
9172 }
9173 function step(op) {
9174 if (f) throw new TypeError("Generator is already executing.");
9175 while(_)try {
9176 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
9177 if (y = 0, t) op = [
9178 op[0] & 2,
9179 t.value
9180 ];
9181 switch(op[0]){
9182 case 0:
9183 case 1:
9184 t = op;
9185 break;
9186 case 4:
9187 _.label++;
9188 return {
9189 value: op[1],
9190 done: false
9191 };
9192 case 5:
9193 _.label++;
9194 y = op[1];
9195 op = [
9196 0
9197 ];
9198 continue;
9199 case 7:
9200 op = _.ops.pop();
9201 _.trys.pop();
9202 continue;
9203 default:
9204 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
9205 _ = 0;
9206 continue;
9207 }
9208 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
9209 _.label = op[1];
9210 break;
9211 }
9212 if (op[0] === 6 && _.label < t[1]) {
9213 _.label = t[1];
9214 t = op;
9215 break;
9216 }
9217 if (t && _.label < t[2]) {
9218 _.label = t[2];
9219 _.ops.push(op);
9220 break;
9221 }
9222 if (t[2]) _.ops.pop();
9223 _.trys.pop();
9224 continue;
9225 }
9226 op = body.call(thisArg, _);
9227 } catch (e) {
9228 op = [
9229 6,
9230 e
9231 ];
9232 y = 0;
9233 } finally{
9234 f = t = 0;
9235 }
9236 if (op[0] & 5) throw op[1];
9237 return {
9238 value: op[0] ? op[1] : void 0,
9239 done: true
9240 };
9241 }
9242 }
9243 function _ts_values(o) {
9244 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
9245 if (m) return m.call(o);
9246 if (o && typeof o.length === "number") return {
9247 next: function() {
9248 if (o && i >= o.length) o = void 0;
9249 return {
9250 value: o && o[i++],
9251 done: !o
9252 };
9253 }
9254 };
9255 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
9256 }
9257 var __defProp = Object.defineProperty;
9258 var __defNormalProp = function(obj, key, value) {
9259 return key in obj ? __defProp(obj, key, {
9260 enumerable: true,
9261 configurable: true,
9262 writable: true,
9263 value: value
9264 }) : obj[key] = value;
9265 };
9266 var __publicField = function(obj, key, value) {
9267 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
9268 };
9269 var _a;
9270 var __defProp$1 = Object.defineProperty;
9271 var __defNormalProp$1 = function(obj, key, value) {
9272 return key in obj ? __defProp$1(obj, key, {
9273 enumerable: true,
9274 configurable: true,
9275 writable: true,
9276 value: value
9277 }) : obj[key] = value;
9278 };
9279 var __publicField$1 = function(obj, key, value) {
9280 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
9281 };
9282 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
9283 NodeType2[NodeType2["Document"] = 0] = "Document";
9284 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
9285 NodeType2[NodeType2["Element"] = 2] = "Element";
9286 NodeType2[NodeType2["Text"] = 3] = "Text";
9287 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
9288 NodeType2[NodeType2["Comment"] = 5] = "Comment";
9289 return NodeType2;
9290 }(NodeType$3 || {});
9291 var testableAccessors$1 = {
9292 Node: [
9293 "childNodes",
9294 "parentNode",
9295 "parentElement",
9296 "textContent"
9297 ],
9298 ShadowRoot: [
9299 "host",
9300 "styleSheets"
9301 ],
9302 Element: [
9303 "shadowRoot",
9304 "querySelector",
9305 "querySelectorAll"
9306 ],
9307 MutationObserver: []
9308 };
9309 var testableMethods$1 = {
9310 Node: [
9311 "contains",
9312 "getRootNode"
9313 ],
9314 ShadowRoot: [
9315 "getSelection"
9316 ],
9317 Element: [],
9318 MutationObserver: [
9319 "constructor"
9320 ]
9321 };
9322 var untaintedBasePrototype$1 = {};
9323 var isAngularZonePresent$1 = function() {
9324 return !!globalThis.Zone;
9325 };
9326 function getUntaintedPrototype$1(key) {
9327 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
9328 var defaultObj = globalThis[key];
9329 var defaultPrototype = defaultObj.prototype;
9330 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
9331 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
9332 accessorNames.every(function(accessor) {
9333 var _a2, _b;
9334 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
9335 }));
9336 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
9337 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
9338 function(method) {
9339 var _a2;
9340 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
9341 }));
9342 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
9343 untaintedBasePrototype$1[key] = defaultObj.prototype;
9344 return defaultObj.prototype;
9345 }
9346 try {
9347 var iframeEl = document.createElement("iframe");
9348 document.body.appendChild(iframeEl);
9349 var win = iframeEl.contentWindow;
9350 if (!win) return defaultObj.prototype;
9351 var untaintedObject = win[key].prototype;
9352 document.body.removeChild(iframeEl);
9353 if (!untaintedObject) return defaultPrototype;
9354 return untaintedBasePrototype$1[key] = untaintedObject;
9355 } catch (e) {
9356 return defaultPrototype;
9357 }
9358 }
9359 var untaintedAccessorCache$1 = {};
9360 function getUntaintedAccessor$1(key, instance, accessor) {
9361 var _a2;
9362 var cacheKey = key + "." + String(accessor);
9363 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
9364 var untaintedPrototype = getUntaintedPrototype$1(key);
9365 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
9366 if (!untaintedAccessor) return instance[accessor];
9367 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
9368 return untaintedAccessor.call(instance);
9369 }
9370 var untaintedMethodCache$1 = {};
9371 function getUntaintedMethod$1(key, instance, method) {
9372 var cacheKey = key + "." + String(method);
9373 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
9374 var untaintedPrototype = getUntaintedPrototype$1(key);
9375 var untaintedMethod = untaintedPrototype[method];
9376 if (typeof untaintedMethod !== "function") return instance[method];
9377 untaintedMethodCache$1[cacheKey] = untaintedMethod;
9378 return untaintedMethod.bind(instance);
9379 }
9380 function childNodes$1(n2) {
9381 return getUntaintedAccessor$1("Node", n2, "childNodes");
9382 }
9383 function parentNode$1(n2) {
9384 return getUntaintedAccessor$1("Node", n2, "parentNode");
9385 }
9386 function parentElement$1(n2) {
9387 return getUntaintedAccessor$1("Node", n2, "parentElement");
9388 }
9389 function textContent$1(n2) {
9390 return getUntaintedAccessor$1("Node", n2, "textContent");
9391 }
9392 function contains$1(n2, other) {
9393 return getUntaintedMethod$1("Node", n2, "contains")(other);
9394 }
9395 function getRootNode$1(n2) {
9396 return getUntaintedMethod$1("Node", n2, "getRootNode")();
9397 }
9398 function host$1(n2) {
9399 if (!n2 || !("host" in n2)) return null;
9400 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
9401 }
9402 function styleSheets$1(n2) {
9403 return n2.styleSheets;
9404 }
9405 function shadowRoot$1(n2) {
9406 if (!n2 || !("shadowRoot" in n2)) return null;
9407 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
9408 }
9409 function querySelector$1(n2, selectors) {
9410 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
9411 }
9412 function querySelectorAll$1(n2, selectors) {
9413 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
9414 }
9415 function mutationObserverCtor$1() {
9416 return getUntaintedPrototype$1("MutationObserver").constructor;
9417 }
9418 function patch$1(source, name, replacement) {
9419 try {
9420 if (!(name in source)) {
9421 return function() {};
9422 }
9423 var original = source[name];
9424 var wrapped = replacement(original);
9425 if (typeof wrapped === "function") {
9426 wrapped.prototype = wrapped.prototype || {};
9427 Object.defineProperties(wrapped, {
9428 __rrweb_original__: {
9429 enumerable: false,
9430 value: original
9431 }
9432 });
9433 }
9434 source[name] = wrapped;
9435 return function() {
9436 source[name] = original;
9437 };
9438 } catch (e) {
9439 return function() {};
9440 }
9441 }
9442 var index$1 = {
9443 childNodes: childNodes$1,
9444 parentNode: parentNode$1,
9445 parentElement: parentElement$1,
9446 textContent: textContent$1,
9447 contains: contains$1,
9448 getRootNode: getRootNode$1,
9449 host: host$1,
9450 styleSheets: styleSheets$1,
9451 shadowRoot: shadowRoot$1,
9452 querySelector: querySelector$1,
9453 querySelectorAll: querySelectorAll$1,
9454 mutationObserver: mutationObserverCtor$1,
9455 patch: patch$1
9456 };
9457 function isElement(n2) {
9458 return n2.nodeType === n2.ELEMENT_NODE;
9459 }
9460 function isShadowRoot(n2) {
9461 var hostEl = // anchor and textarea elements also have a `host` property
9462 // but only shadow roots have a `mode` property
9463 n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
9464 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
9465 }
9466 function isNativeShadowDom(shadowRoot2) {
9467 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
9468 }
9469 function fixBrowserCompatibilityIssuesInCSS(cssText) {
9470 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
9471 cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
9472 }
9473 return cssText;
9474 }
9475 function escapeImportStatement(rule2) {
9476 var cssText = rule2.cssText;
9477 if (cssText.split('"').length < 3) return cssText;
9478 var statement = [
9479 "@import",
9480 "url(" + JSON.stringify(rule2.href) + ")"
9481 ];
9482 if (rule2.layerName === "") {
9483 statement.push("layer");
9484 } else if (rule2.layerName) {
9485 statement.push("layer(" + rule2.layerName + ")");
9486 }
9487 if (rule2.supportsText) {
9488 statement.push("supports(" + rule2.supportsText + ")");
9489 }
9490 if (rule2.media.length) {
9491 statement.push(rule2.media.mediaText);
9492 }
9493 return statement.join(" ") + ";";
9494 }
9495 function stringifyStylesheet(s2) {
9496 try {
9497 var rules2 = s2.rules || s2.cssRules;
9498 if (!rules2) {
9499 return null;
9500 }
9501 var sheetHref = s2.href;
9502 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) {
9503 sheetHref = s2.ownerNode.ownerDocument.location.href;
9504 }
9505 var stringifiedRules = Array.from(rules2, function(rule2) {
9506 return stringifyRule(rule2, sheetHref);
9507 }).join("");
9508 return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);
9509 } catch (error) {
9510 return null;
9511 }
9512 }
9513 function stringifyRule(rule2, sheetHref) {
9514 if (isCSSImportRule(rule2)) {
9515 var importStringified;
9516 try {
9517 importStringified = // we can access the imported stylesheet rules directly
9518 stringifyStylesheet(rule2.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement
9519 escapeImportStatement(rule2);
9520 } catch (error) {
9521 importStringified = rule2.cssText;
9522 }
9523 if (rule2.styleSheet.href) {
9524 return absolutifyURLs(importStringified, rule2.styleSheet.href);
9525 }
9526 return importStringified;
9527 } else {
9528 var ruleStringified = rule2.cssText;
9529 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) {
9530 ruleStringified = fixSafariColons(ruleStringified);
9531 }
9532 if (sheetHref) {
9533 return absolutifyURLs(ruleStringified, sheetHref);
9534 }
9535 return ruleStringified;
9536 }
9537 }
9538 function fixSafariColons(cssStringified) {
9539 var regex = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
9540 return cssStringified.replace(regex, "$1\\$2");
9541 }
9542 function isCSSImportRule(rule2) {
9543 return "styleSheet" in rule2;
9544 }
9545 function isCSSStyleRule(rule2) {
9546 return "selectorText" in rule2;
9547 }
9548 var Mirror = /*#__PURE__*/ function() {
9549 function Mirror() {
9550 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
9551 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
9552 }
9553 var _proto = Mirror.prototype;
9554 _proto.getId = function getId(n2) {
9555 var _a2;
9556 if (!n2) return -1;
9557 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
9558 return id != null ? id : -1;
9559 };
9560 _proto.getNode = function getNode(id) {
9561 return this.idNodeMap.get(id) || null;
9562 };
9563 _proto.getIds = function getIds() {
9564 return Array.from(this.idNodeMap.keys());
9565 };
9566 _proto.getMeta = function getMeta(n2) {
9567 return this.nodeMetaMap.get(n2) || null;
9568 };
9569 // removes the node from idNodeMap
9570 // doesn't remove the node from nodeMetaMap
9571 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
9572 var _this = this;
9573 var id = this.getId(n2);
9574 this.idNodeMap.delete(id);
9575 if (n2.childNodes) {
9576 n2.childNodes.forEach(function(childNode) {
9577 return _this.removeNodeFromMap(childNode);
9578 });
9579 }
9580 };
9581 _proto.has = function has(id) {
9582 return this.idNodeMap.has(id);
9583 };
9584 _proto.hasNode = function hasNode(node2) {
9585 return this.nodeMetaMap.has(node2);
9586 };
9587 _proto.add = function add(n2, meta) {
9588 var id = meta.id;
9589 this.idNodeMap.set(id, n2);
9590 this.nodeMetaMap.set(n2, meta);
9591 };
9592 _proto.replace = function replace(id, n2) {
9593 var oldNode = this.getNode(id);
9594 if (oldNode) {
9595 var meta = this.nodeMetaMap.get(oldNode);
9596 if (meta) this.nodeMetaMap.set(n2, meta);
9597 }
9598 this.idNodeMap.set(id, n2);
9599 };
9600 _proto.reset = function reset() {
9601 this.idNodeMap = /* @__PURE__ */ new Map();
9602 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
9603 };
9604 return Mirror;
9605 }();
9606 function createMirror$2() {
9607 return new Mirror();
9608 }
9609 function maskInputValue(param) {
9610 var element = param.element, maskInputOptions = param.maskInputOptions, tagName = param.tagName, type = param.type, value = param.value, maskInputFn = param.maskInputFn;
9611 var text = value || "";
9612 var actualType = type && toLowerCase(type);
9613 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
9614 if (maskInputFn) {
9615 text = maskInputFn(text, element);
9616 } else {
9617 text = "*".repeat(text.length);
9618 }
9619 }
9620 return text;
9621 }
9622 function toLowerCase(str) {
9623 return str.toLowerCase();
9624 }
9625 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
9626 function is2DCanvasBlank(canvas) {
9627 var ctx = canvas.getContext("2d");
9628 if (!ctx) return true;
9629 var chunkSize = 50;
9630 for(var x2 = 0; x2 < canvas.width; x2 += chunkSize){
9631 for(var y = 0; y < canvas.height; y += chunkSize){
9632 var getImageData = ctx.getImageData;
9633 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
9634 var pixelBuffer = new Uint32Array(// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
9635 originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer);
9636 if (pixelBuffer.some(function(pixel) {
9637 return pixel !== 0;
9638 })) return false;
9639 }
9640 }
9641 return true;
9642 }
9643 function getInputType(element) {
9644 var type = element.type;
9645 return element.hasAttribute("data-rr-is-password") ? "password" : type ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
9646 toLowerCase(type) : null;
9647 }
9648 function extractFileExtension(path, baseURL) {
9649 var url;
9650 try {
9651 url = new URL(path, baseURL != null ? baseURL : window.location.href);
9652 } catch (err) {
9653 return null;
9654 }
9655 var regex = /\.([0-9a-z]+)(?:$)/i;
9656 var match = url.pathname.match(regex);
9657 var _ref;
9658 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
9659 }
9660 function extractOrigin(url) {
9661 var origin = "";
9662 if (url.indexOf("//") > -1) {
9663 origin = url.split("/").slice(0, 3).join("/");
9664 } else {
9665 origin = url.split("/")[0];
9666 }
9667 origin = origin.split("?")[0];
9668 return origin;
9669 }
9670 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
9671 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
9672 var URL_WWW_MATCH = /^www\..*/i;
9673 var DATA_URI = /^(data:)([^,]*),(.*)/i;
9674 function absolutifyURLs(cssText, href) {
9675 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
9676 var filePath = path1 || path2 || path3;
9677 var maybeQuote = quote1 || quote2 || "";
9678 if (!filePath) {
9679 return origin;
9680 }
9681 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
9682 return "url(" + maybeQuote + filePath + maybeQuote + ")";
9683 }
9684 if (DATA_URI.test(filePath)) {
9685 return "url(" + maybeQuote + filePath + maybeQuote + ")";
9686 }
9687 if (filePath[0] === "/") {
9688 return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
9689 }
9690 var stack = href.split("/");
9691 var parts = filePath.split("/");
9692 stack.pop();
9693 for(var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;){
9694 var part = _step.value;
9695 if (part === ".") {
9696 continue;
9697 } else if (part === "..") {
9698 stack.pop();
9699 } else {
9700 stack.push(part);
9701 }
9702 }
9703 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
9704 });
9705 }
9706 function normalizeCssString(cssText, _testNoPxNorm) {
9707 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
9708 if (_testNoPxNorm) {
9709 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
9710 } else {
9711 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
9712 }
9713 }
9714 function splitCssText(cssText, style, _testNoPxNorm) {
9715 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
9716 var childNodes2 = Array.from(style.childNodes);
9717 var splits = [];
9718 var iterCount = 0;
9719 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
9720 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
9721 var normFactor = cssTextNorm.length / cssText.length;
9722 for(var i2 = 1; i2 < childNodes2.length; i2++){
9723 if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
9724 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
9725 var jLimit = 100;
9726 var j = 3;
9727 for(; j < textContentNorm.length; j++){
9728 if (// keep consuming css identifiers (to get a decent chunk more quickly)
9729 textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section
9730 textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) {
9731 continue;
9732 }
9733 break;
9734 }
9735 for(; j < textContentNorm.length; j++){
9736 var startSubstring = textContentNorm.substring(0, j);
9737 var cssNormSplits = cssTextNorm.split(startSubstring);
9738 var splitNorm = -1;
9739 if (cssNormSplits.length === 2) {
9740 splitNorm = cssNormSplits[0].length;
9741 } else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") {
9742 splitNorm = cssTextNorm.indexOf(startSubstring, 1);
9743 } else if (cssNormSplits.length === 1) {
9744 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
9745 cssNormSplits = cssTextNorm.split(startSubstring);
9746 if (cssNormSplits.length <= 1) {
9747 splits.push(cssText);
9748 return splits;
9749 }
9750 j = jLimit + 1;
9751 } else if (j === textContentNorm.length - 1) {
9752 splitNorm = cssTextNorm.indexOf(startSubstring);
9753 }
9754 if (cssNormSplits.length >= 2 && j > jLimit) {
9755 var prevTextContent = childNodes2[i2 - 1].textContent;
9756 if (prevTextContent && typeof prevTextContent === "string") {
9757 var prevMinLength = normalizeCssString(prevTextContent).length;
9758 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
9759 }
9760 if (splitNorm === -1) {
9761 splitNorm = cssNormSplits[0].length;
9762 }
9763 }
9764 if (splitNorm !== -1) {
9765 var k = Math.floor(splitNorm / normFactor);
9766 for(; k > 0 && k < cssText.length;){
9767 iterCount += 1;
9768 if (iterCount > 50 * childNodes2.length) {
9769 splits.push(cssText);
9770 return splits;
9771 }
9772 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
9773 if (normPart.length === splitNorm) {
9774 splits.push(cssText.substring(0, k));
9775 cssText = cssText.substring(k);
9776 cssTextNorm = cssTextNorm.substring(splitNorm);
9777 break;
9778 } else if (normPart.length < splitNorm) {
9779 k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
9780 } else {
9781 k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
9782 }
9783 }
9784 break;
9785 }
9786 }
9787 }
9788 }
9789 }
9790 splits.push(cssText);
9791 return splits;
9792 }
9793 function markCssSplits(cssText, style) {
9794 return splitCssText(cssText, style).join("/* rr_split */");
9795 }
9796 var _id = 1;
9797 var tagNameRegex = new RegExp("[^a-z0-9-_:]");
9798 var IGNORED_NODE = -2;
9799 function genId() {
9800 return _id++;
9801 }
9802 function getValidTagName$1(element) {
9803 if (_instanceof(element, HTMLFormElement)) {
9804 return "form";
9805 }
9806 var processedTagName = toLowerCase(element.tagName);
9807 if (tagNameRegex.test(processedTagName)) {
9808 return "div";
9809 }
9810 return processedTagName;
9811 }
9812 var canvasService;
9813 var canvasCtx;
9814 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
9815 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
9816 function getAbsoluteSrcsetString(doc, attributeValue) {
9817 if (attributeValue.trim() === "") {
9818 return attributeValue;
9819 }
9820 var pos = 0;
9821 function collectCharacters(regEx) {
9822 var chars2;
9823 var match = regEx.exec(attributeValue.substring(pos));
9824 if (match) {
9825 chars2 = match[0];
9826 pos += chars2.length;
9827 return chars2;
9828 }
9829 return "";
9830 }
9831 var output = [];
9832 while(true){
9833 collectCharacters(SRCSET_COMMAS_OR_SPACES);
9834 if (pos >= attributeValue.length) {
9835 break;
9836 }
9837 var url = collectCharacters(SRCSET_NOT_SPACES);
9838 if (url.slice(-1) === ",") {
9839 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
9840 output.push(url);
9841 } else {
9842 var descriptorsStr = "";
9843 url = absoluteToDoc(doc, url);
9844 var inParens = false;
9845 while(true){
9846 var c2 = attributeValue.charAt(pos);
9847 if (c2 === "") {
9848 output.push((url + descriptorsStr).trim());
9849 break;
9850 } else if (!inParens) {
9851 if (c2 === ",") {
9852 pos += 1;
9853 output.push((url + descriptorsStr).trim());
9854 break;
9855 } else if (c2 === "(") {
9856 inParens = true;
9857 }
9858 } else {
9859 if (c2 === ")") {
9860 inParens = false;
9861 }
9862 }
9863 descriptorsStr += c2;
9864 pos += 1;
9865 }
9866 }
9867 }
9868 return output.join(", ");
9869 }
9870 var cachedDocument = /* @__PURE__ */ new WeakMap();
9871 function absoluteToDoc(doc, attributeValue) {
9872 if (!attributeValue || attributeValue.trim() === "") {
9873 return attributeValue;
9874 }
9875 return getHref(doc, attributeValue);
9876 }
9877 function isSVGElement(el) {
9878 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
9879 }
9880 function getHref(doc, customHref) {
9881 var a2 = cachedDocument.get(doc);
9882 if (!a2) {
9883 a2 = doc.createElement("a");
9884 cachedDocument.set(doc, a2);
9885 }
9886 if (!customHref) {
9887 customHref = "";
9888 } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
9889 return customHref;
9890 }
9891 a2.setAttribute("href", customHref);
9892 return a2.href;
9893 }
9894 function transformAttribute(doc, tagName, name, value) {
9895 if (!value) {
9896 return value;
9897 }
9898 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
9899 return absoluteToDoc(doc, value);
9900 } else if (name === "xlink:href" && value[0] !== "#") {
9901 return absoluteToDoc(doc, value);
9902 } else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
9903 return absoluteToDoc(doc, value);
9904 } else if (name === "srcset") {
9905 return getAbsoluteSrcsetString(doc, value);
9906 } else if (name === "style") {
9907 return absolutifyURLs(value, getHref(doc));
9908 } else if (tagName === "object" && name === "data") {
9909 return absoluteToDoc(doc, value);
9910 }
9911 return value;
9912 }
9913 function ignoreAttribute(tagName, name, _value) {
9914 return (tagName === "video" || tagName === "audio") && name === "autoplay";
9915 }
9916 function _isBlockedElement(element, blockClass, blockSelector) {
9917 try {
9918 if (typeof blockClass === "string") {
9919 if (element.classList.contains(blockClass)) {
9920 return true;
9921 }
9922 } else {
9923 for(var eIndex = element.classList.length; eIndex--;){
9924 var className = element.classList[eIndex];
9925 if (blockClass.test(className)) {
9926 return true;
9927 }
9928 }
9929 }
9930 if (blockSelector) {
9931 return element.matches(blockSelector);
9932 }
9933 } catch (e2) {}
9934 return false;
9935 }
9936 function classMatchesRegex(node2, regex, checkAncestors) {
9937 if (!node2) return false;
9938 if (node2.nodeType !== node2.ELEMENT_NODE) {
9939 if (!checkAncestors) return false;
9940 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
9941 }
9942 for(var eIndex = node2.classList.length; eIndex--;){
9943 var className = node2.classList[eIndex];
9944 if (regex.test(className)) {
9945 return true;
9946 }
9947 }
9948 if (!checkAncestors) return false;
9949 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
9950 }
9951 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
9952 var el;
9953 if (isElement(node2)) {
9954 el = node2;
9955 if (!index$1.childNodes(el).length) {
9956 return false;
9957 }
9958 } else if (index$1.parentElement(node2) === null) {
9959 return false;
9960 } else {
9961 el = index$1.parentElement(node2);
9962 }
9963 try {
9964 if (typeof maskTextClass === "string") {
9965 if (checkAncestors) {
9966 if (el.closest("." + maskTextClass)) return true;
9967 } else {
9968 if (el.classList.contains(maskTextClass)) return true;
9969 }
9970 } else {
9971 if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
9972 }
9973 if (maskTextSelector) {
9974 if (checkAncestors) {
9975 if (el.closest(maskTextSelector)) return true;
9976 } else {
9977 if (el.matches(maskTextSelector)) return true;
9978 }
9979 }
9980 } catch (e2) {}
9981 return false;
9982 }
9983 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
9984 var win = iframeEl.contentWindow;
9985 if (!win) {
9986 return;
9987 }
9988 var fired = false;
9989 var readyState;
9990 try {
9991 readyState = win.document.readyState;
9992 } catch (error) {
9993 return;
9994 }
9995 if (readyState !== "complete") {
9996 var timer = setTimeout(function() {
9997 if (!fired) {
9998 listener();
9999 fired = true;
10000 }
10001 }, iframeLoadTimeout);
10002 iframeEl.addEventListener("load", function() {
10003 clearTimeout(timer);
10004 fired = true;
10005 listener();
10006 });
10007 return;
10008 }
10009 var blankUrl = "about:blank";
10010 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
10011 setTimeout(listener, 0);
10012 return iframeEl.addEventListener("load", listener);
10013 }
10014 iframeEl.addEventListener("load", listener);
10015 }
10016 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
10017 var fired = false;
10018 var styleSheetLoaded;
10019 try {
10020 styleSheetLoaded = link.sheet;
10021 } catch (error) {
10022 return;
10023 }
10024 if (styleSheetLoaded) return;
10025 var timer = setTimeout(function() {
10026 if (!fired) {
10027 listener();
10028 fired = true;
10029 }
10030 }, styleSheetLoadTimeout);
10031 link.addEventListener("load", function() {
10032 clearTimeout(timer);
10033 fired = true;
10034 listener();
10035 });
10036 }
10037 function serializeNode(n2, options) {
10038 var doc = options.doc, mirror2 = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, needsMask = options.needsMask, inlineStylesheet = options.inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, _options_cssCaptured = options.cssCaptured, cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
10039 var rootId = getRootId(doc, mirror2);
10040 switch(n2.nodeType){
10041 case n2.DOCUMENT_NODE:
10042 if (n2.compatMode !== "CSS1Compat") {
10043 return {
10044 type: NodeType$3.Document,
10045 childNodes: [],
10046 compatMode: n2.compatMode
10047 };
10048 } else {
10049 return {
10050 type: NodeType$3.Document,
10051 childNodes: []
10052 };
10053 }
10054 case n2.DOCUMENT_TYPE_NODE:
10055 return {
10056 type: NodeType$3.DocumentType,
10057 name: n2.name,
10058 publicId: n2.publicId,
10059 systemId: n2.systemId,
10060 rootId: rootId
10061 };
10062 case n2.ELEMENT_NODE:
10063 return serializeElementNode(n2, {
10064 doc: doc,
10065 blockClass: blockClass,
10066 blockSelector: blockSelector,
10067 inlineStylesheet: inlineStylesheet,
10068 maskInputOptions: maskInputOptions,
10069 maskInputFn: maskInputFn,
10070 dataURLOptions: dataURLOptions,
10071 inlineImages: inlineImages,
10072 recordCanvas: recordCanvas,
10073 keepIframeSrcFn: keepIframeSrcFn,
10074 newlyAddedElement: newlyAddedElement,
10075 rootId: rootId
10076 });
10077 case n2.TEXT_NODE:
10078 return serializeTextNode(n2, {
10079 doc: doc,
10080 needsMask: needsMask,
10081 maskTextFn: maskTextFn,
10082 rootId: rootId,
10083 cssCaptured: cssCaptured
10084 });
10085 case n2.CDATA_SECTION_NODE:
10086 return {
10087 type: NodeType$3.CDATA,
10088 textContent: "",
10089 rootId: rootId
10090 };
10091 case n2.COMMENT_NODE:
10092 return {
10093 type: NodeType$3.Comment,
10094 textContent: index$1.textContent(n2) || "",
10095 rootId: rootId
10096 };
10097 default:
10098 return false;
10099 }
10100 }
10101 function getRootId(doc, mirror2) {
10102 if (!mirror2.hasNode(doc)) return void 0;
10103 var docId = mirror2.getId(doc);
10104 return docId === 1 ? void 0 : docId;
10105 }
10106 function serializeTextNode(n2, options) {
10107 var needsMask = options.needsMask, maskTextFn = options.maskTextFn, rootId = options.rootId, cssCaptured = options.cssCaptured;
10108 var parent = index$1.parentNode(n2);
10109 var parentTagName = parent && parent.tagName;
10110 var textContent2 = "";
10111 var isStyle = parentTagName === "STYLE" ? true : void 0;
10112 var isScript = parentTagName === "SCRIPT" ? true : void 0;
10113 if (isScript) {
10114 textContent2 = "SCRIPT_PLACEHOLDER";
10115 } else if (!cssCaptured) {
10116 textContent2 = index$1.textContent(n2);
10117 if (isStyle && textContent2) {
10118 textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
10119 }
10120 }
10121 if (!isStyle && !isScript && textContent2 && needsMask) {
10122 textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
10123 }
10124 return {
10125 type: NodeType$3.Text,
10126 textContent: textContent2 || "",
10127 rootId: rootId
10128 };
10129 }
10130 function serializeElementNode(n2, options) {
10131 var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskInputFn = options.maskInputFn, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, rootId = options.rootId;
10132 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
10133 var tagName = getValidTagName$1(n2);
10134 var attributes = {};
10135 var len = n2.attributes.length;
10136 for(var i2 = 0; i2 < len; i2++){
10137 var attr = n2.attributes[i2];
10138 if (!ignoreAttribute(tagName, attr.name, attr.value)) {
10139 attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
10140 }
10141 }
10142 if (tagName === "link" && inlineStylesheet) {
10143 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
10144 return s2.href === n2.href;
10145 });
10146 var cssText = null;
10147 if (stylesheet) {
10148 cssText = stringifyStylesheet(stylesheet);
10149 }
10150 if (cssText) {
10151 delete attributes.rel;
10152 delete attributes.href;
10153 attributes._cssText = cssText;
10154 }
10155 }
10156 if (tagName === "style" && n2.sheet) {
10157 var cssText1 = stringifyStylesheet(n2.sheet);
10158 if (cssText1) {
10159 if (n2.childNodes.length > 1) {
10160 cssText1 = markCssSplits(cssText1, n2);
10161 }
10162 attributes._cssText = cssText1;
10163 }
10164 }
10165 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
10166 var value = n2.value;
10167 var checked = n2.checked;
10168 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
10169 attributes.value = maskInputValue({
10170 element: n2,
10171 type: getInputType(n2),
10172 tagName: tagName,
10173 value: value,
10174 maskInputOptions: maskInputOptions,
10175 maskInputFn: maskInputFn
10176 });
10177 } else if (checked) {
10178 attributes.checked = checked;
10179 }
10180 }
10181 if (tagName === "option") {
10182 if (n2.selected && !maskInputOptions["select"]) {
10183 attributes.selected = true;
10184 } else {
10185 delete attributes.selected;
10186 }
10187 }
10188 if (tagName === "dialog" && n2.open) {
10189 attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
10190 }
10191 if (tagName === "canvas" && recordCanvas) {
10192 if (n2.__context === "2d") {
10193 if (!is2DCanvasBlank(n2)) {
10194 attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10195 }
10196 } else if (!("__context" in n2)) {
10197 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10198 var blankCanvas = doc.createElement("canvas");
10199 blankCanvas.width = n2.width;
10200 blankCanvas.height = n2.height;
10201 var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10202 if (canvasDataURL !== blankCanvasDataURL) {
10203 attributes.rr_dataURL = canvasDataURL;
10204 }
10205 }
10206 }
10207 if (tagName === "img" && inlineImages) {
10208 if (!canvasService) {
10209 canvasService = doc.createElement("canvas");
10210 canvasCtx = canvasService.getContext("2d");
10211 }
10212 var image = n2;
10213 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
10214 var priorCrossOrigin = image.crossOrigin;
10215 var recordInlineImage = function() {
10216 image.removeEventListener("load", recordInlineImage);
10217 try {
10218 canvasService.width = image.naturalWidth;
10219 canvasService.height = image.naturalHeight;
10220 canvasCtx.drawImage(image, 0, 0);
10221 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10222 } catch (err) {
10223 if (image.crossOrigin !== "anonymous") {
10224 image.crossOrigin = "anonymous";
10225 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
10226 else image.addEventListener("load", recordInlineImage);
10227 return;
10228 } else {
10229 console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
10230 }
10231 }
10232 if (image.crossOrigin === "anonymous") {
10233 priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
10234 }
10235 };
10236 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
10237 else image.addEventListener("load", recordInlineImage);
10238 }
10239 if (tagName === "audio" || tagName === "video") {
10240 var mediaAttributes = attributes;
10241 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
10242 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
10243 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
10244 mediaAttributes.rr_mediaMuted = n2.muted;
10245 mediaAttributes.rr_mediaLoop = n2.loop;
10246 mediaAttributes.rr_mediaVolume = n2.volume;
10247 }
10248 if (!newlyAddedElement) {
10249 if (n2.scrollLeft) {
10250 attributes.rr_scrollLeft = n2.scrollLeft;
10251 }
10252 if (n2.scrollTop) {
10253 attributes.rr_scrollTop = n2.scrollTop;
10254 }
10255 }
10256 if (needBlock) {
10257 var _n2_getBoundingClientRect = n2.getBoundingClientRect(), width = _n2_getBoundingClientRect.width, height = _n2_getBoundingClientRect.height;
10258 attributes = {
10259 class: attributes.class,
10260 rr_width: "" + width + "px",
10261 rr_height: "" + height + "px"
10262 };
10263 }
10264 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
10265 if (!n2.contentDocument) {
10266 attributes.rr_src = attributes.src;
10267 }
10268 delete attributes.src;
10269 }
10270 var isCustomElement;
10271 try {
10272 if (customElements.get(tagName)) isCustomElement = true;
10273 } catch (e2) {}
10274 return {
10275 type: NodeType$3.Element,
10276 tagName: tagName,
10277 attributes: attributes,
10278 childNodes: [],
10279 isSVG: isSVGElement(n2) || void 0,
10280 needBlock: needBlock,
10281 rootId: rootId,
10282 isCustom: isCustomElement
10283 };
10284 }
10285 function lowerIfExists(maybeAttr) {
10286 if (maybeAttr === void 0 || maybeAttr === null) {
10287 return "";
10288 } else {
10289 return maybeAttr.toLowerCase();
10290 }
10291 }
10292 function slimDOMExcluded(sn, slimDOMOptions) {
10293 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {
10294 return true;
10295 } else if (sn.type === NodeType$3.Element) {
10296 if (slimDOMOptions.script && // script tag
10297 (sn.tagName === "script" || // (module)preload link
10298 sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || // prefetch link
10299 sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) {
10300 return true;
10301 } else if (slimDOMOptions.headFavicon && (sn.tagName === "link" && sn.attributes.rel === "shortcut icon" || sn.tagName === "meta" && (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) || lowerIfExists(sn.attributes.name) === "application-name" || lowerIfExists(sn.attributes.rel) === "icon" || lowerIfExists(sn.attributes.rel) === "apple-touch-icon" || lowerIfExists(sn.attributes.rel) === "shortcut icon"))) {
10302 return true;
10303 } else if (sn.tagName === "meta") {
10304 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
10305 return true;
10306 } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)
10307 lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
10308 return true;
10309 } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
10310 return true;
10311 } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
10312 return true;
10313 } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === "author" || lowerIfExists(sn.attributes.name) === "generator" || lowerIfExists(sn.attributes.name) === "framework" || lowerIfExists(sn.attributes.name) === "publisher" || lowerIfExists(sn.attributes.name) === "progid" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {
10314 return true;
10315 } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === "google-site-verification" || lowerIfExists(sn.attributes.name) === "yandex-verification" || lowerIfExists(sn.attributes.name) === "csrf-token" || lowerIfExists(sn.attributes.name) === "p:domain_verify" || lowerIfExists(sn.attributes.name) === "verify-v1" || lowerIfExists(sn.attributes.name) === "verification" || lowerIfExists(sn.attributes.name) === "shopify-checkout-api-token")) {
10316 return true;
10317 }
10318 }
10319 }
10320 return false;
10321 }
10322 function serializeNodeWithId(n2, options) {
10323 var doc = options.doc, mirror2 = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _options_skipChild = options.skipChild, skipChild = _options_skipChild === void 0 ? false : _options_skipChild, _options_inlineStylesheet = options.inlineStylesheet, inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, _options_inlineImages = options.inlineImages, inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages, _options_recordCanvas = options.recordCanvas, recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _options_iframeLoadTimeout = options.iframeLoadTimeout, iframeLoadTimeout = _options_iframeLoadTimeout === void 0 ? 5e3 : _options_iframeLoadTimeout, onStylesheetLoad = options.onStylesheetLoad, _options_stylesheetLoadTimeout = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _options_stylesheetLoadTimeout === void 0 ? 5e3 : _options_stylesheetLoadTimeout, _options_keepIframeSrcFn = options.keepIframeSrcFn, keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
10324 return false;
10325 } : _options_keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, _options_cssCaptured = options.cssCaptured, cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
10326 var needsMask = options.needsMask;
10327 var _options_preserveWhiteSpace = options.preserveWhiteSpace, preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
10328 if (!needsMask) {
10329 var checkAncestors = needsMask === void 0;
10330 needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, checkAncestors);
10331 }
10332 var _serializedNode = serializeNode(n2, {
10333 doc: doc,
10334 mirror: mirror2,
10335 blockClass: blockClass,
10336 blockSelector: blockSelector,
10337 needsMask: needsMask,
10338 inlineStylesheet: inlineStylesheet,
10339 maskInputOptions: maskInputOptions,
10340 maskTextFn: maskTextFn,
10341 maskInputFn: maskInputFn,
10342 dataURLOptions: dataURLOptions,
10343 inlineImages: inlineImages,
10344 recordCanvas: recordCanvas,
10345 keepIframeSrcFn: keepIframeSrcFn,
10346 newlyAddedElement: newlyAddedElement,
10347 cssCaptured: cssCaptured
10348 });
10349 if (!_serializedNode) {
10350 console.warn(n2, "not serialized");
10351 return null;
10352 }
10353 var id;
10354 if (mirror2.hasNode(n2)) {
10355 id = mirror2.getId(n2);
10356 } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
10357 id = IGNORED_NODE;
10358 } else {
10359 id = genId();
10360 }
10361 var serializedNode = Object.assign(_serializedNode, {
10362 id: id
10363 });
10364 mirror2.add(n2, serializedNode);
10365 if (id === IGNORED_NODE) {
10366 return null;
10367 }
10368 if (onSerialize) {
10369 onSerialize(n2);
10370 }
10371 var recordChild = !skipChild;
10372 if (serializedNode.type === NodeType$3.Element) {
10373 recordChild = recordChild && !serializedNode.needBlock;
10374 delete serializedNode.needBlock;
10375 var shadowRootEl = index$1.shadowRoot(n2);
10376 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
10377 }
10378 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
10379 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") {
10380 preserveWhiteSpace = false;
10381 }
10382 var bypassOptions = {
10383 doc: doc,
10384 mirror: mirror2,
10385 blockClass: blockClass,
10386 blockSelector: blockSelector,
10387 needsMask: needsMask,
10388 maskTextClass: maskTextClass,
10389 maskTextSelector: maskTextSelector,
10390 skipChild: skipChild,
10391 inlineStylesheet: inlineStylesheet,
10392 maskInputOptions: maskInputOptions,
10393 maskTextFn: maskTextFn,
10394 maskInputFn: maskInputFn,
10395 slimDOMOptions: slimDOMOptions,
10396 dataURLOptions: dataURLOptions,
10397 inlineImages: inlineImages,
10398 recordCanvas: recordCanvas,
10399 preserveWhiteSpace: preserveWhiteSpace,
10400 onSerialize: onSerialize,
10401 onIframeLoad: onIframeLoad,
10402 iframeLoadTimeout: iframeLoadTimeout,
10403 onStylesheetLoad: onStylesheetLoad,
10404 stylesheetLoadTimeout: stylesheetLoadTimeout,
10405 keepIframeSrcFn: keepIframeSrcFn,
10406 cssCaptured: false
10407 };
10408 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0) ;
10409 else {
10410 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") {
10411 bypassOptions.cssCaptured = true;
10412 }
10413 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;){
10414 var childN = _step.value;
10415 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
10416 if (serializedChildNode) {
10417 serializedNode.childNodes.push(serializedChildNode);
10418 }
10419 }
10420 }
10421 var shadowRootEl1 = null;
10422 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) {
10423 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;){
10424 var childN1 = _step1.value;
10425 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
10426 if (serializedChildNode1) {
10427 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
10428 serializedNode.childNodes.push(serializedChildNode1);
10429 }
10430 }
10431 }
10432 }
10433 var parent = index$1.parentNode(n2);
10434 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {
10435 serializedNode.isShadow = true;
10436 }
10437 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") {
10438 onceIframeLoaded(n2, function() {
10439 var iframeDoc = n2.contentDocument;
10440 if (iframeDoc && onIframeLoad) {
10441 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
10442 doc: iframeDoc,
10443 mirror: mirror2,
10444 blockClass: blockClass,
10445 blockSelector: blockSelector,
10446 needsMask: needsMask,
10447 maskTextClass: maskTextClass,
10448 maskTextSelector: maskTextSelector,
10449 skipChild: false,
10450 inlineStylesheet: inlineStylesheet,
10451 maskInputOptions: maskInputOptions,
10452 maskTextFn: maskTextFn,
10453 maskInputFn: maskInputFn,
10454 slimDOMOptions: slimDOMOptions,
10455 dataURLOptions: dataURLOptions,
10456 inlineImages: inlineImages,
10457 recordCanvas: recordCanvas,
10458 preserveWhiteSpace: preserveWhiteSpace,
10459 onSerialize: onSerialize,
10460 onIframeLoad: onIframeLoad,
10461 iframeLoadTimeout: iframeLoadTimeout,
10462 onStylesheetLoad: onStylesheetLoad,
10463 stylesheetLoadTimeout: stylesheetLoadTimeout,
10464 keepIframeSrcFn: keepIframeSrcFn
10465 });
10466 if (serializedIframeNode) {
10467 onIframeLoad(n2, serializedIframeNode);
10468 }
10469 }
10470 }, iframeLoadTimeout);
10471 }
10472 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "link" && typeof serializedNode.attributes.rel === "string" && (serializedNode.attributes.rel === "stylesheet" || serializedNode.attributes.rel === "preload" && typeof serializedNode.attributes.href === "string" && extractFileExtension(serializedNode.attributes.href) === "css")) {
10473 onceStylesheetLoaded(n2, function() {
10474 if (onStylesheetLoad) {
10475 var serializedLinkNode = serializeNodeWithId(n2, {
10476 doc: doc,
10477 mirror: mirror2,
10478 blockClass: blockClass,
10479 blockSelector: blockSelector,
10480 needsMask: needsMask,
10481 maskTextClass: maskTextClass,
10482 maskTextSelector: maskTextSelector,
10483 skipChild: false,
10484 inlineStylesheet: inlineStylesheet,
10485 maskInputOptions: maskInputOptions,
10486 maskTextFn: maskTextFn,
10487 maskInputFn: maskInputFn,
10488 slimDOMOptions: slimDOMOptions,
10489 dataURLOptions: dataURLOptions,
10490 inlineImages: inlineImages,
10491 recordCanvas: recordCanvas,
10492 preserveWhiteSpace: preserveWhiteSpace,
10493 onSerialize: onSerialize,
10494 onIframeLoad: onIframeLoad,
10495 iframeLoadTimeout: iframeLoadTimeout,
10496 onStylesheetLoad: onStylesheetLoad,
10497 stylesheetLoadTimeout: stylesheetLoadTimeout,
10498 keepIframeSrcFn: keepIframeSrcFn
10499 });
10500 if (serializedLinkNode) {
10501 onStylesheetLoad(n2, serializedLinkNode);
10502 }
10503 }
10504 }, stylesheetLoadTimeout);
10505 }
10506 return serializedNode;
10507 }
10508 function snapshot(n2, options) {
10509 var _ref = options || {}, tmp = _ref.mirror, mirror2 = tmp === void 0 ? new Mirror() : tmp, _ref_blockClass = _ref.blockClass, blockClass = _ref_blockClass === void 0 ? "rr-block" : _ref_blockClass, _ref_blockSelector = _ref.blockSelector, blockSelector = _ref_blockSelector === void 0 ? null : _ref_blockSelector, _ref_maskTextClass = _ref.maskTextClass, maskTextClass = _ref_maskTextClass === void 0 ? "rr-mask" : _ref_maskTextClass, _ref_maskTextSelector = _ref.maskTextSelector, maskTextSelector = _ref_maskTextSelector === void 0 ? null : _ref_maskTextSelector, _ref_inlineStylesheet = _ref.inlineStylesheet, inlineStylesheet = _ref_inlineStylesheet === void 0 ? true : _ref_inlineStylesheet, _ref_inlineImages = _ref.inlineImages, inlineImages = _ref_inlineImages === void 0 ? false : _ref_inlineImages, _ref_recordCanvas = _ref.recordCanvas, recordCanvas = _ref_recordCanvas === void 0 ? false : _ref_recordCanvas, _ref_maskAllInputs = _ref.maskAllInputs, maskAllInputs = _ref_maskAllInputs === void 0 ? false : _ref_maskAllInputs, maskTextFn = _ref.maskTextFn, maskInputFn = _ref.maskInputFn, _ref_slimDOM = _ref.slimDOM, slimDOM = _ref_slimDOM === void 0 ? false : _ref_slimDOM, dataURLOptions = _ref.dataURLOptions, preserveWhiteSpace = _ref.preserveWhiteSpace, onSerialize = _ref.onSerialize, onIframeLoad = _ref.onIframeLoad, iframeLoadTimeout = _ref.iframeLoadTimeout, onStylesheetLoad = _ref.onStylesheetLoad, stylesheetLoadTimeout = _ref.stylesheetLoadTimeout, _ref_keepIframeSrcFn = _ref.keepIframeSrcFn, keepIframeSrcFn = _ref_keepIframeSrcFn === void 0 ? function() {
10510 return false;
10511 } : _ref_keepIframeSrcFn;
10512 var maskInputOptions = maskAllInputs === true ? {
10513 color: true,
10514 date: true,
10515 "datetime-local": true,
10516 email: true,
10517 month: true,
10518 number: true,
10519 range: true,
10520 search: true,
10521 tel: true,
10522 text: true,
10523 time: true,
10524 url: true,
10525 week: true,
10526 textarea: true,
10527 select: true,
10528 password: true,
10529 hidden: true
10530 } : maskAllInputs === false ? {
10531 password: true
10532 } : maskAllInputs;
10533 var slimDOMOptions = slimDOM === true || slimDOM === "all" ? // if true: set of sensible options that should not throw away any information
10534 {
10535 script: true,
10536 comment: true,
10537 headFavicon: true,
10538 headWhitespace: true,
10539 headMetaDescKeywords: slimDOM === "all",
10540 // destructive
10541 headMetaSocial: true,
10542 headMetaRobots: true,
10543 headMetaHttpEquiv: true,
10544 headMetaAuthorship: true,
10545 headMetaVerification: true
10546 } : slimDOM === false ? {} : slimDOM;
10547 return serializeNodeWithId(n2, {
10548 doc: n2,
10549 mirror: mirror2,
10550 blockClass: blockClass,
10551 blockSelector: blockSelector,
10552 maskTextClass: maskTextClass,
10553 maskTextSelector: maskTextSelector,
10554 skipChild: false,
10555 inlineStylesheet: inlineStylesheet,
10556 maskInputOptions: maskInputOptions,
10557 maskTextFn: maskTextFn,
10558 maskInputFn: maskInputFn,
10559 slimDOMOptions: slimDOMOptions,
10560 dataURLOptions: dataURLOptions,
10561 inlineImages: inlineImages,
10562 recordCanvas: recordCanvas,
10563 preserveWhiteSpace: preserveWhiteSpace,
10564 onSerialize: onSerialize,
10565 onIframeLoad: onIframeLoad,
10566 iframeLoadTimeout: iframeLoadTimeout,
10567 onStylesheetLoad: onStylesheetLoad,
10568 stylesheetLoadTimeout: stylesheetLoadTimeout,
10569 keepIframeSrcFn: keepIframeSrcFn,
10570 newlyAddedElement: false
10571 });
10572 }
10573 function getDefaultExportFromCjs$1(x2) {
10574 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
10575 }
10576 function getAugmentedNamespace$1(n2) {
10577 if (n2.__esModule) return n2;
10578 var f2 = n2.default;
10579 if (typeof f2 == "function") {
10580 var a2 = function a22() {
10581 if (_instanceof(this, a22)) {
10582 return Reflect.construct(f2, arguments, this.constructor);
10583 }
10584 return f2.apply(this, arguments);
10585 };
10586 a2.prototype = f2.prototype;
10587 } else a2 = {};
10588 Object.defineProperty(a2, "__esModule", {
10589 value: true
10590 });
10591 Object.keys(n2).forEach(function(k) {
10592 var d = Object.getOwnPropertyDescriptor(n2, k);
10593 Object.defineProperty(a2, k, d.get ? d : {
10594 enumerable: true,
10595 get: function get() {
10596 return n2[k];
10597 }
10598 });
10599 });
10600 return a2;
10601 }
10602 var picocolors_browser$1 = {
10603 exports: {}
10604 };
10605 var x$1 = String;
10606 var create$1 = function create$1() {
10607 return {
10608 isColorSupported: false,
10609 reset: x$1,
10610 bold: x$1,
10611 dim: x$1,
10612 italic: x$1,
10613 underline: x$1,
10614 inverse: x$1,
10615 hidden: x$1,
10616 strikethrough: x$1,
10617 black: x$1,
10618 red: x$1,
10619 green: x$1,
10620 yellow: x$1,
10621 blue: x$1,
10622 magenta: x$1,
10623 cyan: x$1,
10624 white: x$1,
10625 gray: x$1,
10626 bgBlack: x$1,
10627 bgRed: x$1,
10628 bgGreen: x$1,
10629 bgYellow: x$1,
10630 bgBlue: x$1,
10631 bgMagenta: x$1,
10632 bgCyan: x$1,
10633 bgWhite: x$1
10634 };
10635 };
10636 picocolors_browser$1.exports = create$1();
10637 picocolors_browser$1.exports.createColors = create$1;
10638 var picocolors_browserExports$1 = picocolors_browser$1.exports;
10639 var __viteBrowserExternal$2 = {};
10640 var __viteBrowserExternal$1$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
10641 __proto__: null,
10642 default: __viteBrowserExternal$2
10643 }, Symbol.toStringTag, {
10644 value: "Module"
10645 }));
10646 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal$1$1);
10647 var pico$1 = picocolors_browserExports$1;
10648 var terminalHighlight$1$1 = require$$2$1;
10649 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
10650 _inherits(CssSyntaxError, Error1);
10651 function CssSyntaxError(message, line, column, source, file, plugin22) {
10652 var _this;
10653 _this = Error1.call(this, message) || this;
10654 _this.name = "CssSyntaxError";
10655 _this.reason = message;
10656 if (file) {
10657 _this.file = file;
10658 }
10659 if (source) {
10660 _this.source = source;
10661 }
10662 if (plugin22) {
10663 _this.plugin = plugin22;
10664 }
10665 if (typeof line !== "undefined" && typeof column !== "undefined") {
10666 if (typeof line === "number") {
10667 _this.line = line;
10668 _this.column = column;
10669 } else {
10670 _this.line = line.line;
10671 _this.column = line.column;
10672 _this.endLine = column.line;
10673 _this.endColumn = column.column;
10674 }
10675 }
10676 _this.setMessage();
10677 if (Error.captureStackTrace) {
10678 Error.captureStackTrace(_this, CssSyntaxError);
10679 }
10680 return _this;
10681 }
10682 var _proto = CssSyntaxError.prototype;
10683 _proto.setMessage = function setMessage() {
10684 this.message = this.plugin ? this.plugin + ": " : "";
10685 this.message += this.file ? this.file : "<css input>";
10686 if (typeof this.line !== "undefined") {
10687 this.message += ":" + this.line + ":" + this.column;
10688 }
10689 this.message += ": " + this.reason;
10690 };
10691 _proto.showSourceCode = function showSourceCode(color) {
10692 var _this = this;
10693 if (!this.source) return "";
10694 var css = this.source;
10695 if (color == null) color = pico$1.isColorSupported;
10696 if (terminalHighlight$1$1) {
10697 if (color) css = terminalHighlight$1$1(css);
10698 }
10699 var lines = css.split(/\r?\n/);
10700 var start = Math.max(this.line - 3, 0);
10701 var end = Math.min(this.line + 2, lines.length);
10702 var maxWidth = String(end).length;
10703 var mark, aside;
10704 if (color) {
10705 var _pico$1_createColors = pico$1.createColors(true), bold = _pico$1_createColors.bold, gray = _pico$1_createColors.gray, red = _pico$1_createColors.red;
10706 mark = function(text) {
10707 return bold(red(text));
10708 };
10709 aside = function(text) {
10710 return gray(text);
10711 };
10712 } else {
10713 mark = aside = function(str) {
10714 return str;
10715 };
10716 }
10717 return lines.slice(start, end).map(function(line, index2) {
10718 var number = start + 1 + index2;
10719 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
10720 if (number === _this.line) {
10721 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
10722 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
10723 }
10724 return " " + aside(gutter) + line;
10725 }).join("\n");
10726 };
10727 _proto.toString = function toString() {
10728 var code = this.showSourceCode();
10729 if (code) {
10730 code = "\n\n" + code + "\n";
10731 }
10732 return this.name + ": " + this.message + code;
10733 };
10734 return CssSyntaxError;
10735 }(_wrap_native_super(Error));
10736 var cssSyntaxError$1 = CssSyntaxError$3$1;
10737 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
10738 var symbols$1 = {};
10739 symbols$1.isClean = Symbol("isClean");
10740 symbols$1.my = Symbol("my");
10741 var DEFAULT_RAW$1 = {
10742 after: "\n",
10743 beforeClose: "\n",
10744 beforeComment: "\n",
10745 beforeDecl: "\n",
10746 beforeOpen: " ",
10747 beforeRule: "\n",
10748 colon: ": ",
10749 commentLeft: " ",
10750 commentRight: " ",
10751 emptyBody: "",
10752 indent: " ",
10753 semicolon: false
10754 };
10755 function capitalize$1(str) {
10756 return str[0].toUpperCase() + str.slice(1);
10757 }
10758 var Stringifier$2$1 = /*#__PURE__*/ function() {
10759 function Stringifier(builder) {
10760 this.builder = builder;
10761 }
10762 var _proto = Stringifier.prototype;
10763 _proto.atrule = function atrule(node2, semicolon) {
10764 var name = "@" + node2.name;
10765 var params = node2.params ? this.rawValue(node2, "params") : "";
10766 if (typeof node2.raws.afterName !== "undefined") {
10767 name += node2.raws.afterName;
10768 } else if (params) {
10769 name += " ";
10770 }
10771 if (node2.nodes) {
10772 this.block(node2, name + params);
10773 } else {
10774 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
10775 this.builder(name + params + end, node2);
10776 }
10777 };
10778 _proto.beforeAfter = function beforeAfter(node2, detect) {
10779 var value;
10780 if (node2.type === "decl") {
10781 value = this.raw(node2, null, "beforeDecl");
10782 } else if (node2.type === "comment") {
10783 value = this.raw(node2, null, "beforeComment");
10784 } else if (detect === "before") {
10785 value = this.raw(node2, null, "beforeRule");
10786 } else {
10787 value = this.raw(node2, null, "beforeClose");
10788 }
10789 var buf = node2.parent;
10790 var depth = 0;
10791 while(buf && buf.type !== "root"){
10792 depth += 1;
10793 buf = buf.parent;
10794 }
10795 if (value.includes("\n")) {
10796 var indent = this.raw(node2, null, "indent");
10797 if (indent.length) {
10798 for(var step = 0; step < depth; step++)value += indent;
10799 }
10800 }
10801 return value;
10802 };
10803 _proto.block = function block(node2, start) {
10804 var between = this.raw(node2, "between", "beforeOpen");
10805 this.builder(start + between + "{", node2, "start");
10806 var after;
10807 if (node2.nodes && node2.nodes.length) {
10808 this.body(node2);
10809 after = this.raw(node2, "after");
10810 } else {
10811 after = this.raw(node2, "after", "emptyBody");
10812 }
10813 if (after) this.builder(after);
10814 this.builder("}", node2, "end");
10815 };
10816 _proto.body = function body(node2) {
10817 var last = node2.nodes.length - 1;
10818 while(last > 0){
10819 if (node2.nodes[last].type !== "comment") break;
10820 last -= 1;
10821 }
10822 var semicolon = this.raw(node2, "semicolon");
10823 for(var i2 = 0; i2 < node2.nodes.length; i2++){
10824 var child = node2.nodes[i2];
10825 var before = this.raw(child, "before");
10826 if (before) this.builder(before);
10827 this.stringify(child, last !== i2 || semicolon);
10828 }
10829 };
10830 _proto.comment = function comment(node2) {
10831 var left = this.raw(node2, "left", "commentLeft");
10832 var right = this.raw(node2, "right", "commentRight");
10833 this.builder("/*" + left + node2.text + right + "*/", node2);
10834 };
10835 _proto.decl = function decl(node2, semicolon) {
10836 var between = this.raw(node2, "between", "colon");
10837 var string = node2.prop + between + this.rawValue(node2, "value");
10838 if (node2.important) {
10839 string += node2.raws.important || " !important";
10840 }
10841 if (semicolon) string += ";";
10842 this.builder(string, node2);
10843 };
10844 _proto.document = function document1(node2) {
10845 this.body(node2);
10846 };
10847 _proto.raw = function raw(node2, own, detect) {
10848 var value;
10849 if (!detect) detect = own;
10850 if (own) {
10851 value = node2.raws[own];
10852 if (typeof value !== "undefined") return value;
10853 }
10854 var parent = node2.parent;
10855 if (detect === "before") {
10856 if (!parent || parent.type === "root" && parent.first === node2) {
10857 return "";
10858 }
10859 if (parent && parent.type === "document") {
10860 return "";
10861 }
10862 }
10863 if (!parent) return DEFAULT_RAW$1[detect];
10864 var root2 = node2.root();
10865 if (!root2.rawCache) root2.rawCache = {};
10866 if (typeof root2.rawCache[detect] !== "undefined") {
10867 return root2.rawCache[detect];
10868 }
10869 if (detect === "before" || detect === "after") {
10870 return this.beforeAfter(node2, detect);
10871 } else {
10872 var method = "raw" + capitalize$1(detect);
10873 if (this[method]) {
10874 value = this[method](root2, node2);
10875 } else {
10876 root2.walk(function(i2) {
10877 value = i2.raws[own];
10878 if (typeof value !== "undefined") return false;
10879 });
10880 }
10881 }
10882 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
10883 root2.rawCache[detect] = value;
10884 return value;
10885 };
10886 _proto.rawBeforeClose = function rawBeforeClose(root2) {
10887 var value;
10888 root2.walk(function(i2) {
10889 if (i2.nodes && i2.nodes.length > 0) {
10890 if (typeof i2.raws.after !== "undefined") {
10891 value = i2.raws.after;
10892 if (value.includes("\n")) {
10893 value = value.replace(/[^\n]+$/, "");
10894 }
10895 return false;
10896 }
10897 }
10898 });
10899 if (value) value = value.replace(/\S/g, "");
10900 return value;
10901 };
10902 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
10903 var value;
10904 root2.walkComments(function(i2) {
10905 if (typeof i2.raws.before !== "undefined") {
10906 value = i2.raws.before;
10907 if (value.includes("\n")) {
10908 value = value.replace(/[^\n]+$/, "");
10909 }
10910 return false;
10911 }
10912 });
10913 if (typeof value === "undefined") {
10914 value = this.raw(node2, null, "beforeDecl");
10915 } else if (value) {
10916 value = value.replace(/\S/g, "");
10917 }
10918 return value;
10919 };
10920 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
10921 var value;
10922 root2.walkDecls(function(i2) {
10923 if (typeof i2.raws.before !== "undefined") {
10924 value = i2.raws.before;
10925 if (value.includes("\n")) {
10926 value = value.replace(/[^\n]+$/, "");
10927 }
10928 return false;
10929 }
10930 });
10931 if (typeof value === "undefined") {
10932 value = this.raw(node2, null, "beforeRule");
10933 } else if (value) {
10934 value = value.replace(/\S/g, "");
10935 }
10936 return value;
10937 };
10938 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
10939 var value;
10940 root2.walk(function(i2) {
10941 if (i2.type !== "decl") {
10942 value = i2.raws.between;
10943 if (typeof value !== "undefined") return false;
10944 }
10945 });
10946 return value;
10947 };
10948 _proto.rawBeforeRule = function rawBeforeRule(root2) {
10949 var value;
10950 root2.walk(function(i2) {
10951 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
10952 if (typeof i2.raws.before !== "undefined") {
10953 value = i2.raws.before;
10954 if (value.includes("\n")) {
10955 value = value.replace(/[^\n]+$/, "");
10956 }
10957 return false;
10958 }
10959 }
10960 });
10961 if (value) value = value.replace(/\S/g, "");
10962 return value;
10963 };
10964 _proto.rawColon = function rawColon(root2) {
10965 var value;
10966 root2.walkDecls(function(i2) {
10967 if (typeof i2.raws.between !== "undefined") {
10968 value = i2.raws.between.replace(/[^\s:]/g, "");
10969 return false;
10970 }
10971 });
10972 return value;
10973 };
10974 _proto.rawEmptyBody = function rawEmptyBody(root2) {
10975 var value;
10976 root2.walk(function(i2) {
10977 if (i2.nodes && i2.nodes.length === 0) {
10978 value = i2.raws.after;
10979 if (typeof value !== "undefined") return false;
10980 }
10981 });
10982 return value;
10983 };
10984 _proto.rawIndent = function rawIndent(root2) {
10985 if (root2.raws.indent) return root2.raws.indent;
10986 var value;
10987 root2.walk(function(i2) {
10988 var p = i2.parent;
10989 if (p && p !== root2 && p.parent && p.parent === root2) {
10990 if (typeof i2.raws.before !== "undefined") {
10991 var parts = i2.raws.before.split("\n");
10992 value = parts[parts.length - 1];
10993 value = value.replace(/\S/g, "");
10994 return false;
10995 }
10996 }
10997 });
10998 return value;
10999 };
11000 _proto.rawSemicolon = function rawSemicolon(root2) {
11001 var value;
11002 root2.walk(function(i2) {
11003 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
11004 value = i2.raws.semicolon;
11005 if (typeof value !== "undefined") return false;
11006 }
11007 });
11008 return value;
11009 };
11010 _proto.rawValue = function rawValue(node2, prop) {
11011 var value = node2[prop];
11012 var raw = node2.raws[prop];
11013 if (raw && raw.value === value) {
11014 return raw.raw;
11015 }
11016 return value;
11017 };
11018 _proto.root = function root(node2) {
11019 this.body(node2);
11020 if (node2.raws.after) this.builder(node2.raws.after);
11021 };
11022 _proto.rule = function rule(node2) {
11023 this.block(node2, this.rawValue(node2, "selector"));
11024 if (node2.raws.ownSemicolon) {
11025 this.builder(node2.raws.ownSemicolon, node2, "end");
11026 }
11027 };
11028 _proto.stringify = function stringify(node2, semicolon) {
11029 if (!this[node2.type]) {
11030 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
11031 }
11032 this[node2.type](node2, semicolon);
11033 };
11034 return Stringifier;
11035 }();
11036 var stringifier$1 = Stringifier$2$1;
11037 Stringifier$2$1.default = Stringifier$2$1;
11038 var Stringifier$1$1 = stringifier$1;
11039 function stringify$4$1(node2, builder) {
11040 var str = new Stringifier$1$1(builder);
11041 str.stringify(node2);
11042 }
11043 var stringify_1$1 = stringify$4$1;
11044 stringify$4$1.default = stringify$4$1;
11045 var isClean$2$1 = symbols$1.isClean, my$2$1 = symbols$1.my;
11046 var CssSyntaxError$2$1 = cssSyntaxError$1;
11047 var Stringifier2$1 = stringifier$1;
11048 var stringify$3$1 = stringify_1$1;
11049 function cloneNode$1(obj, parent) {
11050 var cloned = new obj.constructor();
11051 for(var i2 in obj){
11052 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
11053 continue;
11054 }
11055 if (i2 === "proxyCache") continue;
11056 var value = obj[i2];
11057 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
11058 if (i2 === "parent" && type === "object") {
11059 if (parent) cloned[i2] = parent;
11060 } else if (i2 === "source") {
11061 cloned[i2] = value;
11062 } else if (Array.isArray(value)) {
11063 cloned[i2] = value.map(function(j) {
11064 return cloneNode$1(j, cloned);
11065 });
11066 } else {
11067 if (type === "object" && value !== null) value = cloneNode$1(value);
11068 cloned[i2] = value;
11069 }
11070 }
11071 return cloned;
11072 }
11073 var Node$4$1 = /*#__PURE__*/ function() {
11074 function Node2(defaults) {
11075 if (defaults === void 0) defaults = {};
11076 this.raws = {};
11077 this[isClean$2$1] = false;
11078 this[my$2$1] = true;
11079 for(var name in defaults){
11080 if (name === "nodes") {
11081 this.nodes = [];
11082 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
11083 var node2 = _step.value;
11084 if (typeof node2.clone === "function") {
11085 this.append(node2.clone());
11086 } else {
11087 this.append(node2);
11088 }
11089 }
11090 } else {
11091 this[name] = defaults[name];
11092 }
11093 }
11094 }
11095 var _proto = Node2.prototype;
11096 _proto.addToError = function addToError(error) {
11097 error.postcssNode = this;
11098 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
11099 var s2 = this.source;
11100 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
11101 }
11102 return error;
11103 };
11104 _proto.after = function after(add) {
11105 this.parent.insertAfter(this, add);
11106 return this;
11107 };
11108 _proto.assign = function assign(overrides) {
11109 if (overrides === void 0) overrides = {};
11110 for(var name in overrides){
11111 this[name] = overrides[name];
11112 }
11113 return this;
11114 };
11115 _proto.before = function before(add) {
11116 this.parent.insertBefore(this, add);
11117 return this;
11118 };
11119 _proto.cleanRaws = function cleanRaws(keepBetween) {
11120 delete this.raws.before;
11121 delete this.raws.after;
11122 if (!keepBetween) delete this.raws.between;
11123 };
11124 _proto.clone = function clone(overrides) {
11125 if (overrides === void 0) overrides = {};
11126 var cloned = cloneNode$1(this);
11127 for(var name in overrides){
11128 cloned[name] = overrides[name];
11129 }
11130 return cloned;
11131 };
11132 _proto.cloneAfter = function cloneAfter(overrides) {
11133 if (overrides === void 0) overrides = {};
11134 var cloned = this.clone(overrides);
11135 this.parent.insertAfter(this, cloned);
11136 return cloned;
11137 };
11138 _proto.cloneBefore = function cloneBefore(overrides) {
11139 if (overrides === void 0) overrides = {};
11140 var cloned = this.clone(overrides);
11141 this.parent.insertBefore(this, cloned);
11142 return cloned;
11143 };
11144 _proto.error = function error(message, opts) {
11145 if (opts === void 0) opts = {};
11146 if (this.source) {
11147 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
11148 return this.source.input.error(message, {
11149 column: start.column,
11150 line: start.line
11151 }, {
11152 column: end.column,
11153 line: end.line
11154 }, opts);
11155 }
11156 return new CssSyntaxError$2$1(message);
11157 };
11158 _proto.getProxyProcessor = function getProxyProcessor() {
11159 return {
11160 get: function get(node2, prop) {
11161 if (prop === "proxyOf") {
11162 return node2;
11163 } else if (prop === "root") {
11164 return function() {
11165 return node2.root().toProxy();
11166 };
11167 } else {
11168 return node2[prop];
11169 }
11170 },
11171 set: function set(node2, prop, value) {
11172 if (node2[prop] === value) return true;
11173 node2[prop] = value;
11174 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
11175 node2.markDirty();
11176 }
11177 return true;
11178 }
11179 };
11180 };
11181 _proto.markDirty = function markDirty() {
11182 if (this[isClean$2$1]) {
11183 this[isClean$2$1] = false;
11184 var next = this;
11185 while(next = next.parent){
11186 next[isClean$2$1] = false;
11187 }
11188 }
11189 };
11190 _proto.next = function next() {
11191 if (!this.parent) return void 0;
11192 var index2 = this.parent.index(this);
11193 return this.parent.nodes[index2 + 1];
11194 };
11195 _proto.positionBy = function positionBy(opts, stringRepresentation) {
11196 var pos = this.source.start;
11197 if (opts.index) {
11198 pos = this.positionInside(opts.index, stringRepresentation);
11199 } else if (opts.word) {
11200 stringRepresentation = this.toString();
11201 var index2 = stringRepresentation.indexOf(opts.word);
11202 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
11203 }
11204 return pos;
11205 };
11206 _proto.positionInside = function positionInside(index2, stringRepresentation) {
11207 var string = stringRepresentation || this.toString();
11208 var column = this.source.start.column;
11209 var line = this.source.start.line;
11210 for(var i2 = 0; i2 < index2; i2++){
11211 if (string[i2] === "\n") {
11212 column = 1;
11213 line += 1;
11214 } else {
11215 column += 1;
11216 }
11217 }
11218 return {
11219 column: column,
11220 line: line
11221 };
11222 };
11223 _proto.prev = function prev() {
11224 if (!this.parent) return void 0;
11225 var index2 = this.parent.index(this);
11226 return this.parent.nodes[index2 - 1];
11227 };
11228 _proto.rangeBy = function rangeBy(opts) {
11229 var start = {
11230 column: this.source.start.column,
11231 line: this.source.start.line
11232 };
11233 var end = this.source.end ? {
11234 column: this.source.end.column + 1,
11235 line: this.source.end.line
11236 } : {
11237 column: start.column + 1,
11238 line: start.line
11239 };
11240 if (opts.word) {
11241 var stringRepresentation = this.toString();
11242 var index2 = stringRepresentation.indexOf(opts.word);
11243 if (index2 !== -1) {
11244 start = this.positionInside(index2, stringRepresentation);
11245 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
11246 }
11247 } else {
11248 if (opts.start) {
11249 start = {
11250 column: opts.start.column,
11251 line: opts.start.line
11252 };
11253 } else if (opts.index) {
11254 start = this.positionInside(opts.index);
11255 }
11256 if (opts.end) {
11257 end = {
11258 column: opts.end.column,
11259 line: opts.end.line
11260 };
11261 } else if (typeof opts.endIndex === "number") {
11262 end = this.positionInside(opts.endIndex);
11263 } else if (opts.index) {
11264 end = this.positionInside(opts.index + 1);
11265 }
11266 }
11267 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
11268 end = {
11269 column: start.column + 1,
11270 line: start.line
11271 };
11272 }
11273 return {
11274 end: end,
11275 start: start
11276 };
11277 };
11278 _proto.raw = function raw(prop, defaultType) {
11279 var str = new Stringifier2$1();
11280 return str.raw(this, prop, defaultType);
11281 };
11282 _proto.remove = function remove() {
11283 if (this.parent) {
11284 this.parent.removeChild(this);
11285 }
11286 this.parent = void 0;
11287 return this;
11288 };
11289 _proto.replaceWith = function replaceWith() {
11290 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
11291 nodes[_key] = arguments[_key];
11292 }
11293 if (this.parent) {
11294 var bookmark = this;
11295 var foundSelf = false;
11296 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
11297 var node2 = _step.value;
11298 if (node2 === this) {
11299 foundSelf = true;
11300 } else if (foundSelf) {
11301 this.parent.insertAfter(bookmark, node2);
11302 bookmark = node2;
11303 } else {
11304 this.parent.insertBefore(bookmark, node2);
11305 }
11306 }
11307 if (!foundSelf) {
11308 this.remove();
11309 }
11310 }
11311 return this;
11312 };
11313 _proto.root = function root() {
11314 var result2 = this;
11315 while(result2.parent && result2.parent.type !== "document"){
11316 result2 = result2.parent;
11317 }
11318 return result2;
11319 };
11320 _proto.toJSON = function toJSON(_, inputs) {
11321 var fixed = {};
11322 var emitInputs = inputs == null;
11323 inputs = inputs || /* @__PURE__ */ new Map();
11324 var inputsNextIndex = 0;
11325 for(var name in this){
11326 if (!Object.prototype.hasOwnProperty.call(this, name)) {
11327 continue;
11328 }
11329 if (name === "parent" || name === "proxyCache") continue;
11330 var value = this[name];
11331 if (Array.isArray(value)) {
11332 fixed[name] = value.map(function(i2) {
11333 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
11334 return i2.toJSON(null, inputs);
11335 } else {
11336 return i2;
11337 }
11338 });
11339 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
11340 fixed[name] = value.toJSON(null, inputs);
11341 } else if (name === "source") {
11342 var inputId = inputs.get(value.input);
11343 if (inputId == null) {
11344 inputId = inputsNextIndex;
11345 inputs.set(value.input, inputsNextIndex);
11346 inputsNextIndex++;
11347 }
11348 fixed[name] = {
11349 end: value.end,
11350 inputId: inputId,
11351 start: value.start
11352 };
11353 } else {
11354 fixed[name] = value;
11355 }
11356 }
11357 if (emitInputs) {
11358 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
11359 return input2.toJSON();
11360 });
11361 }
11362 return fixed;
11363 };
11364 _proto.toProxy = function toProxy() {
11365 if (!this.proxyCache) {
11366 this.proxyCache = new Proxy(this, this.getProxyProcessor());
11367 }
11368 return this.proxyCache;
11369 };
11370 _proto.toString = function toString(stringifier2) {
11371 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
11372 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
11373 var result2 = "";
11374 stringifier2(this, function(i2) {
11375 result2 += i2;
11376 });
11377 return result2;
11378 };
11379 _proto.warn = function warn(result2, text, opts) {
11380 var data = {
11381 node: this
11382 };
11383 for(var i2 in opts)data[i2] = opts[i2];
11384 return result2.warn(text, data);
11385 };
11386 _create_class(Node2, [
11387 {
11388 key: "proxyOf",
11389 get: function get() {
11390 return this;
11391 }
11392 }
11393 ]);
11394 return Node2;
11395 }();
11396 var node$1 = Node$4$1;
11397 Node$4$1.default = Node$4$1;
11398 var Node$3$1 = node$1;
11399 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
11400 _inherits(Declaration, Node$3$1);
11401 function Declaration(defaults) {
11402 var _this;
11403 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
11404 defaults = _extends({}, defaults, {
11405 value: String(defaults.value)
11406 });
11407 }
11408 _this = Node$3$1.call(this, defaults) || this;
11409 _this.type = "decl";
11410 return _this;
11411 }
11412 _create_class(Declaration, [
11413 {
11414 key: "variable",
11415 get: function get() {
11416 return this.prop.startsWith("--") || this.prop[0] === "$";
11417 }
11418 }
11419 ]);
11420 return Declaration;
11421 }(Node$3$1);
11422 var declaration$1 = Declaration$4$1;
11423 Declaration$4$1.default = Declaration$4$1;
11424 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
11425 var nanoid$1$1 = function(size) {
11426 if (size === void 0) size = 21;
11427 var id = "";
11428 var i2 = size;
11429 while(i2--){
11430 id += urlAlphabet$1[Math.random() * 64 | 0];
11431 }
11432 return id;
11433 };
11434 var nonSecure$1 = {
11435 nanoid: nanoid$1$1};
11436 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
11437 var existsSync$1 = require$$2$1.existsSync, readFileSync$1 = require$$2$1.readFileSync;
11438 var dirname$1$1 = require$$2$1.dirname, join$1 = require$$2$1.join;
11439 function fromBase64$1(str) {
11440 if (Buffer) {
11441 return Buffer.from(str, "base64").toString();
11442 } else {
11443 return window.atob(str);
11444 }
11445 }
11446 var PreviousMap$2$1 = /*#__PURE__*/ function() {
11447 function PreviousMap(css, opts) {
11448 if (opts.map === false) return;
11449 this.loadAnnotation(css);
11450 this.inline = this.startWith(this.annotation, "data:");
11451 var prev = opts.map ? opts.map.prev : void 0;
11452 var text = this.loadMap(opts.from, prev);
11453 if (!this.mapFile && opts.from) {
11454 this.mapFile = opts.from;
11455 }
11456 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
11457 if (text) this.text = text;
11458 }
11459 var _proto = PreviousMap.prototype;
11460 _proto.consumer = function consumer() {
11461 if (!this.consumerCache) {
11462 this.consumerCache = new SourceMapConsumer$2$1(this.text);
11463 }
11464 return this.consumerCache;
11465 };
11466 _proto.decodeInline = function decodeInline(text) {
11467 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
11468 var baseUri = /^data:application\/json;base64,/;
11469 var charsetUri = /^data:application\/json;charset=utf-?8,/;
11470 var uri = /^data:application\/json,/;
11471 if (charsetUri.test(text) || uri.test(text)) {
11472 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
11473 }
11474 if (baseCharsetUri.test(text) || baseUri.test(text)) {
11475 return fromBase64$1(text.substr(RegExp.lastMatch.length));
11476 }
11477 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
11478 throw new Error("Unsupported source map encoding " + encoding);
11479 };
11480 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
11481 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
11482 };
11483 _proto.isMap = function isMap(map) {
11484 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
11485 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
11486 };
11487 _proto.loadAnnotation = function loadAnnotation(css) {
11488 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
11489 if (!comments) return;
11490 var start = css.lastIndexOf(comments.pop());
11491 var end = css.indexOf("*/", start);
11492 if (start > -1 && end > -1) {
11493 this.annotation = this.getAnnotationURL(css.substring(start, end));
11494 }
11495 };
11496 _proto.loadFile = function loadFile(path) {
11497 this.root = dirname$1$1(path);
11498 if (existsSync$1(path)) {
11499 this.mapFile = path;
11500 return readFileSync$1(path, "utf-8").toString().trim();
11501 }
11502 };
11503 _proto.loadMap = function loadMap(file, prev) {
11504 if (prev === false) return false;
11505 if (prev) {
11506 if (typeof prev === "string") {
11507 return prev;
11508 } else if (typeof prev === "function") {
11509 var prevPath = prev(file);
11510 if (prevPath) {
11511 var map = this.loadFile(prevPath);
11512 if (!map) {
11513 throw new Error("Unable to load previous source map: " + prevPath.toString());
11514 }
11515 return map;
11516 }
11517 } else if (_instanceof(prev, SourceMapConsumer$2$1)) {
11518 return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
11519 } else if (_instanceof(prev, SourceMapGenerator$2$1)) {
11520 return prev.toString();
11521 } else if (this.isMap(prev)) {
11522 return JSON.stringify(prev);
11523 } else {
11524 throw new Error("Unsupported previous source map format: " + prev.toString());
11525 }
11526 } else if (this.inline) {
11527 return this.decodeInline(this.annotation);
11528 } else if (this.annotation) {
11529 var map1 = this.annotation;
11530 if (file) map1 = join$1(dirname$1$1(file), map1);
11531 return this.loadFile(map1);
11532 }
11533 };
11534 _proto.startWith = function startWith(string, start) {
11535 if (!string) return false;
11536 return string.substr(0, start.length) === start;
11537 };
11538 _proto.withContent = function withContent() {
11539 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
11540 };
11541 return PreviousMap;
11542 }();
11543 var previousMap$1 = PreviousMap$2$1;
11544 PreviousMap$2$1.default = PreviousMap$2$1;
11545 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
11546 var fileURLToPath$1 = require$$2$1.fileURLToPath, pathToFileURL$1$1 = require$$2$1.pathToFileURL;
11547 var isAbsolute$1 = require$$2$1.isAbsolute, resolve$1$1 = require$$2$1.resolve;
11548 var nanoid$2 = nonSecure$1.nanoid;
11549 var terminalHighlight$2 = require$$2$1;
11550 var CssSyntaxError$1$1 = cssSyntaxError$1;
11551 var PreviousMap$1$1 = previousMap$1;
11552 var fromOffsetCache$1 = Symbol("fromOffsetCache");
11553 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
11554 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
11555 var Input$4$1 = /*#__PURE__*/ function() {
11556 function Input(css, opts) {
11557 if (opts === void 0) opts = {};
11558 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
11559 throw new Error("PostCSS received " + css + " instead of CSS string");
11560 }
11561 this.css = css.toString();
11562 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
11563 this.hasBOM = true;
11564 this.css = this.css.slice(1);
11565 } else {
11566 this.hasBOM = false;
11567 }
11568 if (opts.from) {
11569 if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) {
11570 this.file = opts.from;
11571 } else {
11572 this.file = resolve$1$1(opts.from);
11573 }
11574 }
11575 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
11576 var map = new PreviousMap$1$1(this.css, opts);
11577 if (map.text) {
11578 this.map = map;
11579 var file = map.consumer().file;
11580 if (!this.file && file) this.file = this.mapResolve(file);
11581 }
11582 }
11583 if (!this.file) {
11584 this.id = "<input css " + nanoid$2(6) + ">";
11585 }
11586 if (this.map) this.map.file = this.from;
11587 }
11588 var _proto = Input.prototype;
11589 _proto.error = function error(message, line, column, opts) {
11590 if (opts === void 0) opts = {};
11591 var result2, endLine, endColumn;
11592 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
11593 var start = line;
11594 var end = column;
11595 if (typeof start.offset === "number") {
11596 var pos = this.fromOffset(start.offset);
11597 line = pos.line;
11598 column = pos.col;
11599 } else {
11600 line = start.line;
11601 column = start.column;
11602 }
11603 if (typeof end.offset === "number") {
11604 var pos1 = this.fromOffset(end.offset);
11605 endLine = pos1.line;
11606 endColumn = pos1.col;
11607 } else {
11608 endLine = end.line;
11609 endColumn = end.column;
11610 }
11611 } else if (!column) {
11612 var pos2 = this.fromOffset(line);
11613 line = pos2.line;
11614 column = pos2.col;
11615 }
11616 var origin = this.origin(line, column, endLine, endColumn);
11617 if (origin) {
11618 result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
11619 column: origin.column,
11620 line: origin.line
11621 }, origin.endLine === void 0 ? origin.column : {
11622 column: origin.endColumn,
11623 line: origin.endLine
11624 }, origin.source, origin.file, opts.plugin);
11625 } else {
11626 result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
11627 column: column,
11628 line: line
11629 }, endLine === void 0 ? column : {
11630 column: endColumn,
11631 line: endLine
11632 }, this.css, this.file, opts.plugin);
11633 }
11634 result2.input = {
11635 column: column,
11636 endColumn: endColumn,
11637 endLine: endLine,
11638 line: line,
11639 source: this.css
11640 };
11641 if (this.file) {
11642 if (pathToFileURL$1$1) {
11643 result2.input.url = pathToFileURL$1$1(this.file).toString();
11644 }
11645 result2.input.file = this.file;
11646 }
11647 return result2;
11648 };
11649 _proto.fromOffset = function fromOffset(offset) {
11650 var lastLine, lineToIndex;
11651 if (!this[fromOffsetCache$1]) {
11652 var lines = this.css.split("\n");
11653 lineToIndex = new Array(lines.length);
11654 var prevIndex = 0;
11655 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
11656 lineToIndex[i2] = prevIndex;
11657 prevIndex += lines[i2].length + 1;
11658 }
11659 this[fromOffsetCache$1] = lineToIndex;
11660 } else {
11661 lineToIndex = this[fromOffsetCache$1];
11662 }
11663 lastLine = lineToIndex[lineToIndex.length - 1];
11664 var min = 0;
11665 if (offset >= lastLine) {
11666 min = lineToIndex.length - 1;
11667 } else {
11668 var max = lineToIndex.length - 2;
11669 var mid;
11670 while(min < max){
11671 mid = min + (max - min >> 1);
11672 if (offset < lineToIndex[mid]) {
11673 max = mid - 1;
11674 } else if (offset >= lineToIndex[mid + 1]) {
11675 min = mid + 1;
11676 } else {
11677 min = mid;
11678 break;
11679 }
11680 }
11681 }
11682 return {
11683 col: offset - lineToIndex[min] + 1,
11684 line: min + 1
11685 };
11686 };
11687 _proto.mapResolve = function mapResolve(file) {
11688 if (/^\w+:\/\//.test(file)) {
11689 return file;
11690 }
11691 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
11692 };
11693 _proto.origin = function origin(line, column, endLine, endColumn) {
11694 if (!this.map) return false;
11695 var consumer = this.map.consumer();
11696 var from = consumer.originalPositionFor({
11697 column: column,
11698 line: line
11699 });
11700 if (!from.source) return false;
11701 var to;
11702 if (typeof endLine === "number") {
11703 to = consumer.originalPositionFor({
11704 column: endColumn,
11705 line: endLine
11706 });
11707 }
11708 var fromUrl;
11709 if (isAbsolute$1(from.source)) {
11710 fromUrl = pathToFileURL$1$1(from.source);
11711 } else {
11712 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
11713 }
11714 var result2 = {
11715 column: from.column,
11716 endColumn: to && to.column,
11717 endLine: to && to.line,
11718 line: from.line,
11719 url: fromUrl.toString()
11720 };
11721 if (fromUrl.protocol === "file:") {
11722 if (fileURLToPath$1) {
11723 result2.file = fileURLToPath$1(fromUrl);
11724 } else {
11725 throw new Error("file: protocol is not available in this PostCSS build");
11726 }
11727 }
11728 var source = consumer.sourceContentFor(from.source);
11729 if (source) result2.source = source;
11730 return result2;
11731 };
11732 _proto.toJSON = function toJSON() {
11733 var json = {};
11734 for(var _i = 0, _iter = [
11735 "hasBOM",
11736 "css",
11737 "file",
11738 "id"
11739 ]; _i < _iter.length; _i++){
11740 var name = _iter[_i];
11741 if (this[name] != null) {
11742 json[name] = this[name];
11743 }
11744 }
11745 if (this.map) {
11746 json.map = _extends({}, this.map);
11747 if (json.map.consumerCache) {
11748 json.map.consumerCache = void 0;
11749 }
11750 }
11751 return json;
11752 };
11753 _create_class(Input, [
11754 {
11755 key: "from",
11756 get: function get() {
11757 return this.file || this.id;
11758 }
11759 }
11760 ]);
11761 return Input;
11762 }();
11763 var input$1 = Input$4$1;
11764 Input$4$1.default = Input$4$1;
11765 if (terminalHighlight$2 && terminalHighlight$2.registerInput) {
11766 terminalHighlight$2.registerInput(Input$4$1);
11767 }
11768 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer, SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
11769 var dirname$2 = require$$2$1.dirname, relative$1 = require$$2$1.relative, resolve$2 = require$$2$1.resolve, sep$1 = require$$2$1.sep;
11770 var pathToFileURL$2 = require$$2$1.pathToFileURL;
11771 var Input$3$1 = input$1;
11772 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
11773 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
11774 var MapGenerator$2$1 = /*#__PURE__*/ function() {
11775 function MapGenerator(stringify2, root2, opts, cssString) {
11776 this.stringify = stringify2;
11777 this.mapOpts = opts.map || {};
11778 this.root = root2;
11779 this.opts = opts;
11780 this.css = cssString;
11781 this.originalCSS = cssString;
11782 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
11783 this.memoizedFileURLs = /* @__PURE__ */ new Map();
11784 this.memoizedPaths = /* @__PURE__ */ new Map();
11785 this.memoizedURLs = /* @__PURE__ */ new Map();
11786 }
11787 var _proto = MapGenerator.prototype;
11788 _proto.addAnnotation = function addAnnotation() {
11789 var content;
11790 if (this.isInline()) {
11791 content = "data:application/json;base64," + this.toBase64(this.map.toString());
11792 } else if (typeof this.mapOpts.annotation === "string") {
11793 content = this.mapOpts.annotation;
11794 } else if (typeof this.mapOpts.annotation === "function") {
11795 content = this.mapOpts.annotation(this.opts.to, this.root);
11796 } else {
11797 content = this.outputFile() + ".map";
11798 }
11799 var eol = "\n";
11800 if (this.css.includes("\r\n")) eol = "\r\n";
11801 this.css += eol + "/*# sourceMappingURL=" + content + " */";
11802 };
11803 _proto.applyPrevMaps = function applyPrevMaps() {
11804 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
11805 var prev = _step.value;
11806 var from = this.toUrl(this.path(prev.file));
11807 var root2 = prev.root || dirname$2(prev.file);
11808 var map = void 0;
11809 if (this.mapOpts.sourcesContent === false) {
11810 map = new SourceMapConsumer$3(prev.text);
11811 if (map.sourcesContent) {
11812 map.sourcesContent = null;
11813 }
11814 } else {
11815 map = prev.consumer();
11816 }
11817 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
11818 }
11819 };
11820 _proto.clearAnnotation = function clearAnnotation() {
11821 if (this.mapOpts.annotation === false) return;
11822 if (this.root) {
11823 var node2;
11824 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
11825 node2 = this.root.nodes[i2];
11826 if (node2.type !== "comment") continue;
11827 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
11828 this.root.removeChild(i2);
11829 }
11830 }
11831 } else if (this.css) {
11832 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
11833 }
11834 };
11835 _proto.generate = function generate() {
11836 this.clearAnnotation();
11837 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) {
11838 return this.generateMap();
11839 } else {
11840 var result2 = "";
11841 this.stringify(this.root, function(i2) {
11842 result2 += i2;
11843 });
11844 return [
11845 result2
11846 ];
11847 }
11848 };
11849 _proto.generateMap = function generateMap() {
11850 if (this.root) {
11851 this.generateString();
11852 } else if (this.previous().length === 1) {
11853 var prev = this.previous()[0].consumer();
11854 prev.file = this.outputFile();
11855 this.map = SourceMapGenerator$3.fromSourceMap(prev, {
11856 ignoreInvalidMapping: true
11857 });
11858 } else {
11859 this.map = new SourceMapGenerator$3({
11860 file: this.outputFile(),
11861 ignoreInvalidMapping: true
11862 });
11863 this.map.addMapping({
11864 generated: {
11865 column: 0,
11866 line: 1
11867 },
11868 original: {
11869 column: 0,
11870 line: 1
11871 },
11872 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
11873 });
11874 }
11875 if (this.isSourcesContent()) this.setSourcesContent();
11876 if (this.root && this.previous().length > 0) this.applyPrevMaps();
11877 if (this.isAnnotation()) this.addAnnotation();
11878 if (this.isInline()) {
11879 return [
11880 this.css
11881 ];
11882 } else {
11883 return [
11884 this.css,
11885 this.map
11886 ];
11887 }
11888 };
11889 _proto.generateString = function generateString() {
11890 var _this = this;
11891 this.css = "";
11892 this.map = new SourceMapGenerator$3({
11893 file: this.outputFile(),
11894 ignoreInvalidMapping: true
11895 });
11896 var line = 1;
11897 var column = 1;
11898 var noSource = "<no source>";
11899 var mapping = {
11900 generated: {
11901 column: 0,
11902 line: 0
11903 },
11904 original: {
11905 column: 0,
11906 line: 0
11907 },
11908 source: ""
11909 };
11910 var lines, last;
11911 this.stringify(this.root, function(str, node2, type) {
11912 _this.css += str;
11913 if (node2 && type !== "end") {
11914 mapping.generated.line = line;
11915 mapping.generated.column = column - 1;
11916 if (node2.source && node2.source.start) {
11917 mapping.source = _this.sourcePath(node2);
11918 mapping.original.line = node2.source.start.line;
11919 mapping.original.column = node2.source.start.column - 1;
11920 _this.map.addMapping(mapping);
11921 } else {
11922 mapping.source = noSource;
11923 mapping.original.line = 1;
11924 mapping.original.column = 0;
11925 _this.map.addMapping(mapping);
11926 }
11927 }
11928 lines = str.match(/\n/g);
11929 if (lines) {
11930 line += lines.length;
11931 last = str.lastIndexOf("\n");
11932 column = str.length - last;
11933 } else {
11934 column += str.length;
11935 }
11936 if (node2 && type !== "start") {
11937 var p = node2.parent || {
11938 raws: {}
11939 };
11940 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
11941 if (!childless || node2 !== p.last || p.raws.semicolon) {
11942 if (node2.source && node2.source.end) {
11943 mapping.source = _this.sourcePath(node2);
11944 mapping.original.line = node2.source.end.line;
11945 mapping.original.column = node2.source.end.column - 1;
11946 mapping.generated.line = line;
11947 mapping.generated.column = column - 2;
11948 _this.map.addMapping(mapping);
11949 } else {
11950 mapping.source = noSource;
11951 mapping.original.line = 1;
11952 mapping.original.column = 0;
11953 mapping.generated.line = line;
11954 mapping.generated.column = column - 1;
11955 _this.map.addMapping(mapping);
11956 }
11957 }
11958 }
11959 });
11960 };
11961 _proto.isAnnotation = function isAnnotation() {
11962 if (this.isInline()) {
11963 return true;
11964 }
11965 if (typeof this.mapOpts.annotation !== "undefined") {
11966 return this.mapOpts.annotation;
11967 }
11968 if (this.previous().length) {
11969 return this.previous().some(function(i2) {
11970 return i2.annotation;
11971 });
11972 }
11973 return true;
11974 };
11975 _proto.isInline = function isInline() {
11976 if (typeof this.mapOpts.inline !== "undefined") {
11977 return this.mapOpts.inline;
11978 }
11979 var annotation = this.mapOpts.annotation;
11980 if (typeof annotation !== "undefined" && annotation !== true) {
11981 return false;
11982 }
11983 if (this.previous().length) {
11984 return this.previous().some(function(i2) {
11985 return i2.inline;
11986 });
11987 }
11988 return true;
11989 };
11990 _proto.isMap = function isMap() {
11991 if (typeof this.opts.map !== "undefined") {
11992 return !!this.opts.map;
11993 }
11994 return this.previous().length > 0;
11995 };
11996 _proto.isSourcesContent = function isSourcesContent() {
11997 if (typeof this.mapOpts.sourcesContent !== "undefined") {
11998 return this.mapOpts.sourcesContent;
11999 }
12000 if (this.previous().length) {
12001 return this.previous().some(function(i2) {
12002 return i2.withContent();
12003 });
12004 }
12005 return true;
12006 };
12007 _proto.outputFile = function outputFile() {
12008 if (this.opts.to) {
12009 return this.path(this.opts.to);
12010 } else if (this.opts.from) {
12011 return this.path(this.opts.from);
12012 } else {
12013 return "to.css";
12014 }
12015 };
12016 _proto.path = function path(file) {
12017 if (this.mapOpts.absolute) return file;
12018 if (file.charCodeAt(0) === 60) return file;
12019 if (/^\w+:\/\//.test(file)) return file;
12020 var cached = this.memoizedPaths.get(file);
12021 if (cached) return cached;
12022 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
12023 if (typeof this.mapOpts.annotation === "string") {
12024 from = dirname$2(resolve$2(from, this.mapOpts.annotation));
12025 }
12026 var path = relative$1(from, file);
12027 this.memoizedPaths.set(file, path);
12028 return path;
12029 };
12030 _proto.previous = function previous() {
12031 var _this = this;
12032 if (!this.previousMaps) {
12033 this.previousMaps = [];
12034 if (this.root) {
12035 this.root.walk(function(node2) {
12036 if (node2.source && node2.source.input.map) {
12037 var map = node2.source.input.map;
12038 if (!_this.previousMaps.includes(map)) {
12039 _this.previousMaps.push(map);
12040 }
12041 }
12042 });
12043 } else {
12044 var input2 = new Input$3$1(this.originalCSS, this.opts);
12045 if (input2.map) this.previousMaps.push(input2.map);
12046 }
12047 }
12048 return this.previousMaps;
12049 };
12050 _proto.setSourcesContent = function setSourcesContent() {
12051 var _this = this;
12052 var already = {};
12053 if (this.root) {
12054 this.root.walk(function(node2) {
12055 if (node2.source) {
12056 var from = node2.source.input.from;
12057 if (from && !already[from]) {
12058 already[from] = true;
12059 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
12060 _this.map.setSourceContent(fromUrl, node2.source.input.css);
12061 }
12062 }
12063 });
12064 } else if (this.css) {
12065 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
12066 this.map.setSourceContent(from, this.css);
12067 }
12068 };
12069 _proto.sourcePath = function sourcePath(node2) {
12070 if (this.mapOpts.from) {
12071 return this.toUrl(this.mapOpts.from);
12072 } else if (this.usesFileUrls) {
12073 return this.toFileUrl(node2.source.input.from);
12074 } else {
12075 return this.toUrl(this.path(node2.source.input.from));
12076 }
12077 };
12078 _proto.toBase64 = function toBase64(str) {
12079 if (Buffer) {
12080 return Buffer.from(str).toString("base64");
12081 } else {
12082 return window.btoa(unescape(encodeURIComponent(str)));
12083 }
12084 };
12085 _proto.toFileUrl = function toFileUrl(path) {
12086 var cached = this.memoizedFileURLs.get(path);
12087 if (cached) return cached;
12088 if (pathToFileURL$2) {
12089 var fileURL = pathToFileURL$2(path).toString();
12090 this.memoizedFileURLs.set(path, fileURL);
12091 return fileURL;
12092 } else {
12093 throw new Error("`map.absolute` option is not available in this PostCSS build");
12094 }
12095 };
12096 _proto.toUrl = function toUrl(path) {
12097 var cached = this.memoizedURLs.get(path);
12098 if (cached) return cached;
12099 if (sep$1 === "\\") {
12100 path = path.replace(/\\/g, "/");
12101 }
12102 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
12103 this.memoizedURLs.set(path, url);
12104 return url;
12105 };
12106 return MapGenerator;
12107 }();
12108 var mapGenerator$1 = MapGenerator$2$1;
12109 var Node$2$1 = node$1;
12110 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
12111 _inherits(Comment, Node$2$1);
12112 function Comment(defaults) {
12113 var _this;
12114 _this = Node$2$1.call(this, defaults) || this;
12115 _this.type = "comment";
12116 return _this;
12117 }
12118 return Comment;
12119 }(Node$2$1);
12120 var comment$1 = Comment$4$1;
12121 Comment$4$1.default = Comment$4$1;
12122 var isClean$1$1 = symbols$1.isClean, my$1$1 = symbols$1.my;
12123 var Declaration$3$1 = declaration$1;
12124 var Comment$3$1 = comment$1;
12125 var Node$1$1 = node$1;
12126 var parse$4$1, Rule$4$1, AtRule$4$1, Root$6$1;
12127 function cleanSource$1(nodes) {
12128 return nodes.map(function(i2) {
12129 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
12130 delete i2.source;
12131 return i2;
12132 });
12133 }
12134 function markDirtyUp$1(node2) {
12135 node2[isClean$1$1] = false;
12136 if (node2.proxyOf.nodes) {
12137 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
12138 var i2 = _step.value;
12139 markDirtyUp$1(i2);
12140 }
12141 }
12142 }
12143 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
12144 _inherits(Container, Node$1$1);
12145 function Container() {
12146 return Node$1$1.apply(this, arguments) || this;
12147 }
12148 var _proto = Container.prototype;
12149 _proto.append = function append() {
12150 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12151 children[_key] = arguments[_key];
12152 }
12153 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
12154 var child = _step.value;
12155 var nodes = this.normalize(child, this.last);
12156 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12157 var node2 = _step1.value;
12158 this.proxyOf.nodes.push(node2);
12159 }
12160 }
12161 this.markDirty();
12162 return this;
12163 };
12164 _proto.cleanRaws = function cleanRaws(keepBetween) {
12165 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
12166 if (this.nodes) {
12167 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
12168 var node2 = _step.value;
12169 node2.cleanRaws(keepBetween);
12170 }
12171 }
12172 };
12173 _proto.each = function each(callback) {
12174 if (!this.proxyOf.nodes) return void 0;
12175 var iterator = this.getIterator();
12176 var index2, result2;
12177 while(this.indexes[iterator] < this.proxyOf.nodes.length){
12178 index2 = this.indexes[iterator];
12179 result2 = callback(this.proxyOf.nodes[index2], index2);
12180 if (result2 === false) break;
12181 this.indexes[iterator] += 1;
12182 }
12183 delete this.indexes[iterator];
12184 return result2;
12185 };
12186 _proto.every = function every(condition) {
12187 return this.nodes.every(condition);
12188 };
12189 _proto.getIterator = function getIterator() {
12190 if (!this.lastEach) this.lastEach = 0;
12191 if (!this.indexes) this.indexes = {};
12192 this.lastEach += 1;
12193 var iterator = this.lastEach;
12194 this.indexes[iterator] = 0;
12195 return iterator;
12196 };
12197 _proto.getProxyProcessor = function getProxyProcessor() {
12198 return {
12199 get: function get(node2, prop) {
12200 if (prop === "proxyOf") {
12201 return node2;
12202 } else if (!node2[prop]) {
12203 return node2[prop];
12204 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
12205 return function() {
12206 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
12207 args[_key] = arguments[_key];
12208 }
12209 var _node2;
12210 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
12211 if (typeof i2 === "function") {
12212 return function(child, index2) {
12213 return i2(child.toProxy(), index2);
12214 };
12215 } else {
12216 return i2;
12217 }
12218 })));
12219 };
12220 } else if (prop === "every" || prop === "some") {
12221 return function(cb) {
12222 return node2[prop](function(child) {
12223 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
12224 other[_key - 1] = arguments[_key];
12225 }
12226 return cb.apply(void 0, [].concat([
12227 child.toProxy()
12228 ], other));
12229 });
12230 };
12231 } else if (prop === "root") {
12232 return function() {
12233 return node2.root().toProxy();
12234 };
12235 } else if (prop === "nodes") {
12236 return node2.nodes.map(function(i2) {
12237 return i2.toProxy();
12238 });
12239 } else if (prop === "first" || prop === "last") {
12240 return node2[prop].toProxy();
12241 } else {
12242 return node2[prop];
12243 }
12244 },
12245 set: function set(node2, prop, value) {
12246 if (node2[prop] === value) return true;
12247 node2[prop] = value;
12248 if (prop === "name" || prop === "params" || prop === "selector") {
12249 node2.markDirty();
12250 }
12251 return true;
12252 }
12253 };
12254 };
12255 _proto.index = function index(child) {
12256 if (typeof child === "number") return child;
12257 if (child.proxyOf) child = child.proxyOf;
12258 return this.proxyOf.nodes.indexOf(child);
12259 };
12260 _proto.insertAfter = function insertAfter(exist, add) {
12261 var existIndex = this.index(exist);
12262 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
12263 existIndex = this.index(exist);
12264 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12265 var node2 = _step.value;
12266 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
12267 }
12268 var index2;
12269 for(var id in this.indexes){
12270 index2 = this.indexes[id];
12271 if (existIndex < index2) {
12272 this.indexes[id] = index2 + nodes.length;
12273 }
12274 }
12275 this.markDirty();
12276 return this;
12277 };
12278 _proto.insertBefore = function insertBefore(exist, add) {
12279 var existIndex = this.index(exist);
12280 var type = existIndex === 0 ? "prepend" : false;
12281 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
12282 existIndex = this.index(exist);
12283 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12284 var node2 = _step.value;
12285 this.proxyOf.nodes.splice(existIndex, 0, node2);
12286 }
12287 var index2;
12288 for(var id in this.indexes){
12289 index2 = this.indexes[id];
12290 if (existIndex <= index2) {
12291 this.indexes[id] = index2 + nodes.length;
12292 }
12293 }
12294 this.markDirty();
12295 return this;
12296 };
12297 _proto.normalize = function normalize(nodes, sample) {
12298 var _this = this;
12299 if (typeof nodes === "string") {
12300 nodes = cleanSource$1(parse$4$1(nodes).nodes);
12301 } else if (typeof nodes === "undefined") {
12302 nodes = [];
12303 } else if (Array.isArray(nodes)) {
12304 nodes = nodes.slice(0);
12305 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12306 var i2 = _step.value;
12307 if (i2.parent) i2.parent.removeChild(i2, "ignore");
12308 }
12309 } else if (nodes.type === "root" && this.type !== "document") {
12310 nodes = nodes.nodes.slice(0);
12311 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12312 var i21 = _step1.value;
12313 if (i21.parent) i21.parent.removeChild(i21, "ignore");
12314 }
12315 } else if (nodes.type) {
12316 nodes = [
12317 nodes
12318 ];
12319 } else if (nodes.prop) {
12320 if (typeof nodes.value === "undefined") {
12321 throw new Error("Value field is missed in node creation");
12322 } else if (typeof nodes.value !== "string") {
12323 nodes.value = String(nodes.value);
12324 }
12325 nodes = [
12326 new Declaration$3$1(nodes)
12327 ];
12328 } else if (nodes.selector) {
12329 nodes = [
12330 new Rule$4$1(nodes)
12331 ];
12332 } else if (nodes.name) {
12333 nodes = [
12334 new AtRule$4$1(nodes)
12335 ];
12336 } else if (nodes.text) {
12337 nodes = [
12338 new Comment$3$1(nodes)
12339 ];
12340 } else {
12341 throw new Error("Unknown node type in node creation");
12342 }
12343 var processed = nodes.map(function(i2) {
12344 if (!i2[my$1$1]) Container.rebuild(i2);
12345 i2 = i2.proxyOf;
12346 if (i2.parent) i2.parent.removeChild(i2);
12347 if (i2[isClean$1$1]) markDirtyUp$1(i2);
12348 if (typeof i2.raws.before === "undefined") {
12349 if (sample && typeof sample.raws.before !== "undefined") {
12350 i2.raws.before = sample.raws.before.replace(/\S/g, "");
12351 }
12352 }
12353 i2.parent = _this.proxyOf;
12354 return i2;
12355 });
12356 return processed;
12357 };
12358 _proto.prepend = function prepend() {
12359 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12360 children[_key] = arguments[_key];
12361 }
12362 children = children.reverse();
12363 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
12364 var child = _step.value;
12365 var nodes = this.normalize(child, this.first, "prepend").reverse();
12366 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12367 var node2 = _step1.value;
12368 this.proxyOf.nodes.unshift(node2);
12369 }
12370 for(var id in this.indexes){
12371 this.indexes[id] = this.indexes[id] + nodes.length;
12372 }
12373 }
12374 this.markDirty();
12375 return this;
12376 };
12377 _proto.push = function push(child) {
12378 child.parent = this;
12379 this.proxyOf.nodes.push(child);
12380 return this;
12381 };
12382 _proto.removeAll = function removeAll() {
12383 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
12384 var node2 = _step.value;
12385 node2.parent = void 0;
12386 }
12387 this.proxyOf.nodes = [];
12388 this.markDirty();
12389 return this;
12390 };
12391 _proto.removeChild = function removeChild(child) {
12392 child = this.index(child);
12393 this.proxyOf.nodes[child].parent = void 0;
12394 this.proxyOf.nodes.splice(child, 1);
12395 var index2;
12396 for(var id in this.indexes){
12397 index2 = this.indexes[id];
12398 if (index2 >= child) {
12399 this.indexes[id] = index2 - 1;
12400 }
12401 }
12402 this.markDirty();
12403 return this;
12404 };
12405 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
12406 if (!callback) {
12407 callback = opts;
12408 opts = {};
12409 }
12410 this.walkDecls(function(decl) {
12411 if (opts.props && !opts.props.includes(decl.prop)) return;
12412 if (opts.fast && !decl.value.includes(opts.fast)) return;
12413 decl.value = decl.value.replace(pattern, callback);
12414 });
12415 this.markDirty();
12416 return this;
12417 };
12418 _proto.some = function some(condition) {
12419 return this.nodes.some(condition);
12420 };
12421 _proto.walk = function walk(callback) {
12422 return this.each(function(child, i2) {
12423 var result2;
12424 try {
12425 result2 = callback(child, i2);
12426 } catch (e2) {
12427 throw child.addToError(e2);
12428 }
12429 if (result2 !== false && child.walk) {
12430 result2 = child.walk(callback);
12431 }
12432 return result2;
12433 });
12434 };
12435 _proto.walkAtRules = function walkAtRules(name, callback) {
12436 if (!callback) {
12437 callback = name;
12438 return this.walk(function(child, i2) {
12439 if (child.type === "atrule") {
12440 return callback(child, i2);
12441 }
12442 });
12443 }
12444 if (_instanceof(name, RegExp)) {
12445 return this.walk(function(child, i2) {
12446 if (child.type === "atrule" && name.test(child.name)) {
12447 return callback(child, i2);
12448 }
12449 });
12450 }
12451 return this.walk(function(child, i2) {
12452 if (child.type === "atrule" && child.name === name) {
12453 return callback(child, i2);
12454 }
12455 });
12456 };
12457 _proto.walkComments = function walkComments(callback) {
12458 return this.walk(function(child, i2) {
12459 if (child.type === "comment") {
12460 return callback(child, i2);
12461 }
12462 });
12463 };
12464 _proto.walkDecls = function walkDecls(prop, callback) {
12465 if (!callback) {
12466 callback = prop;
12467 return this.walk(function(child, i2) {
12468 if (child.type === "decl") {
12469 return callback(child, i2);
12470 }
12471 });
12472 }
12473 if (_instanceof(prop, RegExp)) {
12474 return this.walk(function(child, i2) {
12475 if (child.type === "decl" && prop.test(child.prop)) {
12476 return callback(child, i2);
12477 }
12478 });
12479 }
12480 return this.walk(function(child, i2) {
12481 if (child.type === "decl" && child.prop === prop) {
12482 return callback(child, i2);
12483 }
12484 });
12485 };
12486 _proto.walkRules = function walkRules(selector, callback) {
12487 if (!callback) {
12488 callback = selector;
12489 return this.walk(function(child, i2) {
12490 if (child.type === "rule") {
12491 return callback(child, i2);
12492 }
12493 });
12494 }
12495 if (_instanceof(selector, RegExp)) {
12496 return this.walk(function(child, i2) {
12497 if (child.type === "rule" && selector.test(child.selector)) {
12498 return callback(child, i2);
12499 }
12500 });
12501 }
12502 return this.walk(function(child, i2) {
12503 if (child.type === "rule" && child.selector === selector) {
12504 return callback(child, i2);
12505 }
12506 });
12507 };
12508 _create_class(Container, [
12509 {
12510 key: "first",
12511 get: function get() {
12512 if (!this.proxyOf.nodes) return void 0;
12513 return this.proxyOf.nodes[0];
12514 }
12515 },
12516 {
12517 key: "last",
12518 get: function get() {
12519 if (!this.proxyOf.nodes) return void 0;
12520 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
12521 }
12522 }
12523 ]);
12524 return Container;
12525 }(Node$1$1);
12526 Container$7$1.registerParse = function(dependant) {
12527 parse$4$1 = dependant;
12528 };
12529 Container$7$1.registerRule = function(dependant) {
12530 Rule$4$1 = dependant;
12531 };
12532 Container$7$1.registerAtRule = function(dependant) {
12533 AtRule$4$1 = dependant;
12534 };
12535 Container$7$1.registerRoot = function(dependant) {
12536 Root$6$1 = dependant;
12537 };
12538 var container$1 = Container$7$1;
12539 Container$7$1.default = Container$7$1;
12540 Container$7$1.rebuild = function(node2) {
12541 if (node2.type === "atrule") {
12542 Object.setPrototypeOf(node2, AtRule$4$1.prototype);
12543 } else if (node2.type === "rule") {
12544 Object.setPrototypeOf(node2, Rule$4$1.prototype);
12545 } else if (node2.type === "decl") {
12546 Object.setPrototypeOf(node2, Declaration$3$1.prototype);
12547 } else if (node2.type === "comment") {
12548 Object.setPrototypeOf(node2, Comment$3$1.prototype);
12549 } else if (node2.type === "root") {
12550 Object.setPrototypeOf(node2, Root$6$1.prototype);
12551 }
12552 node2[my$1$1] = true;
12553 if (node2.nodes) {
12554 node2.nodes.forEach(function(child) {
12555 Container$7$1.rebuild(child);
12556 });
12557 }
12558 };
12559 var Container$6$1 = container$1;
12560 var LazyResult$4$1, Processor$3$1;
12561 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
12562 _inherits(Document2, Container$6$1);
12563 function Document2(defaults) {
12564 var _this;
12565 _this = Container$6$1.call(this, _extends({
12566 type: "document"
12567 }, defaults)) || this;
12568 if (!_this.nodes) {
12569 _this.nodes = [];
12570 }
12571 return _this;
12572 }
12573 var _proto = Document2.prototype;
12574 _proto.toResult = function toResult(opts) {
12575 if (opts === void 0) opts = {};
12576 var lazy = new LazyResult$4$1(new Processor$3$1(), this, opts);
12577 return lazy.stringify();
12578 };
12579 return Document2;
12580 }(Container$6$1);
12581 Document$3$1.registerLazyResult = function(dependant) {
12582 LazyResult$4$1 = dependant;
12583 };
12584 Document$3$1.registerProcessor = function(dependant) {
12585 Processor$3$1 = dependant;
12586 };
12587 var document$1$1 = Document$3$1;
12588 Document$3$1.default = Document$3$1;
12589 var printed$1 = {};
12590 var warnOnce$2$1 = function warnOnce(message) {
12591 if (printed$1[message]) return;
12592 printed$1[message] = true;
12593 if (typeof console !== "undefined" && console.warn) {
12594 console.warn(message);
12595 }
12596 };
12597 var Warning$2$1 = /*#__PURE__*/ function() {
12598 function Warning(text, opts) {
12599 if (opts === void 0) opts = {};
12600 this.type = "warning";
12601 this.text = text;
12602 if (opts.node && opts.node.source) {
12603 var range = opts.node.rangeBy(opts);
12604 this.line = range.start.line;
12605 this.column = range.start.column;
12606 this.endLine = range.end.line;
12607 this.endColumn = range.end.column;
12608 }
12609 for(var opt in opts)this[opt] = opts[opt];
12610 }
12611 var _proto = Warning.prototype;
12612 _proto.toString = function toString() {
12613 if (this.node) {
12614 return this.node.error(this.text, {
12615 index: this.index,
12616 plugin: this.plugin,
12617 word: this.word
12618 }).message;
12619 }
12620 if (this.plugin) {
12621 return this.plugin + ": " + this.text;
12622 }
12623 return this.text;
12624 };
12625 return Warning;
12626 }();
12627 var warning$1 = Warning$2$1;
12628 Warning$2$1.default = Warning$2$1;
12629 var Warning$1$1 = warning$1;
12630 var Result$3$1 = /*#__PURE__*/ function() {
12631 function Result(processor2, root2, opts) {
12632 this.processor = processor2;
12633 this.messages = [];
12634 this.root = root2;
12635 this.opts = opts;
12636 this.css = void 0;
12637 this.map = void 0;
12638 }
12639 var _proto = Result.prototype;
12640 _proto.toString = function toString() {
12641 return this.css;
12642 };
12643 _proto.warn = function warn(text, opts) {
12644 if (opts === void 0) opts = {};
12645 if (!opts.plugin) {
12646 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
12647 opts.plugin = this.lastPlugin.postcssPlugin;
12648 }
12649 }
12650 var warning2 = new Warning$1$1(text, opts);
12651 this.messages.push(warning2);
12652 return warning2;
12653 };
12654 _proto.warnings = function warnings() {
12655 return this.messages.filter(function(i2) {
12656 return i2.type === "warning";
12657 });
12658 };
12659 _create_class(Result, [
12660 {
12661 key: "content",
12662 get: function get() {
12663 return this.css;
12664 }
12665 }
12666 ]);
12667 return Result;
12668 }();
12669 var result$1 = Result$3$1;
12670 Result$3$1.default = Result$3$1;
12671 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
12672 var DOUBLE_QUOTE$1 = '"'.charCodeAt(0);
12673 var BACKSLASH$1 = "\\".charCodeAt(0);
12674 var SLASH$1 = "/".charCodeAt(0);
12675 var NEWLINE$1 = "\n".charCodeAt(0);
12676 var SPACE$1 = " ".charCodeAt(0);
12677 var FEED$1 = "\f".charCodeAt(0);
12678 var TAB$1 = " ".charCodeAt(0);
12679 var CR$1 = "\r".charCodeAt(0);
12680 var OPEN_SQUARE$1 = "[".charCodeAt(0);
12681 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
12682 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
12683 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
12684 var OPEN_CURLY$1 = "{".charCodeAt(0);
12685 var CLOSE_CURLY$1 = "}".charCodeAt(0);
12686 var SEMICOLON$1 = ";".charCodeAt(0);
12687 var ASTERISK$1 = "*".charCodeAt(0);
12688 var COLON$1 = ":".charCodeAt(0);
12689 var AT$1 = "@".charCodeAt(0);
12690 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
12691 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
12692 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
12693 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
12694 var tokenize$1 = function tokenizer(input2, options) {
12695 if (options === void 0) options = {};
12696 var css = input2.css.valueOf();
12697 var ignore = options.ignoreErrors;
12698 var code, next, quote, content, escape;
12699 var escaped, escapePos, prev, n2, currentToken;
12700 var length = css.length;
12701 var pos = 0;
12702 var buffer = [];
12703 var returned = [];
12704 function position() {
12705 return pos;
12706 }
12707 function unclosed(what) {
12708 throw input2.error("Unclosed " + what, pos);
12709 }
12710 function endOfFile() {
12711 return returned.length === 0 && pos >= length;
12712 }
12713 function nextToken(opts) {
12714 if (returned.length) return returned.pop();
12715 if (pos >= length) return;
12716 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
12717 code = css.charCodeAt(pos);
12718 switch(code){
12719 case NEWLINE$1:
12720 case SPACE$1:
12721 case TAB$1:
12722 case CR$1:
12723 case FEED$1:
12724 {
12725 next = pos;
12726 do {
12727 next += 1;
12728 code = css.charCodeAt(next);
12729 }while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
12730 currentToken = [
12731 "space",
12732 css.slice(pos, next)
12733 ];
12734 pos = next - 1;
12735 break;
12736 }
12737 case OPEN_SQUARE$1:
12738 case CLOSE_SQUARE$1:
12739 case OPEN_CURLY$1:
12740 case CLOSE_CURLY$1:
12741 case COLON$1:
12742 case SEMICOLON$1:
12743 case CLOSE_PARENTHESES$1:
12744 {
12745 var controlChar = String.fromCharCode(code);
12746 currentToken = [
12747 controlChar,
12748 controlChar,
12749 pos
12750 ];
12751 break;
12752 }
12753 case OPEN_PARENTHESES$1:
12754 {
12755 prev = buffer.length ? buffer.pop()[1] : "";
12756 n2 = css.charCodeAt(pos + 1);
12757 if (prev === "url" && n2 !== SINGLE_QUOTE$1 && n2 !== DOUBLE_QUOTE$1 && n2 !== SPACE$1 && n2 !== NEWLINE$1 && n2 !== TAB$1 && n2 !== FEED$1 && n2 !== CR$1) {
12758 next = pos;
12759 do {
12760 escaped = false;
12761 next = css.indexOf(")", next + 1);
12762 if (next === -1) {
12763 if (ignore || ignoreUnclosed) {
12764 next = pos;
12765 break;
12766 } else {
12767 unclosed("bracket");
12768 }
12769 }
12770 escapePos = next;
12771 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
12772 escapePos -= 1;
12773 escaped = !escaped;
12774 }
12775 }while (escaped);
12776 currentToken = [
12777 "brackets",
12778 css.slice(pos, next + 1),
12779 pos,
12780 next
12781 ];
12782 pos = next;
12783 } else {
12784 next = css.indexOf(")", pos + 1);
12785 content = css.slice(pos, next + 1);
12786 if (next === -1 || RE_BAD_BRACKET$1.test(content)) {
12787 currentToken = [
12788 "(",
12789 "(",
12790 pos
12791 ];
12792 } else {
12793 currentToken = [
12794 "brackets",
12795 content,
12796 pos,
12797 next
12798 ];
12799 pos = next;
12800 }
12801 }
12802 break;
12803 }
12804 case SINGLE_QUOTE$1:
12805 case DOUBLE_QUOTE$1:
12806 {
12807 quote = code === SINGLE_QUOTE$1 ? "'" : '"';
12808 next = pos;
12809 do {
12810 escaped = false;
12811 next = css.indexOf(quote, next + 1);
12812 if (next === -1) {
12813 if (ignore || ignoreUnclosed) {
12814 next = pos + 1;
12815 break;
12816 } else {
12817 unclosed("string");
12818 }
12819 }
12820 escapePos = next;
12821 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
12822 escapePos -= 1;
12823 escaped = !escaped;
12824 }
12825 }while (escaped);
12826 currentToken = [
12827 "string",
12828 css.slice(pos, next + 1),
12829 pos,
12830 next
12831 ];
12832 pos = next;
12833 break;
12834 }
12835 case AT$1:
12836 {
12837 RE_AT_END$1.lastIndex = pos + 1;
12838 RE_AT_END$1.test(css);
12839 if (RE_AT_END$1.lastIndex === 0) {
12840 next = css.length - 1;
12841 } else {
12842 next = RE_AT_END$1.lastIndex - 2;
12843 }
12844 currentToken = [
12845 "at-word",
12846 css.slice(pos, next + 1),
12847 pos,
12848 next
12849 ];
12850 pos = next;
12851 break;
12852 }
12853 case BACKSLASH$1:
12854 {
12855 next = pos;
12856 escape = true;
12857 while(css.charCodeAt(next + 1) === BACKSLASH$1){
12858 next += 1;
12859 escape = !escape;
12860 }
12861 code = css.charCodeAt(next + 1);
12862 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
12863 next += 1;
12864 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
12865 while(RE_HEX_ESCAPE$1.test(css.charAt(next + 1))){
12866 next += 1;
12867 }
12868 if (css.charCodeAt(next + 1) === SPACE$1) {
12869 next += 1;
12870 }
12871 }
12872 }
12873 currentToken = [
12874 "word",
12875 css.slice(pos, next + 1),
12876 pos,
12877 next
12878 ];
12879 pos = next;
12880 break;
12881 }
12882 default:
12883 {
12884 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
12885 next = css.indexOf("*/", pos + 2) + 1;
12886 if (next === 0) {
12887 if (ignore || ignoreUnclosed) {
12888 next = css.length;
12889 } else {
12890 unclosed("comment");
12891 }
12892 }
12893 currentToken = [
12894 "comment",
12895 css.slice(pos, next + 1),
12896 pos,
12897 next
12898 ];
12899 pos = next;
12900 } else {
12901 RE_WORD_END$1.lastIndex = pos + 1;
12902 RE_WORD_END$1.test(css);
12903 if (RE_WORD_END$1.lastIndex === 0) {
12904 next = css.length - 1;
12905 } else {
12906 next = RE_WORD_END$1.lastIndex - 2;
12907 }
12908 currentToken = [
12909 "word",
12910 css.slice(pos, next + 1),
12911 pos,
12912 next
12913 ];
12914 buffer.push(currentToken);
12915 pos = next;
12916 }
12917 break;
12918 }
12919 }
12920 pos++;
12921 return currentToken;
12922 }
12923 function back(token) {
12924 returned.push(token);
12925 }
12926 return {
12927 back: back,
12928 endOfFile: endOfFile,
12929 nextToken: nextToken,
12930 position: position
12931 };
12932 };
12933 var Container$5$1 = container$1;
12934 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
12935 _inherits(AtRule, Container$5$1);
12936 function AtRule(defaults) {
12937 var _this;
12938 _this = Container$5$1.call(this, defaults) || this;
12939 _this.type = "atrule";
12940 return _this;
12941 }
12942 var _proto = AtRule.prototype;
12943 _proto.append = function append() {
12944 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12945 children[_key] = arguments[_key];
12946 }
12947 var _Container$5$1_prototype_append;
12948 if (!this.proxyOf.nodes) this.nodes = [];
12949 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([
12950 this
12951 ], children));
12952 };
12953 _proto.prepend = function prepend() {
12954 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12955 children[_key] = arguments[_key];
12956 }
12957 var _Container$5$1_prototype_prepend;
12958 if (!this.proxyOf.nodes) this.nodes = [];
12959 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([
12960 this
12961 ], children));
12962 };
12963 return AtRule;
12964 }(Container$5$1);
12965 var atRule$1 = AtRule$3$1;
12966 AtRule$3$1.default = AtRule$3$1;
12967 Container$5$1.registerAtRule(AtRule$3$1);
12968 var Container$4$1 = container$1;
12969 var LazyResult$3$1, Processor$2$1;
12970 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
12971 _inherits(Root, Container$4$1);
12972 function Root(defaults) {
12973 var _this;
12974 _this = Container$4$1.call(this, defaults) || this;
12975 _this.type = "root";
12976 if (!_this.nodes) _this.nodes = [];
12977 return _this;
12978 }
12979 var _proto = Root.prototype;
12980 _proto.normalize = function normalize(child, sample, type) {
12981 var nodes = Container$4$1.prototype.normalize.call(this, child);
12982 if (sample) {
12983 if (type === "prepend") {
12984 if (this.nodes.length > 1) {
12985 sample.raws.before = this.nodes[1].raws.before;
12986 } else {
12987 delete sample.raws.before;
12988 }
12989 } else if (this.first !== sample) {
12990 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12991 var node2 = _step.value;
12992 node2.raws.before = sample.raws.before;
12993 }
12994 }
12995 }
12996 return nodes;
12997 };
12998 _proto.removeChild = function removeChild(child, ignore) {
12999 var index2 = this.index(child);
13000 if (!ignore && index2 === 0 && this.nodes.length > 1) {
13001 this.nodes[1].raws.before = this.nodes[index2].raws.before;
13002 }
13003 return Container$4$1.prototype.removeChild.call(this, child);
13004 };
13005 _proto.toResult = function toResult(opts) {
13006 if (opts === void 0) opts = {};
13007 var lazy = new LazyResult$3$1(new Processor$2$1(), this, opts);
13008 return lazy.stringify();
13009 };
13010 return Root;
13011 }(Container$4$1);
13012 Root$5$1.registerLazyResult = function(dependant) {
13013 LazyResult$3$1 = dependant;
13014 };
13015 Root$5$1.registerProcessor = function(dependant) {
13016 Processor$2$1 = dependant;
13017 };
13018 var root$1 = Root$5$1;
13019 Root$5$1.default = Root$5$1;
13020 Container$4$1.registerRoot(Root$5$1);
13021 var list$2$1 = {
13022 comma: function comma(string) {
13023 return list$2$1.split(string, [
13024 ","
13025 ], true);
13026 },
13027 space: function space(string) {
13028 var spaces = [
13029 " ",
13030 "\n",
13031 " "
13032 ];
13033 return list$2$1.split(string, spaces);
13034 },
13035 split: function split(string, separators, last) {
13036 var array = [];
13037 var current = "";
13038 var split = false;
13039 var func = 0;
13040 var inQuote = false;
13041 var prevQuote = "";
13042 var escape = false;
13043 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
13044 var letter = _step.value;
13045 if (escape) {
13046 escape = false;
13047 } else if (letter === "\\") {
13048 escape = true;
13049 } else if (inQuote) {
13050 if (letter === prevQuote) {
13051 inQuote = false;
13052 }
13053 } else if (letter === '"' || letter === "'") {
13054 inQuote = true;
13055 prevQuote = letter;
13056 } else if (letter === "(") {
13057 func += 1;
13058 } else if (letter === ")") {
13059 if (func > 0) func -= 1;
13060 } else if (func === 0) {
13061 if (separators.includes(letter)) split = true;
13062 }
13063 if (split) {
13064 if (current !== "") array.push(current.trim());
13065 current = "";
13066 split = false;
13067 } else {
13068 current += letter;
13069 }
13070 }
13071 if (last || current !== "") array.push(current.trim());
13072 return array;
13073 }
13074 };
13075 var list_1$1 = list$2$1;
13076 list$2$1.default = list$2$1;
13077 var Container$3$1 = container$1;
13078 var list$1$1 = list_1$1;
13079 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
13080 _inherits(Rule, Container$3$1);
13081 function Rule(defaults) {
13082 var _this;
13083 _this = Container$3$1.call(this, defaults) || this;
13084 _this.type = "rule";
13085 if (!_this.nodes) _this.nodes = [];
13086 return _this;
13087 }
13088 _create_class(Rule, [
13089 {
13090 key: "selectors",
13091 get: function get() {
13092 return list$1$1.comma(this.selector);
13093 },
13094 set: function set(values) {
13095 var match = this.selector ? this.selector.match(/,\s*/) : null;
13096 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
13097 this.selector = values.join(sep2);
13098 }
13099 }
13100 ]);
13101 return Rule;
13102 }(Container$3$1);
13103 var rule$1 = Rule$3$1;
13104 Rule$3$1.default = Rule$3$1;
13105 Container$3$1.registerRule(Rule$3$1);
13106 var Declaration$2$1 = declaration$1;
13107 var tokenizer2$1 = tokenize$1;
13108 var Comment$2$1 = comment$1;
13109 var AtRule$2$1 = atRule$1;
13110 var Root$4$1 = root$1;
13111 var Rule$2$1 = rule$1;
13112 var SAFE_COMMENT_NEIGHBOR$1 = {
13113 empty: true,
13114 space: true
13115 };
13116 function findLastWithPosition$1(tokens) {
13117 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
13118 var token = tokens[i2];
13119 var pos = token[3] || token[2];
13120 if (pos) return pos;
13121 }
13122 }
13123 var Parser$1$1 = /*#__PURE__*/ function() {
13124 function Parser(input2) {
13125 this.input = input2;
13126 this.root = new Root$4$1();
13127 this.current = this.root;
13128 this.spaces = "";
13129 this.semicolon = false;
13130 this.createTokenizer();
13131 this.root.source = {
13132 input: input2,
13133 start: {
13134 column: 1,
13135 line: 1,
13136 offset: 0
13137 }
13138 };
13139 }
13140 var _proto = Parser.prototype;
13141 _proto.atrule = function atrule(token) {
13142 var node2 = new AtRule$2$1();
13143 node2.name = token[1].slice(1);
13144 if (node2.name === "") {
13145 this.unnamedAtrule(node2, token);
13146 }
13147 this.init(node2, token[2]);
13148 var type;
13149 var prev;
13150 var shift;
13151 var last = false;
13152 var open = false;
13153 var params = [];
13154 var brackets = [];
13155 while(!this.tokenizer.endOfFile()){
13156 token = this.tokenizer.nextToken();
13157 type = token[0];
13158 if (type === "(" || type === "[") {
13159 brackets.push(type === "(" ? ")" : "]");
13160 } else if (type === "{" && brackets.length > 0) {
13161 brackets.push("}");
13162 } else if (type === brackets[brackets.length - 1]) {
13163 brackets.pop();
13164 }
13165 if (brackets.length === 0) {
13166 if (type === ";") {
13167 node2.source.end = this.getPosition(token[2]);
13168 node2.source.end.offset++;
13169 this.semicolon = true;
13170 break;
13171 } else if (type === "{") {
13172 open = true;
13173 break;
13174 } else if (type === "}") {
13175 if (params.length > 0) {
13176 shift = params.length - 1;
13177 prev = params[shift];
13178 while(prev && prev[0] === "space"){
13179 prev = params[--shift];
13180 }
13181 if (prev) {
13182 node2.source.end = this.getPosition(prev[3] || prev[2]);
13183 node2.source.end.offset++;
13184 }
13185 }
13186 this.end(token);
13187 break;
13188 } else {
13189 params.push(token);
13190 }
13191 } else {
13192 params.push(token);
13193 }
13194 if (this.tokenizer.endOfFile()) {
13195 last = true;
13196 break;
13197 }
13198 }
13199 node2.raws.between = this.spacesAndCommentsFromEnd(params);
13200 if (params.length) {
13201 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
13202 this.raw(node2, "params", params);
13203 if (last) {
13204 token = params[params.length - 1];
13205 node2.source.end = this.getPosition(token[3] || token[2]);
13206 node2.source.end.offset++;
13207 this.spaces = node2.raws.between;
13208 node2.raws.between = "";
13209 }
13210 } else {
13211 node2.raws.afterName = "";
13212 node2.params = "";
13213 }
13214 if (open) {
13215 node2.nodes = [];
13216 this.current = node2;
13217 }
13218 };
13219 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
13220 var colon = this.colon(tokens);
13221 if (colon === false) return;
13222 var founded = 0;
13223 var token;
13224 for(var j = colon - 1; j >= 0; j--){
13225 token = tokens[j];
13226 if (token[0] !== "space") {
13227 founded += 1;
13228 if (founded === 2) break;
13229 }
13230 }
13231 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
13232 };
13233 _proto.colon = function colon(tokens) {
13234 var brackets = 0;
13235 var token, type, prev;
13236 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
13237 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
13238 token = element;
13239 type = token[0];
13240 if (type === "(") {
13241 brackets += 1;
13242 }
13243 if (type === ")") {
13244 brackets -= 1;
13245 }
13246 if (brackets === 0 && type === ":") {
13247 if (!prev) {
13248 this.doubleColon(token);
13249 } else if (prev[0] === "word" && prev[1] === "progid") {
13250 continue;
13251 } else {
13252 return i2;
13253 }
13254 }
13255 prev = token;
13256 }
13257 return false;
13258 };
13259 _proto.comment = function comment(token) {
13260 var node2 = new Comment$2$1();
13261 this.init(node2, token[2]);
13262 node2.source.end = this.getPosition(token[3] || token[2]);
13263 node2.source.end.offset++;
13264 var text = token[1].slice(2, -2);
13265 if (/^\s*$/.test(text)) {
13266 node2.text = "";
13267 node2.raws.left = text;
13268 node2.raws.right = "";
13269 } else {
13270 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
13271 node2.text = match[2];
13272 node2.raws.left = match[1];
13273 node2.raws.right = match[3];
13274 }
13275 };
13276 _proto.createTokenizer = function createTokenizer() {
13277 this.tokenizer = tokenizer2$1(this.input);
13278 };
13279 _proto.decl = function decl(tokens, customProperty) {
13280 var node2 = new Declaration$2$1();
13281 this.init(node2, tokens[0][2]);
13282 var last = tokens[tokens.length - 1];
13283 if (last[0] === ";") {
13284 this.semicolon = true;
13285 tokens.pop();
13286 }
13287 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
13288 node2.source.end.offset++;
13289 while(tokens[0][0] !== "word"){
13290 if (tokens.length === 1) this.unknownWord(tokens);
13291 node2.raws.before += tokens.shift()[1];
13292 }
13293 node2.source.start = this.getPosition(tokens[0][2]);
13294 node2.prop = "";
13295 while(tokens.length){
13296 var type = tokens[0][0];
13297 if (type === ":" || type === "space" || type === "comment") {
13298 break;
13299 }
13300 node2.prop += tokens.shift()[1];
13301 }
13302 node2.raws.between = "";
13303 var token;
13304 while(tokens.length){
13305 token = tokens.shift();
13306 if (token[0] === ":") {
13307 node2.raws.between += token[1];
13308 break;
13309 } else {
13310 if (token[0] === "word" && /\w/.test(token[1])) {
13311 this.unknownWord([
13312 token
13313 ]);
13314 }
13315 node2.raws.between += token[1];
13316 }
13317 }
13318 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
13319 node2.raws.before += node2.prop[0];
13320 node2.prop = node2.prop.slice(1);
13321 }
13322 var firstSpaces = [];
13323 var next;
13324 while(tokens.length){
13325 next = tokens[0][0];
13326 if (next !== "space" && next !== "comment") break;
13327 firstSpaces.push(tokens.shift());
13328 }
13329 this.precheckMissedSemicolon(tokens);
13330 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
13331 token = tokens[i2];
13332 if (token[1].toLowerCase() === "!important") {
13333 node2.important = true;
13334 var string = this.stringFrom(tokens, i2);
13335 string = this.spacesFromEnd(tokens) + string;
13336 if (string !== " !important") node2.raws.important = string;
13337 break;
13338 } else if (token[1].toLowerCase() === "important") {
13339 var cache = tokens.slice(0);
13340 var str = "";
13341 for(var j = i2; j > 0; j--){
13342 var type1 = cache[j][0];
13343 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
13344 break;
13345 }
13346 str = cache.pop()[1] + str;
13347 }
13348 if (str.trim().indexOf("!") === 0) {
13349 node2.important = true;
13350 node2.raws.important = str;
13351 tokens = cache;
13352 }
13353 }
13354 if (token[0] !== "space" && token[0] !== "comment") {
13355 break;
13356 }
13357 }
13358 var hasWord = tokens.some(function(i2) {
13359 return i2[0] !== "space" && i2[0] !== "comment";
13360 });
13361 if (hasWord) {
13362 node2.raws.between += firstSpaces.map(function(i2) {
13363 return i2[1];
13364 }).join("");
13365 firstSpaces = [];
13366 }
13367 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
13368 if (node2.value.includes(":") && !customProperty) {
13369 this.checkMissedSemicolon(tokens);
13370 }
13371 };
13372 _proto.doubleColon = function doubleColon(token) {
13373 throw this.input.error("Double colon", {
13374 offset: token[2]
13375 }, {
13376 offset: token[2] + token[1].length
13377 });
13378 };
13379 _proto.emptyRule = function emptyRule(token) {
13380 var node2 = new Rule$2$1();
13381 this.init(node2, token[2]);
13382 node2.selector = "";
13383 node2.raws.between = "";
13384 this.current = node2;
13385 };
13386 _proto.end = function end(token) {
13387 if (this.current.nodes && this.current.nodes.length) {
13388 this.current.raws.semicolon = this.semicolon;
13389 }
13390 this.semicolon = false;
13391 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
13392 this.spaces = "";
13393 if (this.current.parent) {
13394 this.current.source.end = this.getPosition(token[2]);
13395 this.current.source.end.offset++;
13396 this.current = this.current.parent;
13397 } else {
13398 this.unexpectedClose(token);
13399 }
13400 };
13401 _proto.endFile = function endFile() {
13402 if (this.current.parent) this.unclosedBlock();
13403 if (this.current.nodes && this.current.nodes.length) {
13404 this.current.raws.semicolon = this.semicolon;
13405 }
13406 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
13407 this.root.source.end = this.getPosition(this.tokenizer.position());
13408 };
13409 _proto.freeSemicolon = function freeSemicolon(token) {
13410 this.spaces += token[1];
13411 if (this.current.nodes) {
13412 var prev = this.current.nodes[this.current.nodes.length - 1];
13413 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
13414 prev.raws.ownSemicolon = this.spaces;
13415 this.spaces = "";
13416 }
13417 }
13418 };
13419 // Helpers
13420 _proto.getPosition = function getPosition(offset) {
13421 var pos = this.input.fromOffset(offset);
13422 return {
13423 column: pos.col,
13424 line: pos.line,
13425 offset: offset
13426 };
13427 };
13428 _proto.init = function init(node2, offset) {
13429 this.current.push(node2);
13430 node2.source = {
13431 input: this.input,
13432 start: this.getPosition(offset)
13433 };
13434 node2.raws.before = this.spaces;
13435 this.spaces = "";
13436 if (node2.type !== "comment") this.semicolon = false;
13437 };
13438 _proto.other = function other(start) {
13439 var end = false;
13440 var type = null;
13441 var colon = false;
13442 var bracket = null;
13443 var brackets = [];
13444 var customProperty = start[1].startsWith("--");
13445 var tokens = [];
13446 var token = start;
13447 while(token){
13448 type = token[0];
13449 tokens.push(token);
13450 if (type === "(" || type === "[") {
13451 if (!bracket) bracket = token;
13452 brackets.push(type === "(" ? ")" : "]");
13453 } else if (customProperty && colon && type === "{") {
13454 if (!bracket) bracket = token;
13455 brackets.push("}");
13456 } else if (brackets.length === 0) {
13457 if (type === ";") {
13458 if (colon) {
13459 this.decl(tokens, customProperty);
13460 return;
13461 } else {
13462 break;
13463 }
13464 } else if (type === "{") {
13465 this.rule(tokens);
13466 return;
13467 } else if (type === "}") {
13468 this.tokenizer.back(tokens.pop());
13469 end = true;
13470 break;
13471 } else if (type === ":") {
13472 colon = true;
13473 }
13474 } else if (type === brackets[brackets.length - 1]) {
13475 brackets.pop();
13476 if (brackets.length === 0) bracket = null;
13477 }
13478 token = this.tokenizer.nextToken();
13479 }
13480 if (this.tokenizer.endOfFile()) end = true;
13481 if (brackets.length > 0) this.unclosedBracket(bracket);
13482 if (end && colon) {
13483 if (!customProperty) {
13484 while(tokens.length){
13485 token = tokens[tokens.length - 1][0];
13486 if (token !== "space" && token !== "comment") break;
13487 this.tokenizer.back(tokens.pop());
13488 }
13489 }
13490 this.decl(tokens, customProperty);
13491 } else {
13492 this.unknownWord(tokens);
13493 }
13494 };
13495 _proto.parse = function parse() {
13496 var token;
13497 while(!this.tokenizer.endOfFile()){
13498 token = this.tokenizer.nextToken();
13499 switch(token[0]){
13500 case "space":
13501 this.spaces += token[1];
13502 break;
13503 case ";":
13504 this.freeSemicolon(token);
13505 break;
13506 case "}":
13507 this.end(token);
13508 break;
13509 case "comment":
13510 this.comment(token);
13511 break;
13512 case "at-word":
13513 this.atrule(token);
13514 break;
13515 case "{":
13516 this.emptyRule(token);
13517 break;
13518 default:
13519 this.other(token);
13520 break;
13521 }
13522 }
13523 this.endFile();
13524 };
13525 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
13526 _proto.raw = function raw(node2, prop, tokens, customProperty) {
13527 var token, type;
13528 var length = tokens.length;
13529 var value = "";
13530 var clean = true;
13531 var next, prev;
13532 for(var i2 = 0; i2 < length; i2 += 1){
13533 token = tokens[i2];
13534 type = token[0];
13535 if (type === "space" && i2 === length - 1 && !customProperty) {
13536 clean = false;
13537 } else if (type === "comment") {
13538 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
13539 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
13540 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) {
13541 if (value.slice(-1) === ",") {
13542 clean = false;
13543 } else {
13544 value += token[1];
13545 }
13546 } else {
13547 clean = false;
13548 }
13549 } else {
13550 value += token[1];
13551 }
13552 }
13553 if (!clean) {
13554 var raw = tokens.reduce(function(all, i2) {
13555 return all + i2[1];
13556 }, "");
13557 node2.raws[prop] = {
13558 raw: raw,
13559 value: value
13560 };
13561 }
13562 node2[prop] = value;
13563 };
13564 _proto.rule = function rule(tokens) {
13565 tokens.pop();
13566 var node2 = new Rule$2$1();
13567 this.init(node2, tokens[0][2]);
13568 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
13569 this.raw(node2, "selector", tokens);
13570 this.current = node2;
13571 };
13572 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
13573 var lastTokenType;
13574 var spaces = "";
13575 while(tokens.length){
13576 lastTokenType = tokens[tokens.length - 1][0];
13577 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
13578 spaces = tokens.pop()[1] + spaces;
13579 }
13580 return spaces;
13581 };
13582 // Errors
13583 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
13584 var next;
13585 var spaces = "";
13586 while(tokens.length){
13587 next = tokens[0][0];
13588 if (next !== "space" && next !== "comment") break;
13589 spaces += tokens.shift()[1];
13590 }
13591 return spaces;
13592 };
13593 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
13594 var lastTokenType;
13595 var spaces = "";
13596 while(tokens.length){
13597 lastTokenType = tokens[tokens.length - 1][0];
13598 if (lastTokenType !== "space") break;
13599 spaces = tokens.pop()[1] + spaces;
13600 }
13601 return spaces;
13602 };
13603 _proto.stringFrom = function stringFrom(tokens, from) {
13604 var result2 = "";
13605 for(var i2 = from; i2 < tokens.length; i2++){
13606 result2 += tokens[i2][1];
13607 }
13608 tokens.splice(from, tokens.length - from);
13609 return result2;
13610 };
13611 _proto.unclosedBlock = function unclosedBlock() {
13612 var pos = this.current.source.start;
13613 throw this.input.error("Unclosed block", pos.line, pos.column);
13614 };
13615 _proto.unclosedBracket = function unclosedBracket(bracket) {
13616 throw this.input.error("Unclosed bracket", {
13617 offset: bracket[2]
13618 }, {
13619 offset: bracket[2] + 1
13620 });
13621 };
13622 _proto.unexpectedClose = function unexpectedClose(token) {
13623 throw this.input.error("Unexpected }", {
13624 offset: token[2]
13625 }, {
13626 offset: token[2] + 1
13627 });
13628 };
13629 _proto.unknownWord = function unknownWord(tokens) {
13630 throw this.input.error("Unknown word", {
13631 offset: tokens[0][2]
13632 }, {
13633 offset: tokens[0][2] + tokens[0][1].length
13634 });
13635 };
13636 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
13637 throw this.input.error("At-rule without name", {
13638 offset: token[2]
13639 }, {
13640 offset: token[2] + token[1].length
13641 });
13642 };
13643 return Parser;
13644 }();
13645 var parser$1 = Parser$1$1;
13646 var Container$2$1 = container$1;
13647 var Parser2$1 = parser$1;
13648 var Input$2$1 = input$1;
13649 function parse$3$1(css, opts) {
13650 var input2 = new Input$2$1(css, opts);
13651 var parser2 = new Parser2$1(input2);
13652 try {
13653 parser2.parse();
13654 } catch (e2) {
13655 if (true) {
13656 if (e2.name === "CssSyntaxError" && opts && opts.from) {
13657 if (/\.scss$/i.test(opts.from)) {
13658 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
13659 } else if (/\.sass/i.test(opts.from)) {
13660 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
13661 } else if (/\.less$/i.test(opts.from)) {
13662 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
13663 }
13664 }
13665 }
13666 throw e2;
13667 }
13668 return parser2.root;
13669 }
13670 var parse_1$1 = parse$3$1;
13671 parse$3$1.default = parse$3$1;
13672 Container$2$1.registerParse(parse$3$1);
13673 var isClean$3 = symbols$1.isClean, my$3 = symbols$1.my;
13674 var MapGenerator$1$1 = mapGenerator$1;
13675 var stringify$2$1 = stringify_1$1;
13676 var Container$1$1 = container$1;
13677 var Document$2$1 = document$1$1;
13678 var warnOnce$1$1 = warnOnce$2$1;
13679 var Result$2$1 = result$1;
13680 var parse$2$1 = parse_1$1;
13681 var Root$3$1 = root$1;
13682 var TYPE_TO_CLASS_NAME$1 = {
13683 atrule: "AtRule",
13684 comment: "Comment",
13685 decl: "Declaration",
13686 document: "Document",
13687 root: "Root",
13688 rule: "Rule"
13689 };
13690 var PLUGIN_PROPS$1 = {
13691 AtRule: true,
13692 AtRuleExit: true,
13693 Comment: true,
13694 CommentExit: true,
13695 Declaration: true,
13696 DeclarationExit: true,
13697 Document: true,
13698 DocumentExit: true,
13699 Once: true,
13700 OnceExit: true,
13701 postcssPlugin: true,
13702 prepare: true,
13703 Root: true,
13704 RootExit: true,
13705 Rule: true,
13706 RuleExit: true
13707 };
13708 var NOT_VISITORS$1 = {
13709 Once: true,
13710 postcssPlugin: true,
13711 prepare: true
13712 };
13713 var CHILDREN$1 = 0;
13714 function isPromise$1(obj) {
13715 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
13716 }
13717 function getEvents$1(node2) {
13718 var key = false;
13719 var type = TYPE_TO_CLASS_NAME$1[node2.type];
13720 if (node2.type === "decl") {
13721 key = node2.prop.toLowerCase();
13722 } else if (node2.type === "atrule") {
13723 key = node2.name.toLowerCase();
13724 }
13725 if (key && node2.append) {
13726 return [
13727 type,
13728 type + "-" + key,
13729 CHILDREN$1,
13730 type + "Exit",
13731 type + "Exit-" + key
13732 ];
13733 } else if (key) {
13734 return [
13735 type,
13736 type + "-" + key,
13737 type + "Exit",
13738 type + "Exit-" + key
13739 ];
13740 } else if (node2.append) {
13741 return [
13742 type,
13743 CHILDREN$1,
13744 type + "Exit"
13745 ];
13746 } else {
13747 return [
13748 type,
13749 type + "Exit"
13750 ];
13751 }
13752 }
13753 function toStack$1(node2) {
13754 var events;
13755 if (node2.type === "document") {
13756 events = [
13757 "Document",
13758 CHILDREN$1,
13759 "DocumentExit"
13760 ];
13761 } else if (node2.type === "root") {
13762 events = [
13763 "Root",
13764 CHILDREN$1,
13765 "RootExit"
13766 ];
13767 } else {
13768 events = getEvents$1(node2);
13769 }
13770 return {
13771 eventIndex: 0,
13772 events: events,
13773 iterator: 0,
13774 node: node2,
13775 visitorIndex: 0,
13776 visitors: []
13777 };
13778 }
13779 function cleanMarks$1(node2) {
13780 node2[isClean$3] = false;
13781 if (node2.nodes) node2.nodes.forEach(function(i2) {
13782 return cleanMarks$1(i2);
13783 });
13784 return node2;
13785 }
13786 var postcss$2$1 = {};
13787 var LazyResult$2$1 = /*#__PURE__*/ function() {
13788 function LazyResult(processor2, css, opts) {
13789 var _this = this;
13790 this.stringified = false;
13791 this.processed = false;
13792 var root2;
13793 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
13794 root2 = cleanMarks$1(css);
13795 } else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
13796 root2 = cleanMarks$1(css.root);
13797 if (css.map) {
13798 if (typeof opts.map === "undefined") opts.map = {};
13799 if (!opts.map.inline) opts.map.inline = false;
13800 opts.map.prev = css.map;
13801 }
13802 } else {
13803 var parser2 = parse$2$1;
13804 if (opts.syntax) parser2 = opts.syntax.parse;
13805 if (opts.parser) parser2 = opts.parser;
13806 if (parser2.parse) parser2 = parser2.parse;
13807 try {
13808 root2 = parser2(css, opts);
13809 } catch (error) {
13810 this.processed = true;
13811 this.error = error;
13812 }
13813 if (root2 && !root2[my$3]) {
13814 Container$1$1.rebuild(root2);
13815 }
13816 }
13817 this.result = new Result$2$1(processor2, root2, opts);
13818 this.helpers = _extends({}, postcss$2$1, {
13819 postcss: postcss$2$1,
13820 result: this.result
13821 });
13822 this.plugins = this.processor.plugins.map(function(plugin22) {
13823 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
13824 return _extends({}, plugin22, plugin22.prepare(_this.result));
13825 } else {
13826 return plugin22;
13827 }
13828 });
13829 }
13830 var _proto = LazyResult.prototype;
13831 _proto.async = function async() {
13832 if (this.error) return Promise.reject(this.error);
13833 if (this.processed) return Promise.resolve(this.result);
13834 if (!this.processing) {
13835 this.processing = this.runAsync();
13836 }
13837 return this.processing;
13838 };
13839 _proto.catch = function _catch(onRejected) {
13840 return this.async().catch(onRejected);
13841 };
13842 _proto.finally = function _finally(onFinally) {
13843 return this.async().then(onFinally, onFinally);
13844 };
13845 _proto.getAsyncError = function getAsyncError() {
13846 throw new Error("Use process(css).then(cb) to work with async plugins");
13847 };
13848 _proto.handleError = function handleError(error, node2) {
13849 var plugin22 = this.result.lastPlugin;
13850 try {
13851 if (node2) node2.addToError(error);
13852 this.error = error;
13853 if (error.name === "CssSyntaxError" && !error.plugin) {
13854 error.plugin = plugin22.postcssPlugin;
13855 error.setMessage();
13856 } else if (plugin22.postcssVersion) {
13857 if (true) {
13858 var pluginName = plugin22.postcssPlugin;
13859 var pluginVer = plugin22.postcssVersion;
13860 var runtimeVer = this.result.processor.version;
13861 var a2 = pluginVer.split(".");
13862 var b = runtimeVer.split(".");
13863 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
13864 console.error("Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below.");
13865 }
13866 }
13867 }
13868 } catch (err) {
13869 if (console && console.error) console.error(err);
13870 }
13871 return error;
13872 };
13873 _proto.prepareVisitors = function prepareVisitors() {
13874 var _this = this;
13875 this.listeners = {};
13876 var add = function(plugin22, type, cb) {
13877 if (!_this.listeners[type]) _this.listeners[type] = [];
13878 _this.listeners[type].push([
13879 plugin22,
13880 cb
13881 ]);
13882 };
13883 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
13884 var plugin22 = _step.value;
13885 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
13886 for(var event in plugin22){
13887 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) {
13888 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
13889 }
13890 if (!NOT_VISITORS$1[event]) {
13891 if (_type_of(plugin22[event]) === "object") {
13892 for(var filter in plugin22[event]){
13893 if (filter === "*") {
13894 add(plugin22, event, plugin22[event][filter]);
13895 } else {
13896 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
13897 }
13898 }
13899 } else if (typeof plugin22[event] === "function") {
13900 add(plugin22, event, plugin22[event]);
13901 }
13902 }
13903 }
13904 }
13905 }
13906 this.hasListener = Object.keys(this.listeners).length > 0;
13907 };
13908 _proto.runAsync = function runAsync() {
13909 var _this = this;
13910 return _async_to_generator(function() {
13911 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
13912 return _ts_generator(this, function(_state) {
13913 switch(_state.label){
13914 case 0:
13915 _this.plugin = 0;
13916 i2 = 0;
13917 _state.label = 1;
13918 case 1:
13919 if (!(i2 < _this.plugins.length)) return [
13920 3,
13921 6
13922 ];
13923 plugin22 = _this.plugins[i2];
13924 promise = _this.runOnRoot(plugin22);
13925 if (!isPromise$1(promise)) return [
13926 3,
13927 5
13928 ];
13929 _state.label = 2;
13930 case 2:
13931 _state.trys.push([
13932 2,
13933 4,
13934 ,
13935 5
13936 ]);
13937 return [
13938 4,
13939 promise
13940 ];
13941 case 3:
13942 _state.sent();
13943 return [
13944 3,
13945 5
13946 ];
13947 case 4:
13948 error = _state.sent();
13949 throw _this.handleError(error);
13950 case 5:
13951 i2++;
13952 return [
13953 3,
13954 1
13955 ];
13956 case 6:
13957 _this.prepareVisitors();
13958 if (!_this.hasListener) return [
13959 3,
13960 18
13961 ];
13962 root2 = _this.result.root;
13963 _state.label = 7;
13964 case 7:
13965 if (!!root2[isClean$3]) return [
13966 3,
13967 14
13968 ];
13969 root2[isClean$3] = true;
13970 stack = [
13971 toStack$1(root2)
13972 ];
13973 _state.label = 8;
13974 case 8:
13975 if (!(stack.length > 0)) return [
13976 3,
13977 13
13978 ];
13979 promise1 = _this.visitTick(stack);
13980 if (!isPromise$1(promise1)) return [
13981 3,
13982 12
13983 ];
13984 _state.label = 9;
13985 case 9:
13986 _state.trys.push([
13987 9,
13988 11,
13989 ,
13990 12
13991 ]);
13992 return [
13993 4,
13994 promise1
13995 ];
13996 case 10:
13997 _state.sent();
13998 return [
13999 3,
14000 12
14001 ];
14002 case 11:
14003 e2 = _state.sent();
14004 node2 = stack[stack.length - 1].node;
14005 throw _this.handleError(e2, node2);
14006 case 12:
14007 return [
14008 3,
14009 8
14010 ];
14011 case 13:
14012 return [
14013 3,
14014 7
14015 ];
14016 case 14:
14017 if (!_this.listeners.OnceExit) return [
14018 3,
14019 18
14020 ];
14021 _loop = function() {
14022 var _step_value, plugin22, visitor, roots, e2;
14023 return _ts_generator(this, function(_state) {
14024 switch(_state.label){
14025 case 0:
14026 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
14027 _this.result.lastPlugin = plugin22;
14028 _state.label = 1;
14029 case 1:
14030 _state.trys.push([
14031 1,
14032 6,
14033 ,
14034 7
14035 ]);
14036 if (!(root2.type === "document")) return [
14037 3,
14038 3
14039 ];
14040 roots = root2.nodes.map(function(subRoot) {
14041 return visitor(subRoot, _this.helpers);
14042 });
14043 return [
14044 4,
14045 Promise.all(roots)
14046 ];
14047 case 2:
14048 _state.sent();
14049 return [
14050 3,
14051 5
14052 ];
14053 case 3:
14054 return [
14055 4,
14056 visitor(root2, _this.helpers)
14057 ];
14058 case 4:
14059 _state.sent();
14060 _state.label = 5;
14061 case 5:
14062 return [
14063 3,
14064 7
14065 ];
14066 case 6:
14067 e2 = _state.sent();
14068 throw _this.handleError(e2);
14069 case 7:
14070 return [
14071 2
14072 ];
14073 }
14074 });
14075 };
14076 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
14077 _state.label = 15;
14078 case 15:
14079 if (!!(_step = _iterator()).done) return [
14080 3,
14081 18
14082 ];
14083 return [
14084 5,
14085 _ts_values(_loop())
14086 ];
14087 case 16:
14088 _state.sent();
14089 _state.label = 17;
14090 case 17:
14091 return [
14092 3,
14093 15
14094 ];
14095 case 18:
14096 _this.processed = true;
14097 return [
14098 2,
14099 _this.stringify()
14100 ];
14101 }
14102 });
14103 })();
14104 };
14105 _proto.runOnRoot = function runOnRoot(plugin22) {
14106 var _this = this;
14107 this.result.lastPlugin = plugin22;
14108 try {
14109 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
14110 if (this.result.root.type === "document") {
14111 var roots = this.result.root.nodes.map(function(root2) {
14112 return plugin22.Once(root2, _this.helpers);
14113 });
14114 if (isPromise$1(roots[0])) {
14115 return Promise.all(roots);
14116 }
14117 return roots;
14118 }
14119 return plugin22.Once(this.result.root, this.helpers);
14120 } else if (typeof plugin22 === "function") {
14121 return plugin22(this.result.root, this.result);
14122 }
14123 } catch (error) {
14124 throw this.handleError(error);
14125 }
14126 };
14127 _proto.stringify = function stringify() {
14128 if (this.error) throw this.error;
14129 if (this.stringified) return this.result;
14130 this.stringified = true;
14131 this.sync();
14132 var opts = this.result.opts;
14133 var str = stringify$2$1;
14134 if (opts.syntax) str = opts.syntax.stringify;
14135 if (opts.stringifier) str = opts.stringifier;
14136 if (str.stringify) str = str.stringify;
14137 var map = new MapGenerator$1$1(str, this.result.root, this.result.opts);
14138 var data = map.generate();
14139 this.result.css = data[0];
14140 this.result.map = data[1];
14141 return this.result;
14142 };
14143 _proto.sync = function sync() {
14144 if (this.error) throw this.error;
14145 if (this.processed) return this.result;
14146 this.processed = true;
14147 if (this.processing) {
14148 throw this.getAsyncError();
14149 }
14150 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
14151 var plugin22 = _step.value;
14152 var promise = this.runOnRoot(plugin22);
14153 if (isPromise$1(promise)) {
14154 throw this.getAsyncError();
14155 }
14156 }
14157 this.prepareVisitors();
14158 if (this.hasListener) {
14159 var root2 = this.result.root;
14160 while(!root2[isClean$3]){
14161 root2[isClean$3] = true;
14162 this.walkSync(root2);
14163 }
14164 if (this.listeners.OnceExit) {
14165 if (root2.type === "document") {
14166 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
14167 var subRoot = _step1.value;
14168 this.visitSync(this.listeners.OnceExit, subRoot);
14169 }
14170 } else {
14171 this.visitSync(this.listeners.OnceExit, root2);
14172 }
14173 }
14174 }
14175 return this.result;
14176 };
14177 _proto.then = function then(onFulfilled, onRejected) {
14178 if (true) {
14179 if (!("from" in this.opts)) {
14180 warnOnce$1$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
14181 }
14182 }
14183 return this.async().then(onFulfilled, onRejected);
14184 };
14185 _proto.toString = function toString() {
14186 return this.css;
14187 };
14188 _proto.visitSync = function visitSync(visitors, node2) {
14189 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
14190 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
14191 this.result.lastPlugin = plugin22;
14192 var promise = void 0;
14193 try {
14194 promise = visitor(node2, this.helpers);
14195 } catch (e2) {
14196 throw this.handleError(e2, node2.proxyOf);
14197 }
14198 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
14199 return true;
14200 }
14201 if (isPromise$1(promise)) {
14202 throw this.getAsyncError();
14203 }
14204 }
14205 };
14206 _proto.visitTick = function visitTick(stack) {
14207 var visit2 = stack[stack.length - 1];
14208 var node2 = visit2.node, visitors = visit2.visitors;
14209 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
14210 stack.pop();
14211 return;
14212 }
14213 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
14214 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
14215 visit2.visitorIndex += 1;
14216 if (visit2.visitorIndex === visitors.length) {
14217 visit2.visitors = [];
14218 visit2.visitorIndex = 0;
14219 }
14220 this.result.lastPlugin = plugin22;
14221 try {
14222 return visitor(node2.toProxy(), this.helpers);
14223 } catch (e2) {
14224 throw this.handleError(e2, node2);
14225 }
14226 }
14227 if (visit2.iterator !== 0) {
14228 var iterator = visit2.iterator;
14229 var child;
14230 while(child = node2.nodes[node2.indexes[iterator]]){
14231 node2.indexes[iterator] += 1;
14232 if (!child[isClean$3]) {
14233 child[isClean$3] = true;
14234 stack.push(toStack$1(child));
14235 return;
14236 }
14237 }
14238 visit2.iterator = 0;
14239 delete node2.indexes[iterator];
14240 }
14241 var events = visit2.events;
14242 while(visit2.eventIndex < events.length){
14243 var event = events[visit2.eventIndex];
14244 visit2.eventIndex += 1;
14245 if (event === CHILDREN$1) {
14246 if (node2.nodes && node2.nodes.length) {
14247 node2[isClean$3] = true;
14248 visit2.iterator = node2.getIterator();
14249 }
14250 return;
14251 } else if (this.listeners[event]) {
14252 visit2.visitors = this.listeners[event];
14253 return;
14254 }
14255 }
14256 stack.pop();
14257 };
14258 _proto.walkSync = function walkSync(node2) {
14259 var _this = this;
14260 node2[isClean$3] = true;
14261 var events = getEvents$1(node2);
14262 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
14263 var event = _step.value;
14264 if (event === CHILDREN$1) {
14265 if (node2.nodes) {
14266 node2.each(function(child) {
14267 if (!child[isClean$3]) _this.walkSync(child);
14268 });
14269 }
14270 } else {
14271 var visitors = this.listeners[event];
14272 if (visitors) {
14273 if (this.visitSync(visitors, node2.toProxy())) return;
14274 }
14275 }
14276 }
14277 };
14278 _proto.warnings = function warnings() {
14279 return this.sync().warnings();
14280 };
14281 _create_class(LazyResult, [
14282 {
14283 key: "content",
14284 get: function get() {
14285 return this.stringify().content;
14286 }
14287 },
14288 {
14289 key: "css",
14290 get: function get() {
14291 return this.stringify().css;
14292 }
14293 },
14294 {
14295 key: "map",
14296 get: function get() {
14297 return this.stringify().map;
14298 }
14299 },
14300 {
14301 key: "messages",
14302 get: function get() {
14303 return this.sync().messages;
14304 }
14305 },
14306 {
14307 key: "opts",
14308 get: function get() {
14309 return this.result.opts;
14310 }
14311 },
14312 {
14313 key: "processor",
14314 get: function get() {
14315 return this.result.processor;
14316 }
14317 },
14318 {
14319 key: "root",
14320 get: function get() {
14321 return this.sync().root;
14322 }
14323 },
14324 {
14325 key: Symbol.toStringTag,
14326 get: function get() {
14327 return "LazyResult";
14328 }
14329 }
14330 ]);
14331 return LazyResult;
14332 }();
14333 LazyResult$2$1.registerPostcss = function(dependant) {
14334 postcss$2$1 = dependant;
14335 };
14336 var lazyResult$1 = LazyResult$2$1;
14337 LazyResult$2$1.default = LazyResult$2$1;
14338 Root$3$1.registerLazyResult(LazyResult$2$1);
14339 Document$2$1.registerLazyResult(LazyResult$2$1);
14340 var MapGenerator2$1 = mapGenerator$1;
14341 var stringify$1$1 = stringify_1$1;
14342 var warnOnce2$1 = warnOnce$2$1;
14343 var parse$1$1 = parse_1$1;
14344 var Result$1$1 = result$1;
14345 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
14346 function NoWorkResult(processor2, css, opts) {
14347 css = css.toString();
14348 this.stringified = false;
14349 this._processor = processor2;
14350 this._css = css;
14351 this._opts = opts;
14352 this._map = void 0;
14353 var root2;
14354 var str = stringify$1$1;
14355 this.result = new Result$1$1(this._processor, root2, this._opts);
14356 this.result.css = css;
14357 var self = this;
14358 Object.defineProperty(this.result, "root", {
14359 get: function get() {
14360 return self.root;
14361 }
14362 });
14363 var map = new MapGenerator2$1(str, root2, this._opts, css);
14364 if (map.isMap()) {
14365 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
14366 if (generatedCSS) {
14367 this.result.css = generatedCSS;
14368 }
14369 if (generatedMap) {
14370 this.result.map = generatedMap;
14371 }
14372 } else {
14373 map.clearAnnotation();
14374 this.result.css = map.css;
14375 }
14376 }
14377 var _proto = NoWorkResult.prototype;
14378 _proto.async = function async() {
14379 if (this.error) return Promise.reject(this.error);
14380 return Promise.resolve(this.result);
14381 };
14382 _proto.catch = function _catch(onRejected) {
14383 return this.async().catch(onRejected);
14384 };
14385 _proto.finally = function _finally(onFinally) {
14386 return this.async().then(onFinally, onFinally);
14387 };
14388 _proto.sync = function sync() {
14389 if (this.error) throw this.error;
14390 return this.result;
14391 };
14392 _proto.then = function then(onFulfilled, onRejected) {
14393 if (true) {
14394 if (!("from" in this._opts)) {
14395 warnOnce2$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
14396 }
14397 }
14398 return this.async().then(onFulfilled, onRejected);
14399 };
14400 _proto.toString = function toString() {
14401 return this._css;
14402 };
14403 _proto.warnings = function warnings() {
14404 return [];
14405 };
14406 _create_class(NoWorkResult, [
14407 {
14408 key: "content",
14409 get: function get() {
14410 return this.result.css;
14411 }
14412 },
14413 {
14414 key: "css",
14415 get: function get() {
14416 return this.result.css;
14417 }
14418 },
14419 {
14420 key: "map",
14421 get: function get() {
14422 return this.result.map;
14423 }
14424 },
14425 {
14426 key: "messages",
14427 get: function get() {
14428 return [];
14429 }
14430 },
14431 {
14432 key: "opts",
14433 get: function get() {
14434 return this.result.opts;
14435 }
14436 },
14437 {
14438 key: "processor",
14439 get: function get() {
14440 return this.result.processor;
14441 }
14442 },
14443 {
14444 key: "root",
14445 get: function get() {
14446 if (this._root) {
14447 return this._root;
14448 }
14449 var root2;
14450 var parser2 = parse$1$1;
14451 try {
14452 root2 = parser2(this._css, this._opts);
14453 } catch (error) {
14454 this.error = error;
14455 }
14456 if (this.error) {
14457 throw this.error;
14458 } else {
14459 this._root = root2;
14460 return root2;
14461 }
14462 }
14463 },
14464 {
14465 key: Symbol.toStringTag,
14466 get: function get() {
14467 return "NoWorkResult";
14468 }
14469 }
14470 ]);
14471 return NoWorkResult;
14472 }();
14473 var noWorkResult$1 = NoWorkResult$1$1;
14474 NoWorkResult$1$1.default = NoWorkResult$1$1;
14475 var NoWorkResult2$1 = noWorkResult$1;
14476 var LazyResult$1$1 = lazyResult$1;
14477 var Document$1$1 = document$1$1;
14478 var Root$2$1 = root$1;
14479 var Processor$1$1 = /*#__PURE__*/ function() {
14480 function Processor(plugins) {
14481 if (plugins === void 0) plugins = [];
14482 this.version = "8.4.38";
14483 this.plugins = this.normalize(plugins);
14484 }
14485 var _proto = Processor.prototype;
14486 _proto.normalize = function normalize(plugins) {
14487 var normalized = [];
14488 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
14489 var i2 = _step.value;
14490 if (i2.postcss === true) {
14491 i2 = i2();
14492 } else if (i2.postcss) {
14493 i2 = i2.postcss;
14494 }
14495 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
14496 normalized = normalized.concat(i2.plugins);
14497 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
14498 normalized.push(i2);
14499 } else if (typeof i2 === "function") {
14500 normalized.push(i2);
14501 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
14502 if (true) {
14503 throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.");
14504 }
14505 } else {
14506 throw new Error(i2 + " is not a PostCSS plugin");
14507 }
14508 }
14509 return normalized;
14510 };
14511 _proto.process = function process1(css, opts) {
14512 if (opts === void 0) opts = {};
14513 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
14514 return new NoWorkResult2$1(this, css, opts);
14515 } else {
14516 return new LazyResult$1$1(this, css, opts);
14517 }
14518 };
14519 _proto.use = function use(plugin22) {
14520 this.plugins = this.plugins.concat(this.normalize([
14521 plugin22
14522 ]));
14523 return this;
14524 };
14525 return Processor;
14526 }();
14527 var processor$1 = Processor$1$1;
14528 Processor$1$1.default = Processor$1$1;
14529 Root$2$1.registerProcessor(Processor$1$1);
14530 Document$1$1.registerProcessor(Processor$1$1);
14531 var Declaration$1$1 = declaration$1;
14532 var PreviousMap2$1 = previousMap$1;
14533 var Comment$1$1 = comment$1;
14534 var AtRule$1$1 = atRule$1;
14535 var Input$1$1 = input$1;
14536 var Root$1$1 = root$1;
14537 var Rule$1$1 = rule$1;
14538 function fromJSON$1$1(json, inputs) {
14539 if (Array.isArray(json)) return json.map(function(n2) {
14540 return fromJSON$1$1(n2);
14541 });
14542 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
14543 "inputs"
14544 ]);
14545 if (ownInputs) {
14546 inputs = [];
14547 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
14548 var input2 = _step.value;
14549 var inputHydrated = _extends({}, input2, {
14550 __proto__: Input$1$1.prototype
14551 });
14552 if (inputHydrated.map) {
14553 inputHydrated.map = _extends({}, inputHydrated.map, {
14554 __proto__: PreviousMap2$1.prototype
14555 });
14556 }
14557 inputs.push(inputHydrated);
14558 }
14559 }
14560 if (defaults.nodes) {
14561 defaults.nodes = json.nodes.map(function(n2) {
14562 return fromJSON$1$1(n2, inputs);
14563 });
14564 }
14565 if (defaults.source) {
14566 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
14567 "inputId"
14568 ]);
14569 defaults.source = source;
14570 if (inputId != null) {
14571 defaults.source.input = inputs[inputId];
14572 }
14573 }
14574 if (defaults.type === "root") {
14575 return new Root$1$1(defaults);
14576 } else if (defaults.type === "decl") {
14577 return new Declaration$1$1(defaults);
14578 } else if (defaults.type === "rule") {
14579 return new Rule$1$1(defaults);
14580 } else if (defaults.type === "comment") {
14581 return new Comment$1$1(defaults);
14582 } else if (defaults.type === "atrule") {
14583 return new AtRule$1$1(defaults);
14584 } else {
14585 throw new Error("Unknown node type: " + json.type);
14586 }
14587 }
14588 var fromJSON_1$1 = fromJSON$1$1;
14589 fromJSON$1$1.default = fromJSON$1$1;
14590 var CssSyntaxError2$1 = cssSyntaxError$1;
14591 var Declaration2$1 = declaration$1;
14592 var LazyResult2$1 = lazyResult$1;
14593 var Container2$1 = container$1;
14594 var Processor2$1 = processor$1;
14595 var stringify$5 = stringify_1$1;
14596 var fromJSON$2 = fromJSON_1$1;
14597 var Document22 = document$1$1;
14598 var Warning2$1 = warning$1;
14599 var Comment2$1 = comment$1;
14600 var AtRule2$1 = atRule$1;
14601 var Result2$1 = result$1;
14602 var Input2$1 = input$1;
14603 var parse$5 = parse_1$1;
14604 var list$3 = list_1$1;
14605 var Rule2$1 = rule$1;
14606 var Root2$1 = root$1;
14607 var Node2$1 = node$1;
14608 function postcss$3() {
14609 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
14610 plugins[_key] = arguments[_key];
14611 }
14612 if (plugins.length === 1 && Array.isArray(plugins[0])) {
14613 plugins = plugins[0];
14614 }
14615 return new Processor2$1(plugins);
14616 }
14617 postcss$3.plugin = function plugin(name, initializer) {
14618 var warningPrinted = false;
14619 function creator() {
14620 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
14621 args[_key] = arguments[_key];
14622 }
14623 if (console && console.warn && !warningPrinted) {
14624 warningPrinted = true;
14625 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
14626 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
14627 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
14628 }
14629 }
14630 var transformer = initializer.apply(void 0, [].concat(args));
14631 transformer.postcssPlugin = name;
14632 transformer.postcssVersion = new Processor2$1().version;
14633 return transformer;
14634 }
14635 var cache;
14636 Object.defineProperty(creator, "postcss", {
14637 get: function get() {
14638 if (!cache) cache = creator();
14639 return cache;
14640 }
14641 });
14642 creator.process = function(css, processOpts, pluginOpts) {
14643 return postcss$3([
14644 creator(pluginOpts)
14645 ]).process(css, processOpts);
14646 };
14647 return creator;
14648 };
14649 postcss$3.stringify = stringify$5;
14650 postcss$3.parse = parse$5;
14651 postcss$3.fromJSON = fromJSON$2;
14652 postcss$3.list = list$3;
14653 postcss$3.comment = function(defaults) {
14654 return new Comment2$1(defaults);
14655 };
14656 postcss$3.atRule = function(defaults) {
14657 return new AtRule2$1(defaults);
14658 };
14659 postcss$3.decl = function(defaults) {
14660 return new Declaration2$1(defaults);
14661 };
14662 postcss$3.rule = function(defaults) {
14663 return new Rule2$1(defaults);
14664 };
14665 postcss$3.root = function(defaults) {
14666 return new Root2$1(defaults);
14667 };
14668 postcss$3.document = function(defaults) {
14669 return new Document22(defaults);
14670 };
14671 postcss$3.CssSyntaxError = CssSyntaxError2$1;
14672 postcss$3.Declaration = Declaration2$1;
14673 postcss$3.Container = Container2$1;
14674 postcss$3.Processor = Processor2$1;
14675 postcss$3.Document = Document22;
14676 postcss$3.Comment = Comment2$1;
14677 postcss$3.Warning = Warning2$1;
14678 postcss$3.AtRule = AtRule2$1;
14679 postcss$3.Result = Result2$1;
14680 postcss$3.Input = Input2$1;
14681 postcss$3.Rule = Rule2$1;
14682 postcss$3.Root = Root2$1;
14683 postcss$3.Node = Node2$1;
14684 LazyResult2$1.registerPostcss(postcss$3);
14685 var postcss_1$1 = postcss$3;
14686 postcss$3.default = postcss$3;
14687 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
14688 postcss$1$1.stringify;
14689 postcss$1$1.fromJSON;
14690 postcss$1$1.plugin;
14691 postcss$1$1.parse;
14692 postcss$1$1.list;
14693 postcss$1$1.document;
14694 postcss$1$1.comment;
14695 postcss$1$1.atRule;
14696 postcss$1$1.rule;
14697 postcss$1$1.decl;
14698 postcss$1$1.root;
14699 postcss$1$1.CssSyntaxError;
14700 postcss$1$1.Declaration;
14701 postcss$1$1.Container;
14702 postcss$1$1.Processor;
14703 postcss$1$1.Document;
14704 postcss$1$1.Comment;
14705 postcss$1$1.Warning;
14706 postcss$1$1.AtRule;
14707 postcss$1$1.Result;
14708 postcss$1$1.Input;
14709 postcss$1$1.Rule;
14710 postcss$1$1.Root;
14711 postcss$1$1.Node;
14712 var __defProp2 = Object.defineProperty;
14713 var __defNormalProp2 = function(obj, key, value) {
14714 return key in obj ? __defProp2(obj, key, {
14715 enumerable: true,
14716 configurable: true,
14717 writable: true,
14718 value: value
14719 }) : obj[key] = value;
14720 };
14721 var __publicField2 = function(obj, key, value) {
14722 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
14723 };
14724 function getDefaultExportFromCjs(x2) {
14725 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
14726 }
14727 function getAugmentedNamespace(n2) {
14728 if (n2.__esModule) return n2;
14729 var f2 = n2.default;
14730 if (typeof f2 == "function") {
14731 var a2 = function a22() {
14732 if (_instanceof(this, a22)) {
14733 return Reflect.construct(f2, arguments, this.constructor);
14734 }
14735 return f2.apply(this, arguments);
14736 };
14737 a2.prototype = f2.prototype;
14738 } else a2 = {};
14739 Object.defineProperty(a2, "__esModule", {
14740 value: true
14741 });
14742 Object.keys(n2).forEach(function(k) {
14743 var d = Object.getOwnPropertyDescriptor(n2, k);
14744 Object.defineProperty(a2, k, d.get ? d : {
14745 enumerable: true,
14746 get: function get() {
14747 return n2[k];
14748 }
14749 });
14750 });
14751 return a2;
14752 }
14753 var picocolors_browser = {
14754 exports: {}
14755 };
14756 var x = String;
14757 var create = function create() {
14758 return {
14759 isColorSupported: false,
14760 reset: x,
14761 bold: x,
14762 dim: x,
14763 italic: x,
14764 underline: x,
14765 inverse: x,
14766 hidden: x,
14767 strikethrough: x,
14768 black: x,
14769 red: x,
14770 green: x,
14771 yellow: x,
14772 blue: x,
14773 magenta: x,
14774 cyan: x,
14775 white: x,
14776 gray: x,
14777 bgBlack: x,
14778 bgRed: x,
14779 bgGreen: x,
14780 bgYellow: x,
14781 bgBlue: x,
14782 bgMagenta: x,
14783 bgCyan: x,
14784 bgWhite: x
14785 };
14786 };
14787 picocolors_browser.exports = create();
14788 picocolors_browser.exports.createColors = create;
14789 var picocolors_browserExports = picocolors_browser.exports;
14790 var __viteBrowserExternal = {};
14791 var __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
14792 __proto__: null,
14793 default: __viteBrowserExternal
14794 }, Symbol.toStringTag, {
14795 value: "Module"
14796 }));
14797 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
14798 var pico = picocolors_browserExports;
14799 var terminalHighlight$1 = require$$2;
14800 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
14801 _inherits(CssSyntaxError2, Error1);
14802 function CssSyntaxError2(message, line, column, source, file, plugin22) {
14803 var _this;
14804 _this = Error1.call(this, message) || this;
14805 _this.name = "CssSyntaxError";
14806 _this.reason = message;
14807 if (file) {
14808 _this.file = file;
14809 }
14810 if (source) {
14811 _this.source = source;
14812 }
14813 if (plugin22) {
14814 _this.plugin = plugin22;
14815 }
14816 if (typeof line !== "undefined" && typeof column !== "undefined") {
14817 if (typeof line === "number") {
14818 _this.line = line;
14819 _this.column = column;
14820 } else {
14821 _this.line = line.line;
14822 _this.column = line.column;
14823 _this.endLine = column.line;
14824 _this.endColumn = column.column;
14825 }
14826 }
14827 _this.setMessage();
14828 if (Error.captureStackTrace) {
14829 Error.captureStackTrace(_this, CssSyntaxError2);
14830 }
14831 return _this;
14832 }
14833 var _proto = CssSyntaxError2.prototype;
14834 _proto.setMessage = function setMessage() {
14835 this.message = this.plugin ? this.plugin + ": " : "";
14836 this.message += this.file ? this.file : "<css input>";
14837 if (typeof this.line !== "undefined") {
14838 this.message += ":" + this.line + ":" + this.column;
14839 }
14840 this.message += ": " + this.reason;
14841 };
14842 _proto.showSourceCode = function showSourceCode(color) {
14843 var _this = this;
14844 if (!this.source) return "";
14845 var css = this.source;
14846 if (color == null) color = pico.isColorSupported;
14847 if (terminalHighlight$1) {
14848 if (color) css = terminalHighlight$1(css);
14849 }
14850 var lines = css.split(/\r?\n/);
14851 var start = Math.max(this.line - 3, 0);
14852 var end = Math.min(this.line + 2, lines.length);
14853 var maxWidth = String(end).length;
14854 var mark, aside;
14855 if (color) {
14856 var _pico_createColors = pico.createColors(true), bold = _pico_createColors.bold, gray = _pico_createColors.gray, red = _pico_createColors.red;
14857 mark = function(text) {
14858 return bold(red(text));
14859 };
14860 aside = function(text) {
14861 return gray(text);
14862 };
14863 } else {
14864 mark = aside = function(str) {
14865 return str;
14866 };
14867 }
14868 return lines.slice(start, end).map(function(line, index2) {
14869 var number = start + 1 + index2;
14870 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
14871 if (number === _this.line) {
14872 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
14873 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
14874 }
14875 return " " + aside(gutter) + line;
14876 }).join("\n");
14877 };
14878 _proto.toString = function toString() {
14879 var code = this.showSourceCode();
14880 if (code) {
14881 code = "\n\n" + code + "\n";
14882 }
14883 return this.name + ": " + this.message + code;
14884 };
14885 return CssSyntaxError2;
14886 }(_wrap_native_super(Error));
14887 var cssSyntaxError = CssSyntaxError$3;
14888 CssSyntaxError$3.default = CssSyntaxError$3;
14889 var symbols = {};
14890 symbols.isClean = Symbol("isClean");
14891 symbols.my = Symbol("my");
14892 var DEFAULT_RAW = {
14893 after: "\n",
14894 beforeClose: "\n",
14895 beforeComment: "\n",
14896 beforeDecl: "\n",
14897 beforeOpen: " ",
14898 beforeRule: "\n",
14899 colon: ": ",
14900 commentLeft: " ",
14901 commentRight: " ",
14902 emptyBody: "",
14903 indent: " ",
14904 semicolon: false
14905 };
14906 function capitalize(str) {
14907 return str[0].toUpperCase() + str.slice(1);
14908 }
14909 var Stringifier$2 = /*#__PURE__*/ function() {
14910 function Stringifier2(builder) {
14911 this.builder = builder;
14912 }
14913 var _proto = Stringifier2.prototype;
14914 _proto.atrule = function atrule(node2, semicolon) {
14915 var name = "@" + node2.name;
14916 var params = node2.params ? this.rawValue(node2, "params") : "";
14917 if (typeof node2.raws.afterName !== "undefined") {
14918 name += node2.raws.afterName;
14919 } else if (params) {
14920 name += " ";
14921 }
14922 if (node2.nodes) {
14923 this.block(node2, name + params);
14924 } else {
14925 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
14926 this.builder(name + params + end, node2);
14927 }
14928 };
14929 _proto.beforeAfter = function beforeAfter(node2, detect) {
14930 var value;
14931 if (node2.type === "decl") {
14932 value = this.raw(node2, null, "beforeDecl");
14933 } else if (node2.type === "comment") {
14934 value = this.raw(node2, null, "beforeComment");
14935 } else if (detect === "before") {
14936 value = this.raw(node2, null, "beforeRule");
14937 } else {
14938 value = this.raw(node2, null, "beforeClose");
14939 }
14940 var buf = node2.parent;
14941 var depth = 0;
14942 while(buf && buf.type !== "root"){
14943 depth += 1;
14944 buf = buf.parent;
14945 }
14946 if (value.includes("\n")) {
14947 var indent = this.raw(node2, null, "indent");
14948 if (indent.length) {
14949 for(var step = 0; step < depth; step++)value += indent;
14950 }
14951 }
14952 return value;
14953 };
14954 _proto.block = function block(node2, start) {
14955 var between = this.raw(node2, "between", "beforeOpen");
14956 this.builder(start + between + "{", node2, "start");
14957 var after;
14958 if (node2.nodes && node2.nodes.length) {
14959 this.body(node2);
14960 after = this.raw(node2, "after");
14961 } else {
14962 after = this.raw(node2, "after", "emptyBody");
14963 }
14964 if (after) this.builder(after);
14965 this.builder("}", node2, "end");
14966 };
14967 _proto.body = function body(node2) {
14968 var last = node2.nodes.length - 1;
14969 while(last > 0){
14970 if (node2.nodes[last].type !== "comment") break;
14971 last -= 1;
14972 }
14973 var semicolon = this.raw(node2, "semicolon");
14974 for(var i2 = 0; i2 < node2.nodes.length; i2++){
14975 var child = node2.nodes[i2];
14976 var before = this.raw(child, "before");
14977 if (before) this.builder(before);
14978 this.stringify(child, last !== i2 || semicolon);
14979 }
14980 };
14981 _proto.comment = function comment(node2) {
14982 var left = this.raw(node2, "left", "commentLeft");
14983 var right = this.raw(node2, "right", "commentRight");
14984 this.builder("/*" + left + node2.text + right + "*/", node2);
14985 };
14986 _proto.decl = function decl(node2, semicolon) {
14987 var between = this.raw(node2, "between", "colon");
14988 var string = node2.prop + between + this.rawValue(node2, "value");
14989 if (node2.important) {
14990 string += node2.raws.important || " !important";
14991 }
14992 if (semicolon) string += ";";
14993 this.builder(string, node2);
14994 };
14995 _proto.document = function document1(node2) {
14996 this.body(node2);
14997 };
14998 _proto.raw = function raw(node2, own, detect) {
14999 var value;
15000 if (!detect) detect = own;
15001 if (own) {
15002 value = node2.raws[own];
15003 if (typeof value !== "undefined") return value;
15004 }
15005 var parent = node2.parent;
15006 if (detect === "before") {
15007 if (!parent || parent.type === "root" && parent.first === node2) {
15008 return "";
15009 }
15010 if (parent && parent.type === "document") {
15011 return "";
15012 }
15013 }
15014 if (!parent) return DEFAULT_RAW[detect];
15015 var root2 = node2.root();
15016 if (!root2.rawCache) root2.rawCache = {};
15017 if (typeof root2.rawCache[detect] !== "undefined") {
15018 return root2.rawCache[detect];
15019 }
15020 if (detect === "before" || detect === "after") {
15021 return this.beforeAfter(node2, detect);
15022 } else {
15023 var method = "raw" + capitalize(detect);
15024 if (this[method]) {
15025 value = this[method](root2, node2);
15026 } else {
15027 root2.walk(function(i2) {
15028 value = i2.raws[own];
15029 if (typeof value !== "undefined") return false;
15030 });
15031 }
15032 }
15033 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
15034 root2.rawCache[detect] = value;
15035 return value;
15036 };
15037 _proto.rawBeforeClose = function rawBeforeClose(root2) {
15038 var value;
15039 root2.walk(function(i2) {
15040 if (i2.nodes && i2.nodes.length > 0) {
15041 if (typeof i2.raws.after !== "undefined") {
15042 value = i2.raws.after;
15043 if (value.includes("\n")) {
15044 value = value.replace(/[^\n]+$/, "");
15045 }
15046 return false;
15047 }
15048 }
15049 });
15050 if (value) value = value.replace(/\S/g, "");
15051 return value;
15052 };
15053 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
15054 var value;
15055 root2.walkComments(function(i2) {
15056 if (typeof i2.raws.before !== "undefined") {
15057 value = i2.raws.before;
15058 if (value.includes("\n")) {
15059 value = value.replace(/[^\n]+$/, "");
15060 }
15061 return false;
15062 }
15063 });
15064 if (typeof value === "undefined") {
15065 value = this.raw(node2, null, "beforeDecl");
15066 } else if (value) {
15067 value = value.replace(/\S/g, "");
15068 }
15069 return value;
15070 };
15071 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
15072 var value;
15073 root2.walkDecls(function(i2) {
15074 if (typeof i2.raws.before !== "undefined") {
15075 value = i2.raws.before;
15076 if (value.includes("\n")) {
15077 value = value.replace(/[^\n]+$/, "");
15078 }
15079 return false;
15080 }
15081 });
15082 if (typeof value === "undefined") {
15083 value = this.raw(node2, null, "beforeRule");
15084 } else if (value) {
15085 value = value.replace(/\S/g, "");
15086 }
15087 return value;
15088 };
15089 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
15090 var value;
15091 root2.walk(function(i2) {
15092 if (i2.type !== "decl") {
15093 value = i2.raws.between;
15094 if (typeof value !== "undefined") return false;
15095 }
15096 });
15097 return value;
15098 };
15099 _proto.rawBeforeRule = function rawBeforeRule(root2) {
15100 var value;
15101 root2.walk(function(i2) {
15102 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
15103 if (typeof i2.raws.before !== "undefined") {
15104 value = i2.raws.before;
15105 if (value.includes("\n")) {
15106 value = value.replace(/[^\n]+$/, "");
15107 }
15108 return false;
15109 }
15110 }
15111 });
15112 if (value) value = value.replace(/\S/g, "");
15113 return value;
15114 };
15115 _proto.rawColon = function rawColon(root2) {
15116 var value;
15117 root2.walkDecls(function(i2) {
15118 if (typeof i2.raws.between !== "undefined") {
15119 value = i2.raws.between.replace(/[^\s:]/g, "");
15120 return false;
15121 }
15122 });
15123 return value;
15124 };
15125 _proto.rawEmptyBody = function rawEmptyBody(root2) {
15126 var value;
15127 root2.walk(function(i2) {
15128 if (i2.nodes && i2.nodes.length === 0) {
15129 value = i2.raws.after;
15130 if (typeof value !== "undefined") return false;
15131 }
15132 });
15133 return value;
15134 };
15135 _proto.rawIndent = function rawIndent(root2) {
15136 if (root2.raws.indent) return root2.raws.indent;
15137 var value;
15138 root2.walk(function(i2) {
15139 var p = i2.parent;
15140 if (p && p !== root2 && p.parent && p.parent === root2) {
15141 if (typeof i2.raws.before !== "undefined") {
15142 var parts = i2.raws.before.split("\n");
15143 value = parts[parts.length - 1];
15144 value = value.replace(/\S/g, "");
15145 return false;
15146 }
15147 }
15148 });
15149 return value;
15150 };
15151 _proto.rawSemicolon = function rawSemicolon(root2) {
15152 var value;
15153 root2.walk(function(i2) {
15154 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
15155 value = i2.raws.semicolon;
15156 if (typeof value !== "undefined") return false;
15157 }
15158 });
15159 return value;
15160 };
15161 _proto.rawValue = function rawValue(node2, prop) {
15162 var value = node2[prop];
15163 var raw = node2.raws[prop];
15164 if (raw && raw.value === value) {
15165 return raw.raw;
15166 }
15167 return value;
15168 };
15169 _proto.root = function root(node2) {
15170 this.body(node2);
15171 if (node2.raws.after) this.builder(node2.raws.after);
15172 };
15173 _proto.rule = function rule(node2) {
15174 this.block(node2, this.rawValue(node2, "selector"));
15175 if (node2.raws.ownSemicolon) {
15176 this.builder(node2.raws.ownSemicolon, node2, "end");
15177 }
15178 };
15179 _proto.stringify = function stringify(node2, semicolon) {
15180 if (!this[node2.type]) {
15181 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
15182 }
15183 this[node2.type](node2, semicolon);
15184 };
15185 return Stringifier2;
15186 }();
15187 var stringifier = Stringifier$2;
15188 Stringifier$2.default = Stringifier$2;
15189 var Stringifier$1 = stringifier;
15190 function stringify$4(node2, builder) {
15191 var str = new Stringifier$1(builder);
15192 str.stringify(node2);
15193 }
15194 var stringify_1 = stringify$4;
15195 stringify$4.default = stringify$4;
15196 var isClean$2 = symbols.isClean, my$2 = symbols.my;
15197 var CssSyntaxError$2 = cssSyntaxError;
15198 var Stringifier22 = stringifier;
15199 var stringify$3 = stringify_1;
15200 function cloneNode(obj, parent) {
15201 var cloned = new obj.constructor();
15202 for(var i2 in obj){
15203 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
15204 continue;
15205 }
15206 if (i2 === "proxyCache") continue;
15207 var value = obj[i2];
15208 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
15209 if (i2 === "parent" && type === "object") {
15210 if (parent) cloned[i2] = parent;
15211 } else if (i2 === "source") {
15212 cloned[i2] = value;
15213 } else if (Array.isArray(value)) {
15214 cloned[i2] = value.map(function(j) {
15215 return cloneNode(j, cloned);
15216 });
15217 } else {
15218 if (type === "object" && value !== null) value = cloneNode(value);
15219 cloned[i2] = value;
15220 }
15221 }
15222 return cloned;
15223 }
15224 var Node$4 = /*#__PURE__*/ function() {
15225 function Node3(defaults) {
15226 if (defaults === void 0) defaults = {};
15227 this.raws = {};
15228 this[isClean$2] = false;
15229 this[my$2] = true;
15230 for(var name in defaults){
15231 if (name === "nodes") {
15232 this.nodes = [];
15233 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
15234 var node2 = _step.value;
15235 if (typeof node2.clone === "function") {
15236 this.append(node2.clone());
15237 } else {
15238 this.append(node2);
15239 }
15240 }
15241 } else {
15242 this[name] = defaults[name];
15243 }
15244 }
15245 }
15246 var _proto = Node3.prototype;
15247 _proto.addToError = function addToError(error) {
15248 error.postcssNode = this;
15249 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
15250 var s2 = this.source;
15251 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
15252 }
15253 return error;
15254 };
15255 _proto.after = function after(add) {
15256 this.parent.insertAfter(this, add);
15257 return this;
15258 };
15259 _proto.assign = function assign(overrides) {
15260 if (overrides === void 0) overrides = {};
15261 for(var name in overrides){
15262 this[name] = overrides[name];
15263 }
15264 return this;
15265 };
15266 _proto.before = function before(add) {
15267 this.parent.insertBefore(this, add);
15268 return this;
15269 };
15270 _proto.cleanRaws = function cleanRaws(keepBetween) {
15271 delete this.raws.before;
15272 delete this.raws.after;
15273 if (!keepBetween) delete this.raws.between;
15274 };
15275 _proto.clone = function clone(overrides) {
15276 if (overrides === void 0) overrides = {};
15277 var cloned = cloneNode(this);
15278 for(var name in overrides){
15279 cloned[name] = overrides[name];
15280 }
15281 return cloned;
15282 };
15283 _proto.cloneAfter = function cloneAfter(overrides) {
15284 if (overrides === void 0) overrides = {};
15285 var cloned = this.clone(overrides);
15286 this.parent.insertAfter(this, cloned);
15287 return cloned;
15288 };
15289 _proto.cloneBefore = function cloneBefore(overrides) {
15290 if (overrides === void 0) overrides = {};
15291 var cloned = this.clone(overrides);
15292 this.parent.insertBefore(this, cloned);
15293 return cloned;
15294 };
15295 _proto.error = function error(message, opts) {
15296 if (opts === void 0) opts = {};
15297 if (this.source) {
15298 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
15299 return this.source.input.error(message, {
15300 column: start.column,
15301 line: start.line
15302 }, {
15303 column: end.column,
15304 line: end.line
15305 }, opts);
15306 }
15307 return new CssSyntaxError$2(message);
15308 };
15309 _proto.getProxyProcessor = function getProxyProcessor() {
15310 return {
15311 get: function get(node2, prop) {
15312 if (prop === "proxyOf") {
15313 return node2;
15314 } else if (prop === "root") {
15315 return function() {
15316 return node2.root().toProxy();
15317 };
15318 } else {
15319 return node2[prop];
15320 }
15321 },
15322 set: function set(node2, prop, value) {
15323 if (node2[prop] === value) return true;
15324 node2[prop] = value;
15325 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
15326 node2.markDirty();
15327 }
15328 return true;
15329 }
15330 };
15331 };
15332 _proto.markDirty = function markDirty() {
15333 if (this[isClean$2]) {
15334 this[isClean$2] = false;
15335 var next = this;
15336 while(next = next.parent){
15337 next[isClean$2] = false;
15338 }
15339 }
15340 };
15341 _proto.next = function next() {
15342 if (!this.parent) return void 0;
15343 var index2 = this.parent.index(this);
15344 return this.parent.nodes[index2 + 1];
15345 };
15346 _proto.positionBy = function positionBy(opts, stringRepresentation) {
15347 var pos = this.source.start;
15348 if (opts.index) {
15349 pos = this.positionInside(opts.index, stringRepresentation);
15350 } else if (opts.word) {
15351 stringRepresentation = this.toString();
15352 var index2 = stringRepresentation.indexOf(opts.word);
15353 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
15354 }
15355 return pos;
15356 };
15357 _proto.positionInside = function positionInside(index2, stringRepresentation) {
15358 var string = stringRepresentation || this.toString();
15359 var column = this.source.start.column;
15360 var line = this.source.start.line;
15361 for(var i2 = 0; i2 < index2; i2++){
15362 if (string[i2] === "\n") {
15363 column = 1;
15364 line += 1;
15365 } else {
15366 column += 1;
15367 }
15368 }
15369 return {
15370 column: column,
15371 line: line
15372 };
15373 };
15374 _proto.prev = function prev() {
15375 if (!this.parent) return void 0;
15376 var index2 = this.parent.index(this);
15377 return this.parent.nodes[index2 - 1];
15378 };
15379 _proto.rangeBy = function rangeBy(opts) {
15380 var start = {
15381 column: this.source.start.column,
15382 line: this.source.start.line
15383 };
15384 var end = this.source.end ? {
15385 column: this.source.end.column + 1,
15386 line: this.source.end.line
15387 } : {
15388 column: start.column + 1,
15389 line: start.line
15390 };
15391 if (opts.word) {
15392 var stringRepresentation = this.toString();
15393 var index2 = stringRepresentation.indexOf(opts.word);
15394 if (index2 !== -1) {
15395 start = this.positionInside(index2, stringRepresentation);
15396 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
15397 }
15398 } else {
15399 if (opts.start) {
15400 start = {
15401 column: opts.start.column,
15402 line: opts.start.line
15403 };
15404 } else if (opts.index) {
15405 start = this.positionInside(opts.index);
15406 }
15407 if (opts.end) {
15408 end = {
15409 column: opts.end.column,
15410 line: opts.end.line
15411 };
15412 } else if (typeof opts.endIndex === "number") {
15413 end = this.positionInside(opts.endIndex);
15414 } else if (opts.index) {
15415 end = this.positionInside(opts.index + 1);
15416 }
15417 }
15418 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
15419 end = {
15420 column: start.column + 1,
15421 line: start.line
15422 };
15423 }
15424 return {
15425 end: end,
15426 start: start
15427 };
15428 };
15429 _proto.raw = function raw(prop, defaultType) {
15430 var str = new Stringifier22();
15431 return str.raw(this, prop, defaultType);
15432 };
15433 _proto.remove = function remove() {
15434 if (this.parent) {
15435 this.parent.removeChild(this);
15436 }
15437 this.parent = void 0;
15438 return this;
15439 };
15440 _proto.replaceWith = function replaceWith() {
15441 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
15442 nodes[_key] = arguments[_key];
15443 }
15444 if (this.parent) {
15445 var bookmark = this;
15446 var foundSelf = false;
15447 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
15448 var node2 = _step.value;
15449 if (node2 === this) {
15450 foundSelf = true;
15451 } else if (foundSelf) {
15452 this.parent.insertAfter(bookmark, node2);
15453 bookmark = node2;
15454 } else {
15455 this.parent.insertBefore(bookmark, node2);
15456 }
15457 }
15458 if (!foundSelf) {
15459 this.remove();
15460 }
15461 }
15462 return this;
15463 };
15464 _proto.root = function root() {
15465 var result2 = this;
15466 while(result2.parent && result2.parent.type !== "document"){
15467 result2 = result2.parent;
15468 }
15469 return result2;
15470 };
15471 _proto.toJSON = function toJSON(_, inputs) {
15472 var fixed = {};
15473 var emitInputs = inputs == null;
15474 inputs = inputs || /* @__PURE__ */ new Map();
15475 var inputsNextIndex = 0;
15476 for(var name in this){
15477 if (!Object.prototype.hasOwnProperty.call(this, name)) {
15478 continue;
15479 }
15480 if (name === "parent" || name === "proxyCache") continue;
15481 var value = this[name];
15482 if (Array.isArray(value)) {
15483 fixed[name] = value.map(function(i2) {
15484 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
15485 return i2.toJSON(null, inputs);
15486 } else {
15487 return i2;
15488 }
15489 });
15490 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
15491 fixed[name] = value.toJSON(null, inputs);
15492 } else if (name === "source") {
15493 var inputId = inputs.get(value.input);
15494 if (inputId == null) {
15495 inputId = inputsNextIndex;
15496 inputs.set(value.input, inputsNextIndex);
15497 inputsNextIndex++;
15498 }
15499 fixed[name] = {
15500 end: value.end,
15501 inputId: inputId,
15502 start: value.start
15503 };
15504 } else {
15505 fixed[name] = value;
15506 }
15507 }
15508 if (emitInputs) {
15509 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
15510 return input2.toJSON();
15511 });
15512 }
15513 return fixed;
15514 };
15515 _proto.toProxy = function toProxy() {
15516 if (!this.proxyCache) {
15517 this.proxyCache = new Proxy(this, this.getProxyProcessor());
15518 }
15519 return this.proxyCache;
15520 };
15521 _proto.toString = function toString(stringifier2) {
15522 if (stringifier2 === void 0) stringifier2 = stringify$3;
15523 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
15524 var result2 = "";
15525 stringifier2(this, function(i2) {
15526 result2 += i2;
15527 });
15528 return result2;
15529 };
15530 _proto.warn = function warn(result2, text, opts) {
15531 var data = {
15532 node: this
15533 };
15534 for(var i2 in opts)data[i2] = opts[i2];
15535 return result2.warn(text, data);
15536 };
15537 _create_class(Node3, [
15538 {
15539 key: "proxyOf",
15540 get: function get() {
15541 return this;
15542 }
15543 }
15544 ]);
15545 return Node3;
15546 }();
15547 var node = Node$4;
15548 Node$4.default = Node$4;
15549 var Node$3 = node;
15550 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
15551 _inherits(Declaration2, Node$3);
15552 function Declaration2(defaults) {
15553 var _this;
15554 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
15555 defaults = _extends({}, defaults, {
15556 value: String(defaults.value)
15557 });
15558 }
15559 _this = Node$3.call(this, defaults) || this;
15560 _this.type = "decl";
15561 return _this;
15562 }
15563 _create_class(Declaration2, [
15564 {
15565 key: "variable",
15566 get: function get() {
15567 return this.prop.startsWith("--") || this.prop[0] === "$";
15568 }
15569 }
15570 ]);
15571 return Declaration2;
15572 }(Node$3);
15573 var declaration = Declaration$4;
15574 Declaration$4.default = Declaration$4;
15575 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
15576 var nanoid$1 = function(size) {
15577 if (size === void 0) size = 21;
15578 var id = "";
15579 var i2 = size;
15580 while(i2--){
15581 id += urlAlphabet[Math.random() * 64 | 0];
15582 }
15583 return id;
15584 };
15585 var nonSecure = {
15586 nanoid: nanoid$1};
15587 var SourceMapConsumer$2 = require$$2.SourceMapConsumer, SourceMapGenerator$2 = require$$2.SourceMapGenerator;
15588 var existsSync = require$$2.existsSync, readFileSync = require$$2.readFileSync;
15589 var dirname$1 = require$$2.dirname, join = require$$2.join;
15590 function fromBase64(str) {
15591 if (Buffer) {
15592 return Buffer.from(str, "base64").toString();
15593 } else {
15594 return window.atob(str);
15595 }
15596 }
15597 var PreviousMap$2 = /*#__PURE__*/ function() {
15598 function PreviousMap2(css, opts) {
15599 if (opts.map === false) return;
15600 this.loadAnnotation(css);
15601 this.inline = this.startWith(this.annotation, "data:");
15602 var prev = opts.map ? opts.map.prev : void 0;
15603 var text = this.loadMap(opts.from, prev);
15604 if (!this.mapFile && opts.from) {
15605 this.mapFile = opts.from;
15606 }
15607 if (this.mapFile) this.root = dirname$1(this.mapFile);
15608 if (text) this.text = text;
15609 }
15610 var _proto = PreviousMap2.prototype;
15611 _proto.consumer = function consumer() {
15612 if (!this.consumerCache) {
15613 this.consumerCache = new SourceMapConsumer$2(this.text);
15614 }
15615 return this.consumerCache;
15616 };
15617 _proto.decodeInline = function decodeInline(text) {
15618 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
15619 var baseUri = /^data:application\/json;base64,/;
15620 var charsetUri = /^data:application\/json;charset=utf-?8,/;
15621 var uri = /^data:application\/json,/;
15622 if (charsetUri.test(text) || uri.test(text)) {
15623 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
15624 }
15625 if (baseCharsetUri.test(text) || baseUri.test(text)) {
15626 return fromBase64(text.substr(RegExp.lastMatch.length));
15627 }
15628 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
15629 throw new Error("Unsupported source map encoding " + encoding);
15630 };
15631 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
15632 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
15633 };
15634 _proto.isMap = function isMap(map) {
15635 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
15636 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
15637 };
15638 _proto.loadAnnotation = function loadAnnotation(css) {
15639 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
15640 if (!comments) return;
15641 var start = css.lastIndexOf(comments.pop());
15642 var end = css.indexOf("*/", start);
15643 if (start > -1 && end > -1) {
15644 this.annotation = this.getAnnotationURL(css.substring(start, end));
15645 }
15646 };
15647 _proto.loadFile = function loadFile(path) {
15648 this.root = dirname$1(path);
15649 if (existsSync(path)) {
15650 this.mapFile = path;
15651 return readFileSync(path, "utf-8").toString().trim();
15652 }
15653 };
15654 _proto.loadMap = function loadMap(file, prev) {
15655 if (prev === false) return false;
15656 if (prev) {
15657 if (typeof prev === "string") {
15658 return prev;
15659 } else if (typeof prev === "function") {
15660 var prevPath = prev(file);
15661 if (prevPath) {
15662 var map = this.loadFile(prevPath);
15663 if (!map) {
15664 throw new Error("Unable to load previous source map: " + prevPath.toString());
15665 }
15666 return map;
15667 }
15668 } else if (_instanceof(prev, SourceMapConsumer$2)) {
15669 return SourceMapGenerator$2.fromSourceMap(prev).toString();
15670 } else if (_instanceof(prev, SourceMapGenerator$2)) {
15671 return prev.toString();
15672 } else if (this.isMap(prev)) {
15673 return JSON.stringify(prev);
15674 } else {
15675 throw new Error("Unsupported previous source map format: " + prev.toString());
15676 }
15677 } else if (this.inline) {
15678 return this.decodeInline(this.annotation);
15679 } else if (this.annotation) {
15680 var map1 = this.annotation;
15681 if (file) map1 = join(dirname$1(file), map1);
15682 return this.loadFile(map1);
15683 }
15684 };
15685 _proto.startWith = function startWith(string, start) {
15686 if (!string) return false;
15687 return string.substr(0, start.length) === start;
15688 };
15689 _proto.withContent = function withContent() {
15690 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
15691 };
15692 return PreviousMap2;
15693 }();
15694 var previousMap = PreviousMap$2;
15695 PreviousMap$2.default = PreviousMap$2;
15696 var SourceMapConsumer$1 = require$$2.SourceMapConsumer, SourceMapGenerator$1 = require$$2.SourceMapGenerator;
15697 var fileURLToPath = require$$2.fileURLToPath, pathToFileURL$1 = require$$2.pathToFileURL;
15698 var isAbsolute = require$$2.isAbsolute, resolve$1 = require$$2.resolve;
15699 var nanoid = nonSecure.nanoid;
15700 var terminalHighlight = require$$2;
15701 var CssSyntaxError$1 = cssSyntaxError;
15702 var PreviousMap$1 = previousMap;
15703 var fromOffsetCache = Symbol("fromOffsetCache");
15704 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
15705 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
15706 var Input$4 = /*#__PURE__*/ function() {
15707 function Input2(css, opts) {
15708 if (opts === void 0) opts = {};
15709 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
15710 throw new Error("PostCSS received " + css + " instead of CSS string");
15711 }
15712 this.css = css.toString();
15713 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
15714 this.hasBOM = true;
15715 this.css = this.css.slice(1);
15716 } else {
15717 this.hasBOM = false;
15718 }
15719 if (opts.from) {
15720 if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
15721 this.file = opts.from;
15722 } else {
15723 this.file = resolve$1(opts.from);
15724 }
15725 }
15726 if (pathAvailable$1 && sourceMapAvailable$1) {
15727 var map = new PreviousMap$1(this.css, opts);
15728 if (map.text) {
15729 this.map = map;
15730 var file = map.consumer().file;
15731 if (!this.file && file) this.file = this.mapResolve(file);
15732 }
15733 }
15734 if (!this.file) {
15735 this.id = "<input css " + nanoid(6) + ">";
15736 }
15737 if (this.map) this.map.file = this.from;
15738 }
15739 var _proto = Input2.prototype;
15740 _proto.error = function error(message, line, column, opts) {
15741 if (opts === void 0) opts = {};
15742 var result2, endLine, endColumn;
15743 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
15744 var start = line;
15745 var end = column;
15746 if (typeof start.offset === "number") {
15747 var pos = this.fromOffset(start.offset);
15748 line = pos.line;
15749 column = pos.col;
15750 } else {
15751 line = start.line;
15752 column = start.column;
15753 }
15754 if (typeof end.offset === "number") {
15755 var pos1 = this.fromOffset(end.offset);
15756 endLine = pos1.line;
15757 endColumn = pos1.col;
15758 } else {
15759 endLine = end.line;
15760 endColumn = end.column;
15761 }
15762 } else if (!column) {
15763 var pos2 = this.fromOffset(line);
15764 line = pos2.line;
15765 column = pos2.col;
15766 }
15767 var origin = this.origin(line, column, endLine, endColumn);
15768 if (origin) {
15769 result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
15770 column: origin.column,
15771 line: origin.line
15772 }, origin.endLine === void 0 ? origin.column : {
15773 column: origin.endColumn,
15774 line: origin.endLine
15775 }, origin.source, origin.file, opts.plugin);
15776 } else {
15777 result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
15778 column: column,
15779 line: line
15780 }, endLine === void 0 ? column : {
15781 column: endColumn,
15782 line: endLine
15783 }, this.css, this.file, opts.plugin);
15784 }
15785 result2.input = {
15786 column: column,
15787 endColumn: endColumn,
15788 endLine: endLine,
15789 line: line,
15790 source: this.css
15791 };
15792 if (this.file) {
15793 if (pathToFileURL$1) {
15794 result2.input.url = pathToFileURL$1(this.file).toString();
15795 }
15796 result2.input.file = this.file;
15797 }
15798 return result2;
15799 };
15800 _proto.fromOffset = function fromOffset(offset) {
15801 var lastLine, lineToIndex;
15802 if (!this[fromOffsetCache]) {
15803 var lines = this.css.split("\n");
15804 lineToIndex = new Array(lines.length);
15805 var prevIndex = 0;
15806 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
15807 lineToIndex[i2] = prevIndex;
15808 prevIndex += lines[i2].length + 1;
15809 }
15810 this[fromOffsetCache] = lineToIndex;
15811 } else {
15812 lineToIndex = this[fromOffsetCache];
15813 }
15814 lastLine = lineToIndex[lineToIndex.length - 1];
15815 var min = 0;
15816 if (offset >= lastLine) {
15817 min = lineToIndex.length - 1;
15818 } else {
15819 var max = lineToIndex.length - 2;
15820 var mid;
15821 while(min < max){
15822 mid = min + (max - min >> 1);
15823 if (offset < lineToIndex[mid]) {
15824 max = mid - 1;
15825 } else if (offset >= lineToIndex[mid + 1]) {
15826 min = mid + 1;
15827 } else {
15828 min = mid;
15829 break;
15830 }
15831 }
15832 }
15833 return {
15834 col: offset - lineToIndex[min] + 1,
15835 line: min + 1
15836 };
15837 };
15838 _proto.mapResolve = function mapResolve(file) {
15839 if (/^\w+:\/\//.test(file)) {
15840 return file;
15841 }
15842 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
15843 };
15844 _proto.origin = function origin(line, column, endLine, endColumn) {
15845 if (!this.map) return false;
15846 var consumer = this.map.consumer();
15847 var from = consumer.originalPositionFor({
15848 column: column,
15849 line: line
15850 });
15851 if (!from.source) return false;
15852 var to;
15853 if (typeof endLine === "number") {
15854 to = consumer.originalPositionFor({
15855 column: endColumn,
15856 line: endLine
15857 });
15858 }
15859 var fromUrl;
15860 if (isAbsolute(from.source)) {
15861 fromUrl = pathToFileURL$1(from.source);
15862 } else {
15863 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
15864 }
15865 var result2 = {
15866 column: from.column,
15867 endColumn: to && to.column,
15868 endLine: to && to.line,
15869 line: from.line,
15870 url: fromUrl.toString()
15871 };
15872 if (fromUrl.protocol === "file:") {
15873 if (fileURLToPath) {
15874 result2.file = fileURLToPath(fromUrl);
15875 } else {
15876 throw new Error("file: protocol is not available in this PostCSS build");
15877 }
15878 }
15879 var source = consumer.sourceContentFor(from.source);
15880 if (source) result2.source = source;
15881 return result2;
15882 };
15883 _proto.toJSON = function toJSON() {
15884 var json = {};
15885 for(var _i = 0, _iter = [
15886 "hasBOM",
15887 "css",
15888 "file",
15889 "id"
15890 ]; _i < _iter.length; _i++){
15891 var name = _iter[_i];
15892 if (this[name] != null) {
15893 json[name] = this[name];
15894 }
15895 }
15896 if (this.map) {
15897 json.map = _extends({}, this.map);
15898 if (json.map.consumerCache) {
15899 json.map.consumerCache = void 0;
15900 }
15901 }
15902 return json;
15903 };
15904 _create_class(Input2, [
15905 {
15906 key: "from",
15907 get: function get() {
15908 return this.file || this.id;
15909 }
15910 }
15911 ]);
15912 return Input2;
15913 }();
15914 var input = Input$4;
15915 Input$4.default = Input$4;
15916 if (terminalHighlight && terminalHighlight.registerInput) {
15917 terminalHighlight.registerInput(Input$4);
15918 }
15919 var SourceMapConsumer = require$$2.SourceMapConsumer, SourceMapGenerator = require$$2.SourceMapGenerator;
15920 var dirname = require$$2.dirname, relative = require$$2.relative, resolve$3 = require$$2.resolve, sep = require$$2.sep;
15921 var pathToFileURL = require$$2.pathToFileURL;
15922 var Input$3 = input;
15923 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
15924 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
15925 var MapGenerator$2 = /*#__PURE__*/ function() {
15926 function MapGenerator2(stringify2, root2, opts, cssString) {
15927 this.stringify = stringify2;
15928 this.mapOpts = opts.map || {};
15929 this.root = root2;
15930 this.opts = opts;
15931 this.css = cssString;
15932 this.originalCSS = cssString;
15933 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
15934 this.memoizedFileURLs = /* @__PURE__ */ new Map();
15935 this.memoizedPaths = /* @__PURE__ */ new Map();
15936 this.memoizedURLs = /* @__PURE__ */ new Map();
15937 }
15938 var _proto = MapGenerator2.prototype;
15939 _proto.addAnnotation = function addAnnotation() {
15940 var content;
15941 if (this.isInline()) {
15942 content = "data:application/json;base64," + this.toBase64(this.map.toString());
15943 } else if (typeof this.mapOpts.annotation === "string") {
15944 content = this.mapOpts.annotation;
15945 } else if (typeof this.mapOpts.annotation === "function") {
15946 content = this.mapOpts.annotation(this.opts.to, this.root);
15947 } else {
15948 content = this.outputFile() + ".map";
15949 }
15950 var eol = "\n";
15951 if (this.css.includes("\r\n")) eol = "\r\n";
15952 this.css += eol + "/*# sourceMappingURL=" + content + " */";
15953 };
15954 _proto.applyPrevMaps = function applyPrevMaps() {
15955 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
15956 var prev = _step.value;
15957 var from = this.toUrl(this.path(prev.file));
15958 var root2 = prev.root || dirname(prev.file);
15959 var map = void 0;
15960 if (this.mapOpts.sourcesContent === false) {
15961 map = new SourceMapConsumer(prev.text);
15962 if (map.sourcesContent) {
15963 map.sourcesContent = null;
15964 }
15965 } else {
15966 map = prev.consumer();
15967 }
15968 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
15969 }
15970 };
15971 _proto.clearAnnotation = function clearAnnotation() {
15972 if (this.mapOpts.annotation === false) return;
15973 if (this.root) {
15974 var node2;
15975 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
15976 node2 = this.root.nodes[i2];
15977 if (node2.type !== "comment") continue;
15978 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
15979 this.root.removeChild(i2);
15980 }
15981 }
15982 } else if (this.css) {
15983 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
15984 }
15985 };
15986 _proto.generate = function generate() {
15987 this.clearAnnotation();
15988 if (pathAvailable && sourceMapAvailable && this.isMap()) {
15989 return this.generateMap();
15990 } else {
15991 var result2 = "";
15992 this.stringify(this.root, function(i2) {
15993 result2 += i2;
15994 });
15995 return [
15996 result2
15997 ];
15998 }
15999 };
16000 _proto.generateMap = function generateMap() {
16001 if (this.root) {
16002 this.generateString();
16003 } else if (this.previous().length === 1) {
16004 var prev = this.previous()[0].consumer();
16005 prev.file = this.outputFile();
16006 this.map = SourceMapGenerator.fromSourceMap(prev, {
16007 ignoreInvalidMapping: true
16008 });
16009 } else {
16010 this.map = new SourceMapGenerator({
16011 file: this.outputFile(),
16012 ignoreInvalidMapping: true
16013 });
16014 this.map.addMapping({
16015 generated: {
16016 column: 0,
16017 line: 1
16018 },
16019 original: {
16020 column: 0,
16021 line: 1
16022 },
16023 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
16024 });
16025 }
16026 if (this.isSourcesContent()) this.setSourcesContent();
16027 if (this.root && this.previous().length > 0) this.applyPrevMaps();
16028 if (this.isAnnotation()) this.addAnnotation();
16029 if (this.isInline()) {
16030 return [
16031 this.css
16032 ];
16033 } else {
16034 return [
16035 this.css,
16036 this.map
16037 ];
16038 }
16039 };
16040 _proto.generateString = function generateString() {
16041 var _this = this;
16042 this.css = "";
16043 this.map = new SourceMapGenerator({
16044 file: this.outputFile(),
16045 ignoreInvalidMapping: true
16046 });
16047 var line = 1;
16048 var column = 1;
16049 var noSource = "<no source>";
16050 var mapping = {
16051 generated: {
16052 column: 0,
16053 line: 0
16054 },
16055 original: {
16056 column: 0,
16057 line: 0
16058 },
16059 source: ""
16060 };
16061 var lines, last;
16062 this.stringify(this.root, function(str, node2, type) {
16063 _this.css += str;
16064 if (node2 && type !== "end") {
16065 mapping.generated.line = line;
16066 mapping.generated.column = column - 1;
16067 if (node2.source && node2.source.start) {
16068 mapping.source = _this.sourcePath(node2);
16069 mapping.original.line = node2.source.start.line;
16070 mapping.original.column = node2.source.start.column - 1;
16071 _this.map.addMapping(mapping);
16072 } else {
16073 mapping.source = noSource;
16074 mapping.original.line = 1;
16075 mapping.original.column = 0;
16076 _this.map.addMapping(mapping);
16077 }
16078 }
16079 lines = str.match(/\n/g);
16080 if (lines) {
16081 line += lines.length;
16082 last = str.lastIndexOf("\n");
16083 column = str.length - last;
16084 } else {
16085 column += str.length;
16086 }
16087 if (node2 && type !== "start") {
16088 var p = node2.parent || {
16089 raws: {}
16090 };
16091 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
16092 if (!childless || node2 !== p.last || p.raws.semicolon) {
16093 if (node2.source && node2.source.end) {
16094 mapping.source = _this.sourcePath(node2);
16095 mapping.original.line = node2.source.end.line;
16096 mapping.original.column = node2.source.end.column - 1;
16097 mapping.generated.line = line;
16098 mapping.generated.column = column - 2;
16099 _this.map.addMapping(mapping);
16100 } else {
16101 mapping.source = noSource;
16102 mapping.original.line = 1;
16103 mapping.original.column = 0;
16104 mapping.generated.line = line;
16105 mapping.generated.column = column - 1;
16106 _this.map.addMapping(mapping);
16107 }
16108 }
16109 }
16110 });
16111 };
16112 _proto.isAnnotation = function isAnnotation() {
16113 if (this.isInline()) {
16114 return true;
16115 }
16116 if (typeof this.mapOpts.annotation !== "undefined") {
16117 return this.mapOpts.annotation;
16118 }
16119 if (this.previous().length) {
16120 return this.previous().some(function(i2) {
16121 return i2.annotation;
16122 });
16123 }
16124 return true;
16125 };
16126 _proto.isInline = function isInline() {
16127 if (typeof this.mapOpts.inline !== "undefined") {
16128 return this.mapOpts.inline;
16129 }
16130 var annotation = this.mapOpts.annotation;
16131 if (typeof annotation !== "undefined" && annotation !== true) {
16132 return false;
16133 }
16134 if (this.previous().length) {
16135 return this.previous().some(function(i2) {
16136 return i2.inline;
16137 });
16138 }
16139 return true;
16140 };
16141 _proto.isMap = function isMap() {
16142 if (typeof this.opts.map !== "undefined") {
16143 return !!this.opts.map;
16144 }
16145 return this.previous().length > 0;
16146 };
16147 _proto.isSourcesContent = function isSourcesContent() {
16148 if (typeof this.mapOpts.sourcesContent !== "undefined") {
16149 return this.mapOpts.sourcesContent;
16150 }
16151 if (this.previous().length) {
16152 return this.previous().some(function(i2) {
16153 return i2.withContent();
16154 });
16155 }
16156 return true;
16157 };
16158 _proto.outputFile = function outputFile() {
16159 if (this.opts.to) {
16160 return this.path(this.opts.to);
16161 } else if (this.opts.from) {
16162 return this.path(this.opts.from);
16163 } else {
16164 return "to.css";
16165 }
16166 };
16167 _proto.path = function path(file) {
16168 if (this.mapOpts.absolute) return file;
16169 if (file.charCodeAt(0) === 60) return file;
16170 if (/^\w+:\/\//.test(file)) return file;
16171 var cached = this.memoizedPaths.get(file);
16172 if (cached) return cached;
16173 var from = this.opts.to ? dirname(this.opts.to) : ".";
16174 if (typeof this.mapOpts.annotation === "string") {
16175 from = dirname(resolve$3(from, this.mapOpts.annotation));
16176 }
16177 var path = relative(from, file);
16178 this.memoizedPaths.set(file, path);
16179 return path;
16180 };
16181 _proto.previous = function previous() {
16182 var _this = this;
16183 if (!this.previousMaps) {
16184 this.previousMaps = [];
16185 if (this.root) {
16186 this.root.walk(function(node2) {
16187 if (node2.source && node2.source.input.map) {
16188 var map = node2.source.input.map;
16189 if (!_this.previousMaps.includes(map)) {
16190 _this.previousMaps.push(map);
16191 }
16192 }
16193 });
16194 } else {
16195 var input2 = new Input$3(this.originalCSS, this.opts);
16196 if (input2.map) this.previousMaps.push(input2.map);
16197 }
16198 }
16199 return this.previousMaps;
16200 };
16201 _proto.setSourcesContent = function setSourcesContent() {
16202 var _this = this;
16203 var already = {};
16204 if (this.root) {
16205 this.root.walk(function(node2) {
16206 if (node2.source) {
16207 var from = node2.source.input.from;
16208 if (from && !already[from]) {
16209 already[from] = true;
16210 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
16211 _this.map.setSourceContent(fromUrl, node2.source.input.css);
16212 }
16213 }
16214 });
16215 } else if (this.css) {
16216 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
16217 this.map.setSourceContent(from, this.css);
16218 }
16219 };
16220 _proto.sourcePath = function sourcePath(node2) {
16221 if (this.mapOpts.from) {
16222 return this.toUrl(this.mapOpts.from);
16223 } else if (this.usesFileUrls) {
16224 return this.toFileUrl(node2.source.input.from);
16225 } else {
16226 return this.toUrl(this.path(node2.source.input.from));
16227 }
16228 };
16229 _proto.toBase64 = function toBase64(str) {
16230 if (Buffer) {
16231 return Buffer.from(str).toString("base64");
16232 } else {
16233 return window.btoa(unescape(encodeURIComponent(str)));
16234 }
16235 };
16236 _proto.toFileUrl = function toFileUrl(path) {
16237 var cached = this.memoizedFileURLs.get(path);
16238 if (cached) return cached;
16239 if (pathToFileURL) {
16240 var fileURL = pathToFileURL(path).toString();
16241 this.memoizedFileURLs.set(path, fileURL);
16242 return fileURL;
16243 } else {
16244 throw new Error("`map.absolute` option is not available in this PostCSS build");
16245 }
16246 };
16247 _proto.toUrl = function toUrl(path) {
16248 var cached = this.memoizedURLs.get(path);
16249 if (cached) return cached;
16250 if (sep === "\\") {
16251 path = path.replace(/\\/g, "/");
16252 }
16253 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
16254 this.memoizedURLs.set(path, url);
16255 return url;
16256 };
16257 return MapGenerator2;
16258 }();
16259 var mapGenerator = MapGenerator$2;
16260 var Node$2 = node;
16261 var Comment$4 = /*#__PURE__*/ function(Node$2) {
16262 _inherits(Comment2, Node$2);
16263 function Comment2(defaults) {
16264 var _this;
16265 _this = Node$2.call(this, defaults) || this;
16266 _this.type = "comment";
16267 return _this;
16268 }
16269 return Comment2;
16270 }(Node$2);
16271 var comment = Comment$4;
16272 Comment$4.default = Comment$4;
16273 var isClean$1 = symbols.isClean, my$1 = symbols.my;
16274 var Declaration$3 = declaration;
16275 var Comment$3 = comment;
16276 var Node$1 = node;
16277 var parse$4, Rule$4, AtRule$4, Root$6;
16278 function cleanSource(nodes) {
16279 return nodes.map(function(i2) {
16280 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
16281 delete i2.source;
16282 return i2;
16283 });
16284 }
16285 function markDirtyUp(node2) {
16286 node2[isClean$1] = false;
16287 if (node2.proxyOf.nodes) {
16288 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
16289 var i2 = _step.value;
16290 markDirtyUp(i2);
16291 }
16292 }
16293 }
16294 var Container$7 = /*#__PURE__*/ function(Node$1) {
16295 _inherits(Container2, Node$1);
16296 function Container2() {
16297 return Node$1.apply(this, arguments) || this;
16298 }
16299 var _proto = Container2.prototype;
16300 _proto.append = function append() {
16301 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
16302 children[_key] = arguments[_key];
16303 }
16304 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
16305 var child = _step.value;
16306 var nodes = this.normalize(child, this.last);
16307 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16308 var node2 = _step1.value;
16309 this.proxyOf.nodes.push(node2);
16310 }
16311 }
16312 this.markDirty();
16313 return this;
16314 };
16315 _proto.cleanRaws = function cleanRaws(keepBetween) {
16316 Node$1.prototype.cleanRaws.call(this, keepBetween);
16317 if (this.nodes) {
16318 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
16319 var node2 = _step.value;
16320 node2.cleanRaws(keepBetween);
16321 }
16322 }
16323 };
16324 _proto.each = function each(callback) {
16325 if (!this.proxyOf.nodes) return void 0;
16326 var iterator = this.getIterator();
16327 var index2, result2;
16328 while(this.indexes[iterator] < this.proxyOf.nodes.length){
16329 index2 = this.indexes[iterator];
16330 result2 = callback(this.proxyOf.nodes[index2], index2);
16331 if (result2 === false) break;
16332 this.indexes[iterator] += 1;
16333 }
16334 delete this.indexes[iterator];
16335 return result2;
16336 };
16337 _proto.every = function every(condition) {
16338 return this.nodes.every(condition);
16339 };
16340 _proto.getIterator = function getIterator() {
16341 if (!this.lastEach) this.lastEach = 0;
16342 if (!this.indexes) this.indexes = {};
16343 this.lastEach += 1;
16344 var iterator = this.lastEach;
16345 this.indexes[iterator] = 0;
16346 return iterator;
16347 };
16348 _proto.getProxyProcessor = function getProxyProcessor() {
16349 return {
16350 get: function get(node2, prop) {
16351 if (prop === "proxyOf") {
16352 return node2;
16353 } else if (!node2[prop]) {
16354 return node2[prop];
16355 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
16356 return function() {
16357 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16358 args[_key] = arguments[_key];
16359 }
16360 var _node2;
16361 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
16362 if (typeof i2 === "function") {
16363 return function(child, index2) {
16364 return i2(child.toProxy(), index2);
16365 };
16366 } else {
16367 return i2;
16368 }
16369 })));
16370 };
16371 } else if (prop === "every" || prop === "some") {
16372 return function(cb) {
16373 return node2[prop](function(child) {
16374 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
16375 other[_key - 1] = arguments[_key];
16376 }
16377 return cb.apply(void 0, [].concat([
16378 child.toProxy()
16379 ], other));
16380 });
16381 };
16382 } else if (prop === "root") {
16383 return function() {
16384 return node2.root().toProxy();
16385 };
16386 } else if (prop === "nodes") {
16387 return node2.nodes.map(function(i2) {
16388 return i2.toProxy();
16389 });
16390 } else if (prop === "first" || prop === "last") {
16391 return node2[prop].toProxy();
16392 } else {
16393 return node2[prop];
16394 }
16395 },
16396 set: function set(node2, prop, value) {
16397 if (node2[prop] === value) return true;
16398 node2[prop] = value;
16399 if (prop === "name" || prop === "params" || prop === "selector") {
16400 node2.markDirty();
16401 }
16402 return true;
16403 }
16404 };
16405 };
16406 _proto.index = function index(child) {
16407 if (typeof child === "number") return child;
16408 if (child.proxyOf) child = child.proxyOf;
16409 return this.proxyOf.nodes.indexOf(child);
16410 };
16411 _proto.insertAfter = function insertAfter(exist, add) {
16412 var existIndex = this.index(exist);
16413 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
16414 existIndex = this.index(exist);
16415 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16416 var node2 = _step.value;
16417 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
16418 }
16419 var index2;
16420 for(var id in this.indexes){
16421 index2 = this.indexes[id];
16422 if (existIndex < index2) {
16423 this.indexes[id] = index2 + nodes.length;
16424 }
16425 }
16426 this.markDirty();
16427 return this;
16428 };
16429 _proto.insertBefore = function insertBefore(exist, add) {
16430 var existIndex = this.index(exist);
16431 var type = existIndex === 0 ? "prepend" : false;
16432 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
16433 existIndex = this.index(exist);
16434 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16435 var node2 = _step.value;
16436 this.proxyOf.nodes.splice(existIndex, 0, node2);
16437 }
16438 var index2;
16439 for(var id in this.indexes){
16440 index2 = this.indexes[id];
16441 if (existIndex <= index2) {
16442 this.indexes[id] = index2 + nodes.length;
16443 }
16444 }
16445 this.markDirty();
16446 return this;
16447 };
16448 _proto.normalize = function normalize(nodes, sample) {
16449 var _this = this;
16450 if (typeof nodes === "string") {
16451 nodes = cleanSource(parse$4(nodes).nodes);
16452 } else if (typeof nodes === "undefined") {
16453 nodes = [];
16454 } else if (Array.isArray(nodes)) {
16455 nodes = nodes.slice(0);
16456 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16457 var i2 = _step.value;
16458 if (i2.parent) i2.parent.removeChild(i2, "ignore");
16459 }
16460 } else if (nodes.type === "root" && this.type !== "document") {
16461 nodes = nodes.nodes.slice(0);
16462 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16463 var i21 = _step1.value;
16464 if (i21.parent) i21.parent.removeChild(i21, "ignore");
16465 }
16466 } else if (nodes.type) {
16467 nodes = [
16468 nodes
16469 ];
16470 } else if (nodes.prop) {
16471 if (typeof nodes.value === "undefined") {
16472 throw new Error("Value field is missed in node creation");
16473 } else if (typeof nodes.value !== "string") {
16474 nodes.value = String(nodes.value);
16475 }
16476 nodes = [
16477 new Declaration$3(nodes)
16478 ];
16479 } else if (nodes.selector) {
16480 nodes = [
16481 new Rule$4(nodes)
16482 ];
16483 } else if (nodes.name) {
16484 nodes = [
16485 new AtRule$4(nodes)
16486 ];
16487 } else if (nodes.text) {
16488 nodes = [
16489 new Comment$3(nodes)
16490 ];
16491 } else {
16492 throw new Error("Unknown node type in node creation");
16493 }
16494 var processed = nodes.map(function(i2) {
16495 if (!i2[my$1]) Container2.rebuild(i2);
16496 i2 = i2.proxyOf;
16497 if (i2.parent) i2.parent.removeChild(i2);
16498 if (i2[isClean$1]) markDirtyUp(i2);
16499 if (typeof i2.raws.before === "undefined") {
16500 if (sample && typeof sample.raws.before !== "undefined") {
16501 i2.raws.before = sample.raws.before.replace(/\S/g, "");
16502 }
16503 }
16504 i2.parent = _this.proxyOf;
16505 return i2;
16506 });
16507 return processed;
16508 };
16509 _proto.prepend = function prepend() {
16510 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
16511 children[_key] = arguments[_key];
16512 }
16513 children = children.reverse();
16514 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
16515 var child = _step.value;
16516 var nodes = this.normalize(child, this.first, "prepend").reverse();
16517 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16518 var node2 = _step1.value;
16519 this.proxyOf.nodes.unshift(node2);
16520 }
16521 for(var id in this.indexes){
16522 this.indexes[id] = this.indexes[id] + nodes.length;
16523 }
16524 }
16525 this.markDirty();
16526 return this;
16527 };
16528 _proto.push = function push(child) {
16529 child.parent = this;
16530 this.proxyOf.nodes.push(child);
16531 return this;
16532 };
16533 _proto.removeAll = function removeAll() {
16534 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
16535 var node2 = _step.value;
16536 node2.parent = void 0;
16537 }
16538 this.proxyOf.nodes = [];
16539 this.markDirty();
16540 return this;
16541 };
16542 _proto.removeChild = function removeChild(child) {
16543 child = this.index(child);
16544 this.proxyOf.nodes[child].parent = void 0;
16545 this.proxyOf.nodes.splice(child, 1);
16546 var index2;
16547 for(var id in this.indexes){
16548 index2 = this.indexes[id];
16549 if (index2 >= child) {
16550 this.indexes[id] = index2 - 1;
16551 }
16552 }
16553 this.markDirty();
16554 return this;
16555 };
16556 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
16557 if (!callback) {
16558 callback = opts;
16559 opts = {};
16560 }
16561 this.walkDecls(function(decl) {
16562 if (opts.props && !opts.props.includes(decl.prop)) return;
16563 if (opts.fast && !decl.value.includes(opts.fast)) return;
16564 decl.value = decl.value.replace(pattern, callback);
16565 });
16566 this.markDirty();
16567 return this;
16568 };
16569 _proto.some = function some(condition) {
16570 return this.nodes.some(condition);
16571 };
16572 _proto.walk = function walk(callback) {
16573 return this.each(function(child, i2) {
16574 var result2;
16575 try {
16576 result2 = callback(child, i2);
16577 } catch (e2) {
16578 throw child.addToError(e2);
16579 }
16580 if (result2 !== false && child.walk) {
16581 result2 = child.walk(callback);
16582 }
16583 return result2;
16584 });
16585 };
16586 _proto.walkAtRules = function walkAtRules(name, callback) {
16587 if (!callback) {
16588 callback = name;
16589 return this.walk(function(child, i2) {
16590 if (child.type === "atrule") {
16591 return callback(child, i2);
16592 }
16593 });
16594 }
16595 if (_instanceof(name, RegExp)) {
16596 return this.walk(function(child, i2) {
16597 if (child.type === "atrule" && name.test(child.name)) {
16598 return callback(child, i2);
16599 }
16600 });
16601 }
16602 return this.walk(function(child, i2) {
16603 if (child.type === "atrule" && child.name === name) {
16604 return callback(child, i2);
16605 }
16606 });
16607 };
16608 _proto.walkComments = function walkComments(callback) {
16609 return this.walk(function(child, i2) {
16610 if (child.type === "comment") {
16611 return callback(child, i2);
16612 }
16613 });
16614 };
16615 _proto.walkDecls = function walkDecls(prop, callback) {
16616 if (!callback) {
16617 callback = prop;
16618 return this.walk(function(child, i2) {
16619 if (child.type === "decl") {
16620 return callback(child, i2);
16621 }
16622 });
16623 }
16624 if (_instanceof(prop, RegExp)) {
16625 return this.walk(function(child, i2) {
16626 if (child.type === "decl" && prop.test(child.prop)) {
16627 return callback(child, i2);
16628 }
16629 });
16630 }
16631 return this.walk(function(child, i2) {
16632 if (child.type === "decl" && child.prop === prop) {
16633 return callback(child, i2);
16634 }
16635 });
16636 };
16637 _proto.walkRules = function walkRules(selector, callback) {
16638 if (!callback) {
16639 callback = selector;
16640 return this.walk(function(child, i2) {
16641 if (child.type === "rule") {
16642 return callback(child, i2);
16643 }
16644 });
16645 }
16646 if (_instanceof(selector, RegExp)) {
16647 return this.walk(function(child, i2) {
16648 if (child.type === "rule" && selector.test(child.selector)) {
16649 return callback(child, i2);
16650 }
16651 });
16652 }
16653 return this.walk(function(child, i2) {
16654 if (child.type === "rule" && child.selector === selector) {
16655 return callback(child, i2);
16656 }
16657 });
16658 };
16659 _create_class(Container2, [
16660 {
16661 key: "first",
16662 get: function get() {
16663 if (!this.proxyOf.nodes) return void 0;
16664 return this.proxyOf.nodes[0];
16665 }
16666 },
16667 {
16668 key: "last",
16669 get: function get() {
16670 if (!this.proxyOf.nodes) return void 0;
16671 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
16672 }
16673 }
16674 ]);
16675 return Container2;
16676 }(Node$1);
16677 Container$7.registerParse = function(dependant) {
16678 parse$4 = dependant;
16679 };
16680 Container$7.registerRule = function(dependant) {
16681 Rule$4 = dependant;
16682 };
16683 Container$7.registerAtRule = function(dependant) {
16684 AtRule$4 = dependant;
16685 };
16686 Container$7.registerRoot = function(dependant) {
16687 Root$6 = dependant;
16688 };
16689 var container = Container$7;
16690 Container$7.default = Container$7;
16691 Container$7.rebuild = function(node2) {
16692 if (node2.type === "atrule") {
16693 Object.setPrototypeOf(node2, AtRule$4.prototype);
16694 } else if (node2.type === "rule") {
16695 Object.setPrototypeOf(node2, Rule$4.prototype);
16696 } else if (node2.type === "decl") {
16697 Object.setPrototypeOf(node2, Declaration$3.prototype);
16698 } else if (node2.type === "comment") {
16699 Object.setPrototypeOf(node2, Comment$3.prototype);
16700 } else if (node2.type === "root") {
16701 Object.setPrototypeOf(node2, Root$6.prototype);
16702 }
16703 node2[my$1] = true;
16704 if (node2.nodes) {
16705 node2.nodes.forEach(function(child) {
16706 Container$7.rebuild(child);
16707 });
16708 }
16709 };
16710 var Container$6 = container;
16711 var LazyResult$4, Processor$3;
16712 var Document$3 = /*#__PURE__*/ function(Container$6) {
16713 _inherits(Document23, Container$6);
16714 function Document23(defaults) {
16715 var _this;
16716 _this = Container$6.call(this, _extends({
16717 type: "document"
16718 }, defaults)) || this;
16719 if (!_this.nodes) {
16720 _this.nodes = [];
16721 }
16722 return _this;
16723 }
16724 var _proto = Document23.prototype;
16725 _proto.toResult = function toResult(opts) {
16726 if (opts === void 0) opts = {};
16727 var lazy = new LazyResult$4(new Processor$3(), this, opts);
16728 return lazy.stringify();
16729 };
16730 return Document23;
16731 }(Container$6);
16732 Document$3.registerLazyResult = function(dependant) {
16733 LazyResult$4 = dependant;
16734 };
16735 Document$3.registerProcessor = function(dependant) {
16736 Processor$3 = dependant;
16737 };
16738 var document$1$2 = Document$3;
16739 Document$3.default = Document$3;
16740 var printed = {};
16741 var warnOnce$2 = function warnOnce2(message) {
16742 if (printed[message]) return;
16743 printed[message] = true;
16744 if (typeof console !== "undefined" && console.warn) {
16745 console.warn(message);
16746 }
16747 };
16748 var Warning$2 = /*#__PURE__*/ function() {
16749 function Warning2(text, opts) {
16750 if (opts === void 0) opts = {};
16751 this.type = "warning";
16752 this.text = text;
16753 if (opts.node && opts.node.source) {
16754 var range = opts.node.rangeBy(opts);
16755 this.line = range.start.line;
16756 this.column = range.start.column;
16757 this.endLine = range.end.line;
16758 this.endColumn = range.end.column;
16759 }
16760 for(var opt in opts)this[opt] = opts[opt];
16761 }
16762 var _proto = Warning2.prototype;
16763 _proto.toString = function toString() {
16764 if (this.node) {
16765 return this.node.error(this.text, {
16766 index: this.index,
16767 plugin: this.plugin,
16768 word: this.word
16769 }).message;
16770 }
16771 if (this.plugin) {
16772 return this.plugin + ": " + this.text;
16773 }
16774 return this.text;
16775 };
16776 return Warning2;
16777 }();
16778 var warning = Warning$2;
16779 Warning$2.default = Warning$2;
16780 var Warning$1 = warning;
16781 var Result$3 = /*#__PURE__*/ function() {
16782 function Result2(processor2, root2, opts) {
16783 this.processor = processor2;
16784 this.messages = [];
16785 this.root = root2;
16786 this.opts = opts;
16787 this.css = void 0;
16788 this.map = void 0;
16789 }
16790 var _proto = Result2.prototype;
16791 _proto.toString = function toString() {
16792 return this.css;
16793 };
16794 _proto.warn = function warn(text, opts) {
16795 if (opts === void 0) opts = {};
16796 if (!opts.plugin) {
16797 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
16798 opts.plugin = this.lastPlugin.postcssPlugin;
16799 }
16800 }
16801 var warning2 = new Warning$1(text, opts);
16802 this.messages.push(warning2);
16803 return warning2;
16804 };
16805 _proto.warnings = function warnings() {
16806 return this.messages.filter(function(i2) {
16807 return i2.type === "warning";
16808 });
16809 };
16810 _create_class(Result2, [
16811 {
16812 key: "content",
16813 get: function get() {
16814 return this.css;
16815 }
16816 }
16817 ]);
16818 return Result2;
16819 }();
16820 var result = Result$3;
16821 Result$3.default = Result$3;
16822 var SINGLE_QUOTE = "'".charCodeAt(0);
16823 var DOUBLE_QUOTE = '"'.charCodeAt(0);
16824 var BACKSLASH = "\\".charCodeAt(0);
16825 var SLASH = "/".charCodeAt(0);
16826 var NEWLINE = "\n".charCodeAt(0);
16827 var SPACE = " ".charCodeAt(0);
16828 var FEED = "\f".charCodeAt(0);
16829 var TAB = " ".charCodeAt(0);
16830 var CR = "\r".charCodeAt(0);
16831 var OPEN_SQUARE = "[".charCodeAt(0);
16832 var CLOSE_SQUARE = "]".charCodeAt(0);
16833 var OPEN_PARENTHESES = "(".charCodeAt(0);
16834 var CLOSE_PARENTHESES = ")".charCodeAt(0);
16835 var OPEN_CURLY = "{".charCodeAt(0);
16836 var CLOSE_CURLY = "}".charCodeAt(0);
16837 var SEMICOLON = ";".charCodeAt(0);
16838 var ASTERISK = "*".charCodeAt(0);
16839 var COLON = ":".charCodeAt(0);
16840 var AT = "@".charCodeAt(0);
16841 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
16842 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
16843 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
16844 var RE_HEX_ESCAPE = /[\da-f]/i;
16845 var tokenize = function tokenizer2(input2, options) {
16846 if (options === void 0) options = {};
16847 var css = input2.css.valueOf();
16848 var ignore = options.ignoreErrors;
16849 var code, next, quote, content, escape;
16850 var escaped, escapePos, prev, n2, currentToken;
16851 var length = css.length;
16852 var pos = 0;
16853 var buffer = [];
16854 var returned = [];
16855 function position() {
16856 return pos;
16857 }
16858 function unclosed(what) {
16859 throw input2.error("Unclosed " + what, pos);
16860 }
16861 function endOfFile() {
16862 return returned.length === 0 && pos >= length;
16863 }
16864 function nextToken(opts) {
16865 if (returned.length) return returned.pop();
16866 if (pos >= length) return;
16867 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
16868 code = css.charCodeAt(pos);
16869 switch(code){
16870 case NEWLINE:
16871 case SPACE:
16872 case TAB:
16873 case CR:
16874 case FEED:
16875 {
16876 next = pos;
16877 do {
16878 next += 1;
16879 code = css.charCodeAt(next);
16880 }while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
16881 currentToken = [
16882 "space",
16883 css.slice(pos, next)
16884 ];
16885 pos = next - 1;
16886 break;
16887 }
16888 case OPEN_SQUARE:
16889 case CLOSE_SQUARE:
16890 case OPEN_CURLY:
16891 case CLOSE_CURLY:
16892 case COLON:
16893 case SEMICOLON:
16894 case CLOSE_PARENTHESES:
16895 {
16896 var controlChar = String.fromCharCode(code);
16897 currentToken = [
16898 controlChar,
16899 controlChar,
16900 pos
16901 ];
16902 break;
16903 }
16904 case OPEN_PARENTHESES:
16905 {
16906 prev = buffer.length ? buffer.pop()[1] : "";
16907 n2 = css.charCodeAt(pos + 1);
16908 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
16909 next = pos;
16910 do {
16911 escaped = false;
16912 next = css.indexOf(")", next + 1);
16913 if (next === -1) {
16914 if (ignore || ignoreUnclosed) {
16915 next = pos;
16916 break;
16917 } else {
16918 unclosed("bracket");
16919 }
16920 }
16921 escapePos = next;
16922 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
16923 escapePos -= 1;
16924 escaped = !escaped;
16925 }
16926 }while (escaped);
16927 currentToken = [
16928 "brackets",
16929 css.slice(pos, next + 1),
16930 pos,
16931 next
16932 ];
16933 pos = next;
16934 } else {
16935 next = css.indexOf(")", pos + 1);
16936 content = css.slice(pos, next + 1);
16937 if (next === -1 || RE_BAD_BRACKET.test(content)) {
16938 currentToken = [
16939 "(",
16940 "(",
16941 pos
16942 ];
16943 } else {
16944 currentToken = [
16945 "brackets",
16946 content,
16947 pos,
16948 next
16949 ];
16950 pos = next;
16951 }
16952 }
16953 break;
16954 }
16955 case SINGLE_QUOTE:
16956 case DOUBLE_QUOTE:
16957 {
16958 quote = code === SINGLE_QUOTE ? "'" : '"';
16959 next = pos;
16960 do {
16961 escaped = false;
16962 next = css.indexOf(quote, next + 1);
16963 if (next === -1) {
16964 if (ignore || ignoreUnclosed) {
16965 next = pos + 1;
16966 break;
16967 } else {
16968 unclosed("string");
16969 }
16970 }
16971 escapePos = next;
16972 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
16973 escapePos -= 1;
16974 escaped = !escaped;
16975 }
16976 }while (escaped);
16977 currentToken = [
16978 "string",
16979 css.slice(pos, next + 1),
16980 pos,
16981 next
16982 ];
16983 pos = next;
16984 break;
16985 }
16986 case AT:
16987 {
16988 RE_AT_END.lastIndex = pos + 1;
16989 RE_AT_END.test(css);
16990 if (RE_AT_END.lastIndex === 0) {
16991 next = css.length - 1;
16992 } else {
16993 next = RE_AT_END.lastIndex - 2;
16994 }
16995 currentToken = [
16996 "at-word",
16997 css.slice(pos, next + 1),
16998 pos,
16999 next
17000 ];
17001 pos = next;
17002 break;
17003 }
17004 case BACKSLASH:
17005 {
17006 next = pos;
17007 escape = true;
17008 while(css.charCodeAt(next + 1) === BACKSLASH){
17009 next += 1;
17010 escape = !escape;
17011 }
17012 code = css.charCodeAt(next + 1);
17013 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
17014 next += 1;
17015 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
17016 while(RE_HEX_ESCAPE.test(css.charAt(next + 1))){
17017 next += 1;
17018 }
17019 if (css.charCodeAt(next + 1) === SPACE) {
17020 next += 1;
17021 }
17022 }
17023 }
17024 currentToken = [
17025 "word",
17026 css.slice(pos, next + 1),
17027 pos,
17028 next
17029 ];
17030 pos = next;
17031 break;
17032 }
17033 default:
17034 {
17035 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
17036 next = css.indexOf("*/", pos + 2) + 1;
17037 if (next === 0) {
17038 if (ignore || ignoreUnclosed) {
17039 next = css.length;
17040 } else {
17041 unclosed("comment");
17042 }
17043 }
17044 currentToken = [
17045 "comment",
17046 css.slice(pos, next + 1),
17047 pos,
17048 next
17049 ];
17050 pos = next;
17051 } else {
17052 RE_WORD_END.lastIndex = pos + 1;
17053 RE_WORD_END.test(css);
17054 if (RE_WORD_END.lastIndex === 0) {
17055 next = css.length - 1;
17056 } else {
17057 next = RE_WORD_END.lastIndex - 2;
17058 }
17059 currentToken = [
17060 "word",
17061 css.slice(pos, next + 1),
17062 pos,
17063 next
17064 ];
17065 buffer.push(currentToken);
17066 pos = next;
17067 }
17068 break;
17069 }
17070 }
17071 pos++;
17072 return currentToken;
17073 }
17074 function back(token) {
17075 returned.push(token);
17076 }
17077 return {
17078 back: back,
17079 endOfFile: endOfFile,
17080 nextToken: nextToken,
17081 position: position
17082 };
17083 };
17084 var Container$5 = container;
17085 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
17086 _inherits(AtRule2, Container$5);
17087 function AtRule2(defaults) {
17088 var _this;
17089 _this = Container$5.call(this, defaults) || this;
17090 _this.type = "atrule";
17091 return _this;
17092 }
17093 var _proto = AtRule2.prototype;
17094 _proto.append = function append() {
17095 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
17096 children[_key] = arguments[_key];
17097 }
17098 var _Container$5_prototype_append;
17099 if (!this.proxyOf.nodes) this.nodes = [];
17100 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([
17101 this
17102 ], children));
17103 };
17104 _proto.prepend = function prepend() {
17105 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
17106 children[_key] = arguments[_key];
17107 }
17108 var _Container$5_prototype_prepend;
17109 if (!this.proxyOf.nodes) this.nodes = [];
17110 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([
17111 this
17112 ], children));
17113 };
17114 return AtRule2;
17115 }(Container$5);
17116 var atRule = AtRule$3;
17117 AtRule$3.default = AtRule$3;
17118 Container$5.registerAtRule(AtRule$3);
17119 var Container$4 = container;
17120 var LazyResult$3, Processor$2;
17121 var Root$5 = /*#__PURE__*/ function(Container$4) {
17122 _inherits(Root2, Container$4);
17123 function Root2(defaults) {
17124 var _this;
17125 _this = Container$4.call(this, defaults) || this;
17126 _this.type = "root";
17127 if (!_this.nodes) _this.nodes = [];
17128 return _this;
17129 }
17130 var _proto = Root2.prototype;
17131 _proto.normalize = function normalize(child, sample, type) {
17132 var nodes = Container$4.prototype.normalize.call(this, child);
17133 if (sample) {
17134 if (type === "prepend") {
17135 if (this.nodes.length > 1) {
17136 sample.raws.before = this.nodes[1].raws.before;
17137 } else {
17138 delete sample.raws.before;
17139 }
17140 } else if (this.first !== sample) {
17141 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
17142 var node2 = _step.value;
17143 node2.raws.before = sample.raws.before;
17144 }
17145 }
17146 }
17147 return nodes;
17148 };
17149 _proto.removeChild = function removeChild(child, ignore) {
17150 var index2 = this.index(child);
17151 if (!ignore && index2 === 0 && this.nodes.length > 1) {
17152 this.nodes[1].raws.before = this.nodes[index2].raws.before;
17153 }
17154 return Container$4.prototype.removeChild.call(this, child);
17155 };
17156 _proto.toResult = function toResult(opts) {
17157 if (opts === void 0) opts = {};
17158 var lazy = new LazyResult$3(new Processor$2(), this, opts);
17159 return lazy.stringify();
17160 };
17161 return Root2;
17162 }(Container$4);
17163 Root$5.registerLazyResult = function(dependant) {
17164 LazyResult$3 = dependant;
17165 };
17166 Root$5.registerProcessor = function(dependant) {
17167 Processor$2 = dependant;
17168 };
17169 var root = Root$5;
17170 Root$5.default = Root$5;
17171 Container$4.registerRoot(Root$5);
17172 var list$2 = {
17173 comma: function comma(string) {
17174 return list$2.split(string, [
17175 ","
17176 ], true);
17177 },
17178 space: function space(string) {
17179 var spaces = [
17180 " ",
17181 "\n",
17182 " "
17183 ];
17184 return list$2.split(string, spaces);
17185 },
17186 split: function split(string, separators, last) {
17187 var array = [];
17188 var current = "";
17189 var split = false;
17190 var func = 0;
17191 var inQuote = false;
17192 var prevQuote = "";
17193 var escape = false;
17194 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
17195 var letter = _step.value;
17196 if (escape) {
17197 escape = false;
17198 } else if (letter === "\\") {
17199 escape = true;
17200 } else if (inQuote) {
17201 if (letter === prevQuote) {
17202 inQuote = false;
17203 }
17204 } else if (letter === '"' || letter === "'") {
17205 inQuote = true;
17206 prevQuote = letter;
17207 } else if (letter === "(") {
17208 func += 1;
17209 } else if (letter === ")") {
17210 if (func > 0) func -= 1;
17211 } else if (func === 0) {
17212 if (separators.includes(letter)) split = true;
17213 }
17214 if (split) {
17215 if (current !== "") array.push(current.trim());
17216 current = "";
17217 split = false;
17218 } else {
17219 current += letter;
17220 }
17221 }
17222 if (last || current !== "") array.push(current.trim());
17223 return array;
17224 }
17225 };
17226 var list_1 = list$2;
17227 list$2.default = list$2;
17228 var Container$3 = container;
17229 var list$1 = list_1;
17230 var Rule$3 = /*#__PURE__*/ function(Container$3) {
17231 _inherits(Rule2, Container$3);
17232 function Rule2(defaults) {
17233 var _this;
17234 _this = Container$3.call(this, defaults) || this;
17235 _this.type = "rule";
17236 if (!_this.nodes) _this.nodes = [];
17237 return _this;
17238 }
17239 _create_class(Rule2, [
17240 {
17241 key: "selectors",
17242 get: function get() {
17243 return list$1.comma(this.selector);
17244 },
17245 set: function set(values) {
17246 var match = this.selector ? this.selector.match(/,\s*/) : null;
17247 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
17248 this.selector = values.join(sep2);
17249 }
17250 }
17251 ]);
17252 return Rule2;
17253 }(Container$3);
17254 var rule = Rule$3;
17255 Rule$3.default = Rule$3;
17256 Container$3.registerRule(Rule$3);
17257 var Declaration$2 = declaration;
17258 var tokenizer22 = tokenize;
17259 var Comment$2 = comment;
17260 var AtRule$2 = atRule;
17261 var Root$4 = root;
17262 var Rule$2 = rule;
17263 var SAFE_COMMENT_NEIGHBOR = {
17264 empty: true,
17265 space: true
17266 };
17267 function findLastWithPosition(tokens) {
17268 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
17269 var token = tokens[i2];
17270 var pos = token[3] || token[2];
17271 if (pos) return pos;
17272 }
17273 }
17274 var Parser$1 = /*#__PURE__*/ function() {
17275 function Parser2(input2) {
17276 this.input = input2;
17277 this.root = new Root$4();
17278 this.current = this.root;
17279 this.spaces = "";
17280 this.semicolon = false;
17281 this.createTokenizer();
17282 this.root.source = {
17283 input: input2,
17284 start: {
17285 column: 1,
17286 line: 1,
17287 offset: 0
17288 }
17289 };
17290 }
17291 var _proto = Parser2.prototype;
17292 _proto.atrule = function atrule(token) {
17293 var node2 = new AtRule$2();
17294 node2.name = token[1].slice(1);
17295 if (node2.name === "") {
17296 this.unnamedAtrule(node2, token);
17297 }
17298 this.init(node2, token[2]);
17299 var type;
17300 var prev;
17301 var shift;
17302 var last = false;
17303 var open = false;
17304 var params = [];
17305 var brackets = [];
17306 while(!this.tokenizer.endOfFile()){
17307 token = this.tokenizer.nextToken();
17308 type = token[0];
17309 if (type === "(" || type === "[") {
17310 brackets.push(type === "(" ? ")" : "]");
17311 } else if (type === "{" && brackets.length > 0) {
17312 brackets.push("}");
17313 } else if (type === brackets[brackets.length - 1]) {
17314 brackets.pop();
17315 }
17316 if (brackets.length === 0) {
17317 if (type === ";") {
17318 node2.source.end = this.getPosition(token[2]);
17319 node2.source.end.offset++;
17320 this.semicolon = true;
17321 break;
17322 } else if (type === "{") {
17323 open = true;
17324 break;
17325 } else if (type === "}") {
17326 if (params.length > 0) {
17327 shift = params.length - 1;
17328 prev = params[shift];
17329 while(prev && prev[0] === "space"){
17330 prev = params[--shift];
17331 }
17332 if (prev) {
17333 node2.source.end = this.getPosition(prev[3] || prev[2]);
17334 node2.source.end.offset++;
17335 }
17336 }
17337 this.end(token);
17338 break;
17339 } else {
17340 params.push(token);
17341 }
17342 } else {
17343 params.push(token);
17344 }
17345 if (this.tokenizer.endOfFile()) {
17346 last = true;
17347 break;
17348 }
17349 }
17350 node2.raws.between = this.spacesAndCommentsFromEnd(params);
17351 if (params.length) {
17352 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
17353 this.raw(node2, "params", params);
17354 if (last) {
17355 token = params[params.length - 1];
17356 node2.source.end = this.getPosition(token[3] || token[2]);
17357 node2.source.end.offset++;
17358 this.spaces = node2.raws.between;
17359 node2.raws.between = "";
17360 }
17361 } else {
17362 node2.raws.afterName = "";
17363 node2.params = "";
17364 }
17365 if (open) {
17366 node2.nodes = [];
17367 this.current = node2;
17368 }
17369 };
17370 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
17371 var colon = this.colon(tokens);
17372 if (colon === false) return;
17373 var founded = 0;
17374 var token;
17375 for(var j = colon - 1; j >= 0; j--){
17376 token = tokens[j];
17377 if (token[0] !== "space") {
17378 founded += 1;
17379 if (founded === 2) break;
17380 }
17381 }
17382 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
17383 };
17384 _proto.colon = function colon(tokens) {
17385 var brackets = 0;
17386 var token, type, prev;
17387 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
17388 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
17389 token = element;
17390 type = token[0];
17391 if (type === "(") {
17392 brackets += 1;
17393 }
17394 if (type === ")") {
17395 brackets -= 1;
17396 }
17397 if (brackets === 0 && type === ":") {
17398 if (!prev) {
17399 this.doubleColon(token);
17400 } else if (prev[0] === "word" && prev[1] === "progid") {
17401 continue;
17402 } else {
17403 return i2;
17404 }
17405 }
17406 prev = token;
17407 }
17408 return false;
17409 };
17410 _proto.comment = function comment(token) {
17411 var node2 = new Comment$2();
17412 this.init(node2, token[2]);
17413 node2.source.end = this.getPosition(token[3] || token[2]);
17414 node2.source.end.offset++;
17415 var text = token[1].slice(2, -2);
17416 if (/^\s*$/.test(text)) {
17417 node2.text = "";
17418 node2.raws.left = text;
17419 node2.raws.right = "";
17420 } else {
17421 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
17422 node2.text = match[2];
17423 node2.raws.left = match[1];
17424 node2.raws.right = match[3];
17425 }
17426 };
17427 _proto.createTokenizer = function createTokenizer() {
17428 this.tokenizer = tokenizer22(this.input);
17429 };
17430 _proto.decl = function decl(tokens, customProperty) {
17431 var node2 = new Declaration$2();
17432 this.init(node2, tokens[0][2]);
17433 var last = tokens[tokens.length - 1];
17434 if (last[0] === ";") {
17435 this.semicolon = true;
17436 tokens.pop();
17437 }
17438 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
17439 node2.source.end.offset++;
17440 while(tokens[0][0] !== "word"){
17441 if (tokens.length === 1) this.unknownWord(tokens);
17442 node2.raws.before += tokens.shift()[1];
17443 }
17444 node2.source.start = this.getPosition(tokens[0][2]);
17445 node2.prop = "";
17446 while(tokens.length){
17447 var type = tokens[0][0];
17448 if (type === ":" || type === "space" || type === "comment") {
17449 break;
17450 }
17451 node2.prop += tokens.shift()[1];
17452 }
17453 node2.raws.between = "";
17454 var token;
17455 while(tokens.length){
17456 token = tokens.shift();
17457 if (token[0] === ":") {
17458 node2.raws.between += token[1];
17459 break;
17460 } else {
17461 if (token[0] === "word" && /\w/.test(token[1])) {
17462 this.unknownWord([
17463 token
17464 ]);
17465 }
17466 node2.raws.between += token[1];
17467 }
17468 }
17469 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
17470 node2.raws.before += node2.prop[0];
17471 node2.prop = node2.prop.slice(1);
17472 }
17473 var firstSpaces = [];
17474 var next;
17475 while(tokens.length){
17476 next = tokens[0][0];
17477 if (next !== "space" && next !== "comment") break;
17478 firstSpaces.push(tokens.shift());
17479 }
17480 this.precheckMissedSemicolon(tokens);
17481 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
17482 token = tokens[i2];
17483 if (token[1].toLowerCase() === "!important") {
17484 node2.important = true;
17485 var string = this.stringFrom(tokens, i2);
17486 string = this.spacesFromEnd(tokens) + string;
17487 if (string !== " !important") node2.raws.important = string;
17488 break;
17489 } else if (token[1].toLowerCase() === "important") {
17490 var cache = tokens.slice(0);
17491 var str = "";
17492 for(var j = i2; j > 0; j--){
17493 var type1 = cache[j][0];
17494 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
17495 break;
17496 }
17497 str = cache.pop()[1] + str;
17498 }
17499 if (str.trim().indexOf("!") === 0) {
17500 node2.important = true;
17501 node2.raws.important = str;
17502 tokens = cache;
17503 }
17504 }
17505 if (token[0] !== "space" && token[0] !== "comment") {
17506 break;
17507 }
17508 }
17509 var hasWord = tokens.some(function(i2) {
17510 return i2[0] !== "space" && i2[0] !== "comment";
17511 });
17512 if (hasWord) {
17513 node2.raws.between += firstSpaces.map(function(i2) {
17514 return i2[1];
17515 }).join("");
17516 firstSpaces = [];
17517 }
17518 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
17519 if (node2.value.includes(":") && !customProperty) {
17520 this.checkMissedSemicolon(tokens);
17521 }
17522 };
17523 _proto.doubleColon = function doubleColon(token) {
17524 throw this.input.error("Double colon", {
17525 offset: token[2]
17526 }, {
17527 offset: token[2] + token[1].length
17528 });
17529 };
17530 _proto.emptyRule = function emptyRule(token) {
17531 var node2 = new Rule$2();
17532 this.init(node2, token[2]);
17533 node2.selector = "";
17534 node2.raws.between = "";
17535 this.current = node2;
17536 };
17537 _proto.end = function end(token) {
17538 if (this.current.nodes && this.current.nodes.length) {
17539 this.current.raws.semicolon = this.semicolon;
17540 }
17541 this.semicolon = false;
17542 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
17543 this.spaces = "";
17544 if (this.current.parent) {
17545 this.current.source.end = this.getPosition(token[2]);
17546 this.current.source.end.offset++;
17547 this.current = this.current.parent;
17548 } else {
17549 this.unexpectedClose(token);
17550 }
17551 };
17552 _proto.endFile = function endFile() {
17553 if (this.current.parent) this.unclosedBlock();
17554 if (this.current.nodes && this.current.nodes.length) {
17555 this.current.raws.semicolon = this.semicolon;
17556 }
17557 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
17558 this.root.source.end = this.getPosition(this.tokenizer.position());
17559 };
17560 _proto.freeSemicolon = function freeSemicolon(token) {
17561 this.spaces += token[1];
17562 if (this.current.nodes) {
17563 var prev = this.current.nodes[this.current.nodes.length - 1];
17564 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
17565 prev.raws.ownSemicolon = this.spaces;
17566 this.spaces = "";
17567 }
17568 }
17569 };
17570 // Helpers
17571 _proto.getPosition = function getPosition(offset) {
17572 var pos = this.input.fromOffset(offset);
17573 return {
17574 column: pos.col,
17575 line: pos.line,
17576 offset: offset
17577 };
17578 };
17579 _proto.init = function init(node2, offset) {
17580 this.current.push(node2);
17581 node2.source = {
17582 input: this.input,
17583 start: this.getPosition(offset)
17584 };
17585 node2.raws.before = this.spaces;
17586 this.spaces = "";
17587 if (node2.type !== "comment") this.semicolon = false;
17588 };
17589 _proto.other = function other(start) {
17590 var end = false;
17591 var type = null;
17592 var colon = false;
17593 var bracket = null;
17594 var brackets = [];
17595 var customProperty = start[1].startsWith("--");
17596 var tokens = [];
17597 var token = start;
17598 while(token){
17599 type = token[0];
17600 tokens.push(token);
17601 if (type === "(" || type === "[") {
17602 if (!bracket) bracket = token;
17603 brackets.push(type === "(" ? ")" : "]");
17604 } else if (customProperty && colon && type === "{") {
17605 if (!bracket) bracket = token;
17606 brackets.push("}");
17607 } else if (brackets.length === 0) {
17608 if (type === ";") {
17609 if (colon) {
17610 this.decl(tokens, customProperty);
17611 return;
17612 } else {
17613 break;
17614 }
17615 } else if (type === "{") {
17616 this.rule(tokens);
17617 return;
17618 } else if (type === "}") {
17619 this.tokenizer.back(tokens.pop());
17620 end = true;
17621 break;
17622 } else if (type === ":") {
17623 colon = true;
17624 }
17625 } else if (type === brackets[brackets.length - 1]) {
17626 brackets.pop();
17627 if (brackets.length === 0) bracket = null;
17628 }
17629 token = this.tokenizer.nextToken();
17630 }
17631 if (this.tokenizer.endOfFile()) end = true;
17632 if (brackets.length > 0) this.unclosedBracket(bracket);
17633 if (end && colon) {
17634 if (!customProperty) {
17635 while(tokens.length){
17636 token = tokens[tokens.length - 1][0];
17637 if (token !== "space" && token !== "comment") break;
17638 this.tokenizer.back(tokens.pop());
17639 }
17640 }
17641 this.decl(tokens, customProperty);
17642 } else {
17643 this.unknownWord(tokens);
17644 }
17645 };
17646 _proto.parse = function parse() {
17647 var token;
17648 while(!this.tokenizer.endOfFile()){
17649 token = this.tokenizer.nextToken();
17650 switch(token[0]){
17651 case "space":
17652 this.spaces += token[1];
17653 break;
17654 case ";":
17655 this.freeSemicolon(token);
17656 break;
17657 case "}":
17658 this.end(token);
17659 break;
17660 case "comment":
17661 this.comment(token);
17662 break;
17663 case "at-word":
17664 this.atrule(token);
17665 break;
17666 case "{":
17667 this.emptyRule(token);
17668 break;
17669 default:
17670 this.other(token);
17671 break;
17672 }
17673 }
17674 this.endFile();
17675 };
17676 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
17677 _proto.raw = function raw(node2, prop, tokens, customProperty) {
17678 var token, type;
17679 var length = tokens.length;
17680 var value = "";
17681 var clean = true;
17682 var next, prev;
17683 for(var i2 = 0; i2 < length; i2 += 1){
17684 token = tokens[i2];
17685 type = token[0];
17686 if (type === "space" && i2 === length - 1 && !customProperty) {
17687 clean = false;
17688 } else if (type === "comment") {
17689 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
17690 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
17691 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
17692 if (value.slice(-1) === ",") {
17693 clean = false;
17694 } else {
17695 value += token[1];
17696 }
17697 } else {
17698 clean = false;
17699 }
17700 } else {
17701 value += token[1];
17702 }
17703 }
17704 if (!clean) {
17705 var raw = tokens.reduce(function(all, i2) {
17706 return all + i2[1];
17707 }, "");
17708 node2.raws[prop] = {
17709 raw: raw,
17710 value: value
17711 };
17712 }
17713 node2[prop] = value;
17714 };
17715 _proto.rule = function rule(tokens) {
17716 tokens.pop();
17717 var node2 = new Rule$2();
17718 this.init(node2, tokens[0][2]);
17719 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
17720 this.raw(node2, "selector", tokens);
17721 this.current = node2;
17722 };
17723 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
17724 var lastTokenType;
17725 var spaces = "";
17726 while(tokens.length){
17727 lastTokenType = tokens[tokens.length - 1][0];
17728 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
17729 spaces = tokens.pop()[1] + spaces;
17730 }
17731 return spaces;
17732 };
17733 // Errors
17734 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
17735 var next;
17736 var spaces = "";
17737 while(tokens.length){
17738 next = tokens[0][0];
17739 if (next !== "space" && next !== "comment") break;
17740 spaces += tokens.shift()[1];
17741 }
17742 return spaces;
17743 };
17744 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
17745 var lastTokenType;
17746 var spaces = "";
17747 while(tokens.length){
17748 lastTokenType = tokens[tokens.length - 1][0];
17749 if (lastTokenType !== "space") break;
17750 spaces = tokens.pop()[1] + spaces;
17751 }
17752 return spaces;
17753 };
17754 _proto.stringFrom = function stringFrom(tokens, from) {
17755 var result2 = "";
17756 for(var i2 = from; i2 < tokens.length; i2++){
17757 result2 += tokens[i2][1];
17758 }
17759 tokens.splice(from, tokens.length - from);
17760 return result2;
17761 };
17762 _proto.unclosedBlock = function unclosedBlock() {
17763 var pos = this.current.source.start;
17764 throw this.input.error("Unclosed block", pos.line, pos.column);
17765 };
17766 _proto.unclosedBracket = function unclosedBracket(bracket) {
17767 throw this.input.error("Unclosed bracket", {
17768 offset: bracket[2]
17769 }, {
17770 offset: bracket[2] + 1
17771 });
17772 };
17773 _proto.unexpectedClose = function unexpectedClose(token) {
17774 throw this.input.error("Unexpected }", {
17775 offset: token[2]
17776 }, {
17777 offset: token[2] + 1
17778 });
17779 };
17780 _proto.unknownWord = function unknownWord(tokens) {
17781 throw this.input.error("Unknown word", {
17782 offset: tokens[0][2]
17783 }, {
17784 offset: tokens[0][2] + tokens[0][1].length
17785 });
17786 };
17787 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
17788 throw this.input.error("At-rule without name", {
17789 offset: token[2]
17790 }, {
17791 offset: token[2] + token[1].length
17792 });
17793 };
17794 return Parser2;
17795 }();
17796 var parser = Parser$1;
17797 var Container$2 = container;
17798 var Parser22 = parser;
17799 var Input$2 = input;
17800 function parse$3(css, opts) {
17801 var input2 = new Input$2(css, opts);
17802 var parser2 = new Parser22(input2);
17803 try {
17804 parser2.parse();
17805 } catch (e2) {
17806 if (true) {
17807 if (e2.name === "CssSyntaxError" && opts && opts.from) {
17808 if (/\.scss$/i.test(opts.from)) {
17809 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
17810 } else if (/\.sass/i.test(opts.from)) {
17811 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
17812 } else if (/\.less$/i.test(opts.from)) {
17813 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
17814 }
17815 }
17816 }
17817 throw e2;
17818 }
17819 return parser2.root;
17820 }
17821 var parse_1 = parse$3;
17822 parse$3.default = parse$3;
17823 Container$2.registerParse(parse$3);
17824 var isClean = symbols.isClean, my = symbols.my;
17825 var MapGenerator$1 = mapGenerator;
17826 var stringify$2 = stringify_1;
17827 var Container$1 = container;
17828 var Document$2 = document$1$2;
17829 var warnOnce$1 = warnOnce$2;
17830 var Result$2 = result;
17831 var parse$2 = parse_1;
17832 var Root$3 = root;
17833 var TYPE_TO_CLASS_NAME = {
17834 atrule: "AtRule",
17835 comment: "Comment",
17836 decl: "Declaration",
17837 document: "Document",
17838 root: "Root",
17839 rule: "Rule"
17840 };
17841 var PLUGIN_PROPS = {
17842 AtRule: true,
17843 AtRuleExit: true,
17844 Comment: true,
17845 CommentExit: true,
17846 Declaration: true,
17847 DeclarationExit: true,
17848 Document: true,
17849 DocumentExit: true,
17850 Once: true,
17851 OnceExit: true,
17852 postcssPlugin: true,
17853 prepare: true,
17854 Root: true,
17855 RootExit: true,
17856 Rule: true,
17857 RuleExit: true
17858 };
17859 var NOT_VISITORS = {
17860 Once: true,
17861 postcssPlugin: true,
17862 prepare: true
17863 };
17864 var CHILDREN = 0;
17865 function isPromise(obj) {
17866 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
17867 }
17868 function getEvents(node2) {
17869 var key = false;
17870 var type = TYPE_TO_CLASS_NAME[node2.type];
17871 if (node2.type === "decl") {
17872 key = node2.prop.toLowerCase();
17873 } else if (node2.type === "atrule") {
17874 key = node2.name.toLowerCase();
17875 }
17876 if (key && node2.append) {
17877 return [
17878 type,
17879 type + "-" + key,
17880 CHILDREN,
17881 type + "Exit",
17882 type + "Exit-" + key
17883 ];
17884 } else if (key) {
17885 return [
17886 type,
17887 type + "-" + key,
17888 type + "Exit",
17889 type + "Exit-" + key
17890 ];
17891 } else if (node2.append) {
17892 return [
17893 type,
17894 CHILDREN,
17895 type + "Exit"
17896 ];
17897 } else {
17898 return [
17899 type,
17900 type + "Exit"
17901 ];
17902 }
17903 }
17904 function toStack(node2) {
17905 var events;
17906 if (node2.type === "document") {
17907 events = [
17908 "Document",
17909 CHILDREN,
17910 "DocumentExit"
17911 ];
17912 } else if (node2.type === "root") {
17913 events = [
17914 "Root",
17915 CHILDREN,
17916 "RootExit"
17917 ];
17918 } else {
17919 events = getEvents(node2);
17920 }
17921 return {
17922 eventIndex: 0,
17923 events: events,
17924 iterator: 0,
17925 node: node2,
17926 visitorIndex: 0,
17927 visitors: []
17928 };
17929 }
17930 function cleanMarks(node2) {
17931 node2[isClean] = false;
17932 if (node2.nodes) node2.nodes.forEach(function(i2) {
17933 return cleanMarks(i2);
17934 });
17935 return node2;
17936 }
17937 var postcss$2 = {};
17938 var LazyResult$2 = /*#__PURE__*/ function() {
17939 function LazyResult2(processor2, css, opts) {
17940 var _this = this;
17941 this.stringified = false;
17942 this.processed = false;
17943 var root2;
17944 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
17945 root2 = cleanMarks(css);
17946 } else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
17947 root2 = cleanMarks(css.root);
17948 if (css.map) {
17949 if (typeof opts.map === "undefined") opts.map = {};
17950 if (!opts.map.inline) opts.map.inline = false;
17951 opts.map.prev = css.map;
17952 }
17953 } else {
17954 var parser2 = parse$2;
17955 if (opts.syntax) parser2 = opts.syntax.parse;
17956 if (opts.parser) parser2 = opts.parser;
17957 if (parser2.parse) parser2 = parser2.parse;
17958 try {
17959 root2 = parser2(css, opts);
17960 } catch (error) {
17961 this.processed = true;
17962 this.error = error;
17963 }
17964 if (root2 && !root2[my]) {
17965 Container$1.rebuild(root2);
17966 }
17967 }
17968 this.result = new Result$2(processor2, root2, opts);
17969 this.helpers = _extends({}, postcss$2, {
17970 postcss: postcss$2,
17971 result: this.result
17972 });
17973 this.plugins = this.processor.plugins.map(function(plugin22) {
17974 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
17975 return _extends({}, plugin22, plugin22.prepare(_this.result));
17976 } else {
17977 return plugin22;
17978 }
17979 });
17980 }
17981 var _proto = LazyResult2.prototype;
17982 _proto.async = function async() {
17983 if (this.error) return Promise.reject(this.error);
17984 if (this.processed) return Promise.resolve(this.result);
17985 if (!this.processing) {
17986 this.processing = this.runAsync();
17987 }
17988 return this.processing;
17989 };
17990 _proto.catch = function _catch(onRejected) {
17991 return this.async().catch(onRejected);
17992 };
17993 _proto.finally = function _finally(onFinally) {
17994 return this.async().then(onFinally, onFinally);
17995 };
17996 _proto.getAsyncError = function getAsyncError() {
17997 throw new Error("Use process(css).then(cb) to work with async plugins");
17998 };
17999 _proto.handleError = function handleError(error, node2) {
18000 var plugin22 = this.result.lastPlugin;
18001 try {
18002 if (node2) node2.addToError(error);
18003 this.error = error;
18004 if (error.name === "CssSyntaxError" && !error.plugin) {
18005 error.plugin = plugin22.postcssPlugin;
18006 error.setMessage();
18007 } else if (plugin22.postcssVersion) {
18008 if (true) {
18009 var pluginName = plugin22.postcssPlugin;
18010 var pluginVer = plugin22.postcssVersion;
18011 var runtimeVer = this.result.processor.version;
18012 var a2 = pluginVer.split(".");
18013 var b = runtimeVer.split(".");
18014 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
18015 console.error("Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below.");
18016 }
18017 }
18018 }
18019 } catch (err) {
18020 if (console && console.error) console.error(err);
18021 }
18022 return error;
18023 };
18024 _proto.prepareVisitors = function prepareVisitors() {
18025 var _this = this;
18026 this.listeners = {};
18027 var add = function(plugin22, type, cb) {
18028 if (!_this.listeners[type]) _this.listeners[type] = [];
18029 _this.listeners[type].push([
18030 plugin22,
18031 cb
18032 ]);
18033 };
18034 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
18035 var plugin22 = _step.value;
18036 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
18037 for(var event in plugin22){
18038 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
18039 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
18040 }
18041 if (!NOT_VISITORS[event]) {
18042 if (_type_of(plugin22[event]) === "object") {
18043 for(var filter in plugin22[event]){
18044 if (filter === "*") {
18045 add(plugin22, event, plugin22[event][filter]);
18046 } else {
18047 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
18048 }
18049 }
18050 } else if (typeof plugin22[event] === "function") {
18051 add(plugin22, event, plugin22[event]);
18052 }
18053 }
18054 }
18055 }
18056 }
18057 this.hasListener = Object.keys(this.listeners).length > 0;
18058 };
18059 _proto.runAsync = function runAsync() {
18060 var _this = this;
18061 return _async_to_generator(function() {
18062 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
18063 return _ts_generator(this, function(_state) {
18064 switch(_state.label){
18065 case 0:
18066 _this.plugin = 0;
18067 i2 = 0;
18068 _state.label = 1;
18069 case 1:
18070 if (!(i2 < _this.plugins.length)) return [
18071 3,
18072 6
18073 ];
18074 plugin22 = _this.plugins[i2];
18075 promise = _this.runOnRoot(plugin22);
18076 if (!isPromise(promise)) return [
18077 3,
18078 5
18079 ];
18080 _state.label = 2;
18081 case 2:
18082 _state.trys.push([
18083 2,
18084 4,
18085 ,
18086 5
18087 ]);
18088 return [
18089 4,
18090 promise
18091 ];
18092 case 3:
18093 _state.sent();
18094 return [
18095 3,
18096 5
18097 ];
18098 case 4:
18099 error = _state.sent();
18100 throw _this.handleError(error);
18101 case 5:
18102 i2++;
18103 return [
18104 3,
18105 1
18106 ];
18107 case 6:
18108 _this.prepareVisitors();
18109 if (!_this.hasListener) return [
18110 3,
18111 18
18112 ];
18113 root2 = _this.result.root;
18114 _state.label = 7;
18115 case 7:
18116 if (!!root2[isClean]) return [
18117 3,
18118 14
18119 ];
18120 root2[isClean] = true;
18121 stack = [
18122 toStack(root2)
18123 ];
18124 _state.label = 8;
18125 case 8:
18126 if (!(stack.length > 0)) return [
18127 3,
18128 13
18129 ];
18130 promise1 = _this.visitTick(stack);
18131 if (!isPromise(promise1)) return [
18132 3,
18133 12
18134 ];
18135 _state.label = 9;
18136 case 9:
18137 _state.trys.push([
18138 9,
18139 11,
18140 ,
18141 12
18142 ]);
18143 return [
18144 4,
18145 promise1
18146 ];
18147 case 10:
18148 _state.sent();
18149 return [
18150 3,
18151 12
18152 ];
18153 case 11:
18154 e2 = _state.sent();
18155 node2 = stack[stack.length - 1].node;
18156 throw _this.handleError(e2, node2);
18157 case 12:
18158 return [
18159 3,
18160 8
18161 ];
18162 case 13:
18163 return [
18164 3,
18165 7
18166 ];
18167 case 14:
18168 if (!_this.listeners.OnceExit) return [
18169 3,
18170 18
18171 ];
18172 _loop = function() {
18173 var _step_value, plugin22, visitor, roots, e2;
18174 return _ts_generator(this, function(_state) {
18175 switch(_state.label){
18176 case 0:
18177 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
18178 _this.result.lastPlugin = plugin22;
18179 _state.label = 1;
18180 case 1:
18181 _state.trys.push([
18182 1,
18183 6,
18184 ,
18185 7
18186 ]);
18187 if (!(root2.type === "document")) return [
18188 3,
18189 3
18190 ];
18191 roots = root2.nodes.map(function(subRoot) {
18192 return visitor(subRoot, _this.helpers);
18193 });
18194 return [
18195 4,
18196 Promise.all(roots)
18197 ];
18198 case 2:
18199 _state.sent();
18200 return [
18201 3,
18202 5
18203 ];
18204 case 3:
18205 return [
18206 4,
18207 visitor(root2, _this.helpers)
18208 ];
18209 case 4:
18210 _state.sent();
18211 _state.label = 5;
18212 case 5:
18213 return [
18214 3,
18215 7
18216 ];
18217 case 6:
18218 e2 = _state.sent();
18219 throw _this.handleError(e2);
18220 case 7:
18221 return [
18222 2
18223 ];
18224 }
18225 });
18226 };
18227 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
18228 _state.label = 15;
18229 case 15:
18230 if (!!(_step = _iterator()).done) return [
18231 3,
18232 18
18233 ];
18234 return [
18235 5,
18236 _ts_values(_loop())
18237 ];
18238 case 16:
18239 _state.sent();
18240 _state.label = 17;
18241 case 17:
18242 return [
18243 3,
18244 15
18245 ];
18246 case 18:
18247 _this.processed = true;
18248 return [
18249 2,
18250 _this.stringify()
18251 ];
18252 }
18253 });
18254 })();
18255 };
18256 _proto.runOnRoot = function runOnRoot(plugin22) {
18257 var _this = this;
18258 this.result.lastPlugin = plugin22;
18259 try {
18260 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
18261 if (this.result.root.type === "document") {
18262 var roots = this.result.root.nodes.map(function(root2) {
18263 return plugin22.Once(root2, _this.helpers);
18264 });
18265 if (isPromise(roots[0])) {
18266 return Promise.all(roots);
18267 }
18268 return roots;
18269 }
18270 return plugin22.Once(this.result.root, this.helpers);
18271 } else if (typeof plugin22 === "function") {
18272 return plugin22(this.result.root, this.result);
18273 }
18274 } catch (error) {
18275 throw this.handleError(error);
18276 }
18277 };
18278 _proto.stringify = function stringify() {
18279 if (this.error) throw this.error;
18280 if (this.stringified) return this.result;
18281 this.stringified = true;
18282 this.sync();
18283 var opts = this.result.opts;
18284 var str = stringify$2;
18285 if (opts.syntax) str = opts.syntax.stringify;
18286 if (opts.stringifier) str = opts.stringifier;
18287 if (str.stringify) str = str.stringify;
18288 var map = new MapGenerator$1(str, this.result.root, this.result.opts);
18289 var data = map.generate();
18290 this.result.css = data[0];
18291 this.result.map = data[1];
18292 return this.result;
18293 };
18294 _proto.sync = function sync() {
18295 if (this.error) throw this.error;
18296 if (this.processed) return this.result;
18297 this.processed = true;
18298 if (this.processing) {
18299 throw this.getAsyncError();
18300 }
18301 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
18302 var plugin22 = _step.value;
18303 var promise = this.runOnRoot(plugin22);
18304 if (isPromise(promise)) {
18305 throw this.getAsyncError();
18306 }
18307 }
18308 this.prepareVisitors();
18309 if (this.hasListener) {
18310 var root2 = this.result.root;
18311 while(!root2[isClean]){
18312 root2[isClean] = true;
18313 this.walkSync(root2);
18314 }
18315 if (this.listeners.OnceExit) {
18316 if (root2.type === "document") {
18317 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
18318 var subRoot = _step1.value;
18319 this.visitSync(this.listeners.OnceExit, subRoot);
18320 }
18321 } else {
18322 this.visitSync(this.listeners.OnceExit, root2);
18323 }
18324 }
18325 }
18326 return this.result;
18327 };
18328 _proto.then = function then(onFulfilled, onRejected) {
18329 if (true) {
18330 if (!("from" in this.opts)) {
18331 warnOnce$1("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
18332 }
18333 }
18334 return this.async().then(onFulfilled, onRejected);
18335 };
18336 _proto.toString = function toString() {
18337 return this.css;
18338 };
18339 _proto.visitSync = function visitSync(visitors, node2) {
18340 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
18341 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
18342 this.result.lastPlugin = plugin22;
18343 var promise = void 0;
18344 try {
18345 promise = visitor(node2, this.helpers);
18346 } catch (e2) {
18347 throw this.handleError(e2, node2.proxyOf);
18348 }
18349 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
18350 return true;
18351 }
18352 if (isPromise(promise)) {
18353 throw this.getAsyncError();
18354 }
18355 }
18356 };
18357 _proto.visitTick = function visitTick(stack) {
18358 var visit2 = stack[stack.length - 1];
18359 var node2 = visit2.node, visitors = visit2.visitors;
18360 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
18361 stack.pop();
18362 return;
18363 }
18364 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
18365 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
18366 visit2.visitorIndex += 1;
18367 if (visit2.visitorIndex === visitors.length) {
18368 visit2.visitors = [];
18369 visit2.visitorIndex = 0;
18370 }
18371 this.result.lastPlugin = plugin22;
18372 try {
18373 return visitor(node2.toProxy(), this.helpers);
18374 } catch (e2) {
18375 throw this.handleError(e2, node2);
18376 }
18377 }
18378 if (visit2.iterator !== 0) {
18379 var iterator = visit2.iterator;
18380 var child;
18381 while(child = node2.nodes[node2.indexes[iterator]]){
18382 node2.indexes[iterator] += 1;
18383 if (!child[isClean]) {
18384 child[isClean] = true;
18385 stack.push(toStack(child));
18386 return;
18387 }
18388 }
18389 visit2.iterator = 0;
18390 delete node2.indexes[iterator];
18391 }
18392 var events = visit2.events;
18393 while(visit2.eventIndex < events.length){
18394 var event = events[visit2.eventIndex];
18395 visit2.eventIndex += 1;
18396 if (event === CHILDREN) {
18397 if (node2.nodes && node2.nodes.length) {
18398 node2[isClean] = true;
18399 visit2.iterator = node2.getIterator();
18400 }
18401 return;
18402 } else if (this.listeners[event]) {
18403 visit2.visitors = this.listeners[event];
18404 return;
18405 }
18406 }
18407 stack.pop();
18408 };
18409 _proto.walkSync = function walkSync(node2) {
18410 var _this = this;
18411 node2[isClean] = true;
18412 var events = getEvents(node2);
18413 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
18414 var event = _step.value;
18415 if (event === CHILDREN) {
18416 if (node2.nodes) {
18417 node2.each(function(child) {
18418 if (!child[isClean]) _this.walkSync(child);
18419 });
18420 }
18421 } else {
18422 var visitors = this.listeners[event];
18423 if (visitors) {
18424 if (this.visitSync(visitors, node2.toProxy())) return;
18425 }
18426 }
18427 }
18428 };
18429 _proto.warnings = function warnings() {
18430 return this.sync().warnings();
18431 };
18432 _create_class(LazyResult2, [
18433 {
18434 key: "content",
18435 get: function get() {
18436 return this.stringify().content;
18437 }
18438 },
18439 {
18440 key: "css",
18441 get: function get() {
18442 return this.stringify().css;
18443 }
18444 },
18445 {
18446 key: "map",
18447 get: function get() {
18448 return this.stringify().map;
18449 }
18450 },
18451 {
18452 key: "messages",
18453 get: function get() {
18454 return this.sync().messages;
18455 }
18456 },
18457 {
18458 key: "opts",
18459 get: function get() {
18460 return this.result.opts;
18461 }
18462 },
18463 {
18464 key: "processor",
18465 get: function get() {
18466 return this.result.processor;
18467 }
18468 },
18469 {
18470 key: "root",
18471 get: function get() {
18472 return this.sync().root;
18473 }
18474 },
18475 {
18476 key: Symbol.toStringTag,
18477 get: function get() {
18478 return "LazyResult";
18479 }
18480 }
18481 ]);
18482 return LazyResult2;
18483 }();
18484 LazyResult$2.registerPostcss = function(dependant) {
18485 postcss$2 = dependant;
18486 };
18487 var lazyResult = LazyResult$2;
18488 LazyResult$2.default = LazyResult$2;
18489 Root$3.registerLazyResult(LazyResult$2);
18490 Document$2.registerLazyResult(LazyResult$2);
18491 var MapGenerator22 = mapGenerator;
18492 var stringify$1 = stringify_1;
18493 var warnOnce22 = warnOnce$2;
18494 var parse$1 = parse_1;
18495 var Result$1 = result;
18496 var NoWorkResult$1 = /*#__PURE__*/ function() {
18497 function NoWorkResult2(processor2, css, opts) {
18498 css = css.toString();
18499 this.stringified = false;
18500 this._processor = processor2;
18501 this._css = css;
18502 this._opts = opts;
18503 this._map = void 0;
18504 var root2;
18505 var str = stringify$1;
18506 this.result = new Result$1(this._processor, root2, this._opts);
18507 this.result.css = css;
18508 var self = this;
18509 Object.defineProperty(this.result, "root", {
18510 get: function get() {
18511 return self.root;
18512 }
18513 });
18514 var map = new MapGenerator22(str, root2, this._opts, css);
18515 if (map.isMap()) {
18516 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
18517 if (generatedCSS) {
18518 this.result.css = generatedCSS;
18519 }
18520 if (generatedMap) {
18521 this.result.map = generatedMap;
18522 }
18523 } else {
18524 map.clearAnnotation();
18525 this.result.css = map.css;
18526 }
18527 }
18528 var _proto = NoWorkResult2.prototype;
18529 _proto.async = function async() {
18530 if (this.error) return Promise.reject(this.error);
18531 return Promise.resolve(this.result);
18532 };
18533 _proto.catch = function _catch(onRejected) {
18534 return this.async().catch(onRejected);
18535 };
18536 _proto.finally = function _finally(onFinally) {
18537 return this.async().then(onFinally, onFinally);
18538 };
18539 _proto.sync = function sync() {
18540 if (this.error) throw this.error;
18541 return this.result;
18542 };
18543 _proto.then = function then(onFulfilled, onRejected) {
18544 if (true) {
18545 if (!("from" in this._opts)) {
18546 warnOnce22("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.");
18547 }
18548 }
18549 return this.async().then(onFulfilled, onRejected);
18550 };
18551 _proto.toString = function toString() {
18552 return this._css;
18553 };
18554 _proto.warnings = function warnings() {
18555 return [];
18556 };
18557 _create_class(NoWorkResult2, [
18558 {
18559 key: "content",
18560 get: function get() {
18561 return this.result.css;
18562 }
18563 },
18564 {
18565 key: "css",
18566 get: function get() {
18567 return this.result.css;
18568 }
18569 },
18570 {
18571 key: "map",
18572 get: function get() {
18573 return this.result.map;
18574 }
18575 },
18576 {
18577 key: "messages",
18578 get: function get() {
18579 return [];
18580 }
18581 },
18582 {
18583 key: "opts",
18584 get: function get() {
18585 return this.result.opts;
18586 }
18587 },
18588 {
18589 key: "processor",
18590 get: function get() {
18591 return this.result.processor;
18592 }
18593 },
18594 {
18595 key: "root",
18596 get: function get() {
18597 if (this._root) {
18598 return this._root;
18599 }
18600 var root2;
18601 var parser2 = parse$1;
18602 try {
18603 root2 = parser2(this._css, this._opts);
18604 } catch (error) {
18605 this.error = error;
18606 }
18607 if (this.error) {
18608 throw this.error;
18609 } else {
18610 this._root = root2;
18611 return root2;
18612 }
18613 }
18614 },
18615 {
18616 key: Symbol.toStringTag,
18617 get: function get() {
18618 return "NoWorkResult";
18619 }
18620 }
18621 ]);
18622 return NoWorkResult2;
18623 }();
18624 var noWorkResult = NoWorkResult$1;
18625 NoWorkResult$1.default = NoWorkResult$1;
18626 var NoWorkResult22 = noWorkResult;
18627 var LazyResult$1 = lazyResult;
18628 var Document$1 = document$1$2;
18629 var Root$2 = root;
18630 var Processor$1 = /*#__PURE__*/ function() {
18631 function Processor2(plugins) {
18632 if (plugins === void 0) plugins = [];
18633 this.version = "8.4.38";
18634 this.plugins = this.normalize(plugins);
18635 }
18636 var _proto = Processor2.prototype;
18637 _proto.normalize = function normalize(plugins) {
18638 var normalized = [];
18639 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
18640 var i2 = _step.value;
18641 if (i2.postcss === true) {
18642 i2 = i2();
18643 } else if (i2.postcss) {
18644 i2 = i2.postcss;
18645 }
18646 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
18647 normalized = normalized.concat(i2.plugins);
18648 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
18649 normalized.push(i2);
18650 } else if (typeof i2 === "function") {
18651 normalized.push(i2);
18652 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
18653 if (true) {
18654 throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.");
18655 }
18656 } else {
18657 throw new Error(i2 + " is not a PostCSS plugin");
18658 }
18659 }
18660 return normalized;
18661 };
18662 _proto.process = function process1(css, opts) {
18663 if (opts === void 0) opts = {};
18664 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
18665 return new NoWorkResult22(this, css, opts);
18666 } else {
18667 return new LazyResult$1(this, css, opts);
18668 }
18669 };
18670 _proto.use = function use(plugin22) {
18671 this.plugins = this.plugins.concat(this.normalize([
18672 plugin22
18673 ]));
18674 return this;
18675 };
18676 return Processor2;
18677 }();
18678 var processor = Processor$1;
18679 Processor$1.default = Processor$1;
18680 Root$2.registerProcessor(Processor$1);
18681 Document$1.registerProcessor(Processor$1);
18682 var Declaration$1 = declaration;
18683 var PreviousMap22 = previousMap;
18684 var Comment$1 = comment;
18685 var AtRule$1 = atRule;
18686 var Input$1 = input;
18687 var Root$1 = root;
18688 var Rule$1 = rule;
18689 function fromJSON$1(json, inputs) {
18690 if (Array.isArray(json)) return json.map(function(n2) {
18691 return fromJSON$1(n2);
18692 });
18693 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
18694 "inputs"
18695 ]);
18696 if (ownInputs) {
18697 inputs = [];
18698 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
18699 var input2 = _step.value;
18700 var inputHydrated = _extends({}, input2, {
18701 __proto__: Input$1.prototype
18702 });
18703 if (inputHydrated.map) {
18704 inputHydrated.map = _extends({}, inputHydrated.map, {
18705 __proto__: PreviousMap22.prototype
18706 });
18707 }
18708 inputs.push(inputHydrated);
18709 }
18710 }
18711 if (defaults.nodes) {
18712 defaults.nodes = json.nodes.map(function(n2) {
18713 return fromJSON$1(n2, inputs);
18714 });
18715 }
18716 if (defaults.source) {
18717 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
18718 "inputId"
18719 ]);
18720 defaults.source = source;
18721 if (inputId != null) {
18722 defaults.source.input = inputs[inputId];
18723 }
18724 }
18725 if (defaults.type === "root") {
18726 return new Root$1(defaults);
18727 } else if (defaults.type === "decl") {
18728 return new Declaration$1(defaults);
18729 } else if (defaults.type === "rule") {
18730 return new Rule$1(defaults);
18731 } else if (defaults.type === "comment") {
18732 return new Comment$1(defaults);
18733 } else if (defaults.type === "atrule") {
18734 return new AtRule$1(defaults);
18735 } else {
18736 throw new Error("Unknown node type: " + json.type);
18737 }
18738 }
18739 var fromJSON_1 = fromJSON$1;
18740 fromJSON$1.default = fromJSON$1;
18741 var CssSyntaxError22 = cssSyntaxError;
18742 var Declaration22 = declaration;
18743 var LazyResult22 = lazyResult;
18744 var Container22 = container;
18745 var Processor22 = processor;
18746 var stringify = stringify_1;
18747 var fromJSON = fromJSON_1;
18748 var Document222 = document$1$2;
18749 var Warning22 = warning;
18750 var Comment22 = comment;
18751 var AtRule22 = atRule;
18752 var Result22 = result;
18753 var Input22 = input;
18754 var parse = parse_1;
18755 var list = list_1;
18756 var Rule22 = rule;
18757 var Root22 = root;
18758 var Node22 = node;
18759 function postcss() {
18760 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
18761 plugins[_key] = arguments[_key];
18762 }
18763 if (plugins.length === 1 && Array.isArray(plugins[0])) {
18764 plugins = plugins[0];
18765 }
18766 return new Processor22(plugins);
18767 }
18768 postcss.plugin = function plugin2(name, initializer) {
18769 var warningPrinted = false;
18770 function creator() {
18771 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
18772 args[_key] = arguments[_key];
18773 }
18774 if (console && console.warn && !warningPrinted) {
18775 warningPrinted = true;
18776 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
18777 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
18778 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
18779 }
18780 }
18781 var transformer = initializer.apply(void 0, [].concat(args));
18782 transformer.postcssPlugin = name;
18783 transformer.postcssVersion = new Processor22().version;
18784 return transformer;
18785 }
18786 var cache;
18787 Object.defineProperty(creator, "postcss", {
18788 get: function get() {
18789 if (!cache) cache = creator();
18790 return cache;
18791 }
18792 });
18793 creator.process = function(css, processOpts, pluginOpts) {
18794 return postcss([
18795 creator(pluginOpts)
18796 ]).process(css, processOpts);
18797 };
18798 return creator;
18799 };
18800 postcss.stringify = stringify;
18801 postcss.parse = parse;
18802 postcss.fromJSON = fromJSON;
18803 postcss.list = list;
18804 postcss.comment = function(defaults) {
18805 return new Comment22(defaults);
18806 };
18807 postcss.atRule = function(defaults) {
18808 return new AtRule22(defaults);
18809 };
18810 postcss.decl = function(defaults) {
18811 return new Declaration22(defaults);
18812 };
18813 postcss.rule = function(defaults) {
18814 return new Rule22(defaults);
18815 };
18816 postcss.root = function(defaults) {
18817 return new Root22(defaults);
18818 };
18819 postcss.document = function(defaults) {
18820 return new Document222(defaults);
18821 };
18822 postcss.CssSyntaxError = CssSyntaxError22;
18823 postcss.Declaration = Declaration22;
18824 postcss.Container = Container22;
18825 postcss.Processor = Processor22;
18826 postcss.Document = Document222;
18827 postcss.Comment = Comment22;
18828 postcss.Warning = Warning22;
18829 postcss.AtRule = AtRule22;
18830 postcss.Result = Result22;
18831 postcss.Input = Input22;
18832 postcss.Rule = Rule22;
18833 postcss.Root = Root22;
18834 postcss.Node = Node22;
18835 LazyResult22.registerPostcss(postcss);
18836 var postcss_1 = postcss;
18837 postcss.default = postcss;
18838 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
18839 postcss$1.stringify;
18840 postcss$1.fromJSON;
18841 postcss$1.plugin;
18842 postcss$1.parse;
18843 postcss$1.list;
18844 postcss$1.document;
18845 postcss$1.comment;
18846 postcss$1.atRule;
18847 postcss$1.rule;
18848 postcss$1.decl;
18849 postcss$1.root;
18850 postcss$1.CssSyntaxError;
18851 postcss$1.Declaration;
18852 postcss$1.Container;
18853 postcss$1.Processor;
18854 postcss$1.Document;
18855 postcss$1.Comment;
18856 postcss$1.Warning;
18857 postcss$1.AtRule;
18858 postcss$1.Result;
18859 postcss$1.Input;
18860 postcss$1.Rule;
18861 postcss$1.Root;
18862 postcss$1.Node;
18863 var BaseRRNode = /*#__PURE__*/ function() {
18864 function BaseRRNode() {
18865 for(var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++){
18866 _args[_key] = arguments[_key];
18867 }
18868 __publicField2(this, "parentElement", null);
18869 __publicField2(this, "parentNode", null);
18870 __publicField2(this, "ownerDocument");
18871 __publicField2(this, "firstChild", null);
18872 __publicField2(this, "lastChild", null);
18873 __publicField2(this, "previousSibling", null);
18874 __publicField2(this, "nextSibling", null);
18875 __publicField2(this, "ELEMENT_NODE", 1);
18876 __publicField2(this, "TEXT_NODE", 3);
18877 __publicField2(this, "nodeType");
18878 __publicField2(this, "nodeName");
18879 __publicField2(this, "RRNodeType");
18880 }
18881 var _proto = BaseRRNode.prototype;
18882 _proto.contains = function contains(node2) {
18883 if (!_instanceof(node2, BaseRRNode)) return false;
18884 else if (node2.ownerDocument !== this.ownerDocument) return false;
18885 else if (node2 === this) return true;
18886 while(node2.parentNode){
18887 if (node2.parentNode === this) return true;
18888 node2 = node2.parentNode;
18889 }
18890 return false;
18891 };
18892 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18893 _proto.appendChild = function appendChild(_newChild) {
18894 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
18895 };
18896 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18897 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
18898 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
18899 };
18900 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18901 _proto.removeChild = function removeChild(_node) {
18902 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
18903 };
18904 _proto.toString = function toString() {
18905 return "RRNode";
18906 };
18907 _create_class(BaseRRNode, [
18908 {
18909 key: "childNodes",
18910 get: function get() {
18911 var childNodes2 = [];
18912 var childIterator = this.firstChild;
18913 while(childIterator){
18914 childNodes2.push(childIterator);
18915 childIterator = childIterator.nextSibling;
18916 }
18917 return childNodes2;
18918 }
18919 }
18920 ]);
18921 return BaseRRNode;
18922 }();
18923 var testableAccessors = {
18924 Node: [
18925 "childNodes",
18926 "parentNode",
18927 "parentElement",
18928 "textContent"
18929 ],
18930 ShadowRoot: [
18931 "host",
18932 "styleSheets"
18933 ],
18934 Element: [
18935 "shadowRoot",
18936 "querySelector",
18937 "querySelectorAll"
18938 ],
18939 MutationObserver: []
18940 };
18941 var testableMethods = {
18942 Node: [
18943 "contains",
18944 "getRootNode"
18945 ],
18946 ShadowRoot: [
18947 "getSelection"
18948 ],
18949 Element: [],
18950 MutationObserver: [
18951 "constructor"
18952 ]
18953 };
18954 var untaintedBasePrototype = {};
18955 var isAngularZonePresent = function() {
18956 return !!globalThis.Zone;
18957 };
18958 function getUntaintedPrototype(key) {
18959 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
18960 var defaultObj = globalThis[key];
18961 var defaultPrototype = defaultObj.prototype;
18962 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
18963 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
18964 accessorNames.every(function(accessor) {
18965 var _a2, _b;
18966 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
18967 }));
18968 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
18969 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
18970 function(method) {
18971 var _a2;
18972 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
18973 }));
18974 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
18975 untaintedBasePrototype[key] = defaultObj.prototype;
18976 return defaultObj.prototype;
18977 }
18978 try {
18979 var iframeEl = document.createElement("iframe");
18980 document.body.appendChild(iframeEl);
18981 var win = iframeEl.contentWindow;
18982 if (!win) return defaultObj.prototype;
18983 var untaintedObject = win[key].prototype;
18984 document.body.removeChild(iframeEl);
18985 if (!untaintedObject) return defaultPrototype;
18986 return untaintedBasePrototype[key] = untaintedObject;
18987 } catch (e) {
18988 return defaultPrototype;
18989 }
18990 }
18991 var untaintedAccessorCache = {};
18992 function getUntaintedAccessor(key, instance, accessor) {
18993 var _a2;
18994 var cacheKey = key + "." + String(accessor);
18995 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
18996 var untaintedPrototype = getUntaintedPrototype(key);
18997 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
18998 if (!untaintedAccessor) return instance[accessor];
18999 untaintedAccessorCache[cacheKey] = untaintedAccessor;
19000 return untaintedAccessor.call(instance);
19001 }
19002 var untaintedMethodCache = {};
19003 function getUntaintedMethod(key, instance, method) {
19004 var cacheKey = key + "." + String(method);
19005 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
19006 var untaintedPrototype = getUntaintedPrototype(key);
19007 var untaintedMethod = untaintedPrototype[method];
19008 if (typeof untaintedMethod !== "function") return instance[method];
19009 untaintedMethodCache[cacheKey] = untaintedMethod;
19010 return untaintedMethod.bind(instance);
19011 }
19012 function childNodes(n2) {
19013 return getUntaintedAccessor("Node", n2, "childNodes");
19014 }
19015 function parentNode(n2) {
19016 return getUntaintedAccessor("Node", n2, "parentNode");
19017 }
19018 function parentElement(n2) {
19019 return getUntaintedAccessor("Node", n2, "parentElement");
19020 }
19021 function textContent(n2) {
19022 return getUntaintedAccessor("Node", n2, "textContent");
19023 }
19024 function contains(n2, other) {
19025 return getUntaintedMethod("Node", n2, "contains")(other);
19026 }
19027 function getRootNode(n2) {
19028 return getUntaintedMethod("Node", n2, "getRootNode")();
19029 }
19030 function host(n2) {
19031 if (!n2 || !("host" in n2)) return null;
19032 return getUntaintedAccessor("ShadowRoot", n2, "host");
19033 }
19034 function styleSheets(n2) {
19035 return n2.styleSheets;
19036 }
19037 function shadowRoot(n2) {
19038 if (!n2 || !("shadowRoot" in n2)) return null;
19039 return getUntaintedAccessor("Element", n2, "shadowRoot");
19040 }
19041 function querySelector(n2, selectors) {
19042 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
19043 }
19044 function querySelectorAll(n2, selectors) {
19045 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
19046 }
19047 function mutationObserverCtor() {
19048 return getUntaintedPrototype("MutationObserver").constructor;
19049 }
19050 function patch(source, name, replacement) {
19051 try {
19052 if (!(name in source)) {
19053 return function() {};
19054 }
19055 var original = source[name];
19056 var wrapped = replacement(original);
19057 if (typeof wrapped === "function") {
19058 wrapped.prototype = wrapped.prototype || {};
19059 Object.defineProperties(wrapped, {
19060 __rrweb_original__: {
19061 enumerable: false,
19062 value: original
19063 }
19064 });
19065 }
19066 source[name] = wrapped;
19067 return function() {
19068 source[name] = original;
19069 };
19070 } catch (e) {
19071 return function() {};
19072 }
19073 }
19074 var index = {
19075 childNodes: childNodes,
19076 parentNode: parentNode,
19077 parentElement: parentElement,
19078 textContent: textContent,
19079 contains: contains,
19080 getRootNode: getRootNode,
19081 host: host,
19082 styleSheets: styleSheets,
19083 shadowRoot: shadowRoot,
19084 querySelector: querySelector,
19085 querySelectorAll: querySelectorAll,
19086 mutationObserver: mutationObserverCtor,
19087 patch: patch
19088 };
19089 function on(type, fn, target) {
19090 if (target === void 0) target = document;
19091 var options = {
19092 capture: true,
19093 passive: true
19094 };
19095 target.addEventListener(type, fn, options);
19096 return function() {
19097 return target.removeEventListener(type, fn, options);
19098 };
19099 }
19100 var DEPARTED_MIRROR_ACCESS_WARNING = "Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";
19101 var _mirror = {
19102 map: {},
19103 getId: function getId() {
19104 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19105 return -1;
19106 },
19107 getNode: function getNode() {
19108 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19109 return null;
19110 },
19111 removeNodeFromMap: function removeNodeFromMap() {
19112 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19113 },
19114 has: function has() {
19115 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19116 return false;
19117 },
19118 reset: function reset() {
19119 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19120 }
19121 };
19122 if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
19123 _mirror = new Proxy(_mirror, {
19124 get: function get(target, prop, receiver) {
19125 if (prop === "map") {
19126 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19127 }
19128 return Reflect.get(target, prop, receiver);
19129 }
19130 });
19131 }
19132 function throttle(func, wait, options) {
19133 if (options === void 0) options = {};
19134 var timeout = null;
19135 var previous = 0;
19136 return function() {
19137 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19138 args[_key] = arguments[_key];
19139 }
19140 var now = Date.now();
19141 if (!previous && options.leading === false) {
19142 previous = now;
19143 }
19144 var remaining = wait - (now - previous);
19145 var context = this;
19146 if (remaining <= 0 || remaining > wait) {
19147 if (timeout) {
19148 clearTimeout(timeout);
19149 timeout = null;
19150 }
19151 previous = now;
19152 func.apply(context, args);
19153 } else if (!timeout && options.trailing !== false) {
19154 timeout = setTimeout(function() {
19155 previous = options.leading === false ? 0 : Date.now();
19156 timeout = null;
19157 func.apply(context, args);
19158 }, remaining);
19159 }
19160 };
19161 }
19162 function hookSetter(target, key, d, isRevoked, win) {
19163 if (win === void 0) win = window;
19164 var original = win.Object.getOwnPropertyDescriptor(target, key);
19165 win.Object.defineProperty(target, key, isRevoked ? d : {
19166 set: function set(value) {
19167 var _this = this;
19168 setTimeout(function() {
19169 d.set.call(_this, value);
19170 }, 0);
19171 if (original && original.set) {
19172 original.set.call(this, value);
19173 }
19174 }
19175 });
19176 return function() {
19177 return hookSetter(target, key, original || {}, true);
19178 };
19179 }
19180 var nowTimestamp = Date.now;
19181 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {
19182 nowTimestamp = function() {
19183 return /* @__PURE__ */ new Date().getTime();
19184 };
19185 }
19186 function getWindowScroll(win) {
19187 var _a2, _b, _c, _d;
19188 var doc = win.document;
19189 return {
19190 left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc.documentElement.scrollLeft || (doc == null ? void 0 : doc.body) && ((_a2 = index.parentElement(doc.body)) == null ? void 0 : _a2.scrollLeft) || ((_b = doc == null ? void 0 : doc.body) == null ? void 0 : _b.scrollLeft) || 0,
19191 top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : (doc == null ? void 0 : doc.documentElement.scrollTop) || (doc == null ? void 0 : doc.body) && ((_c = index.parentElement(doc.body)) == null ? void 0 : _c.scrollTop) || ((_d = doc == null ? void 0 : doc.body) == null ? void 0 : _d.scrollTop) || 0
19192 };
19193 }
19194 function getWindowHeight() {
19195 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
19196 }
19197 function getWindowWidth() {
19198 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
19199 }
19200 function closestElementOfNode(node2) {
19201 if (!node2) {
19202 return null;
19203 }
19204 var el = node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
19205 return el;
19206 }
19207 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
19208 if (!node2) {
19209 return false;
19210 }
19211 var el = closestElementOfNode(node2);
19212 if (!el) {
19213 return false;
19214 }
19215 try {
19216 if (typeof blockClass === "string") {
19217 if (el.classList.contains(blockClass)) return true;
19218 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
19219 } else {
19220 if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
19221 }
19222 } catch (e2) {}
19223 if (blockSelector) {
19224 if (el.matches(blockSelector)) return true;
19225 if (checkAncestors && el.closest(blockSelector) !== null) return true;
19226 }
19227 return false;
19228 }
19229 function isSerialized(n2, mirror2) {
19230 return mirror2.getId(n2) !== -1;
19231 }
19232 function isIgnored(n2, mirror2, slimDOMOptions) {
19233 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) {
19234 return true;
19235 }
19236 return mirror2.getId(n2) === IGNORED_NODE;
19237 }
19238 function isAncestorRemoved(target, mirror2) {
19239 if (isShadowRoot(target)) {
19240 return false;
19241 }
19242 var id = mirror2.getId(target);
19243 if (!mirror2.has(id)) {
19244 return true;
19245 }
19246 var parent = index.parentNode(target);
19247 if (parent && parent.nodeType === target.DOCUMENT_NODE) {
19248 return false;
19249 }
19250 if (!parent) {
19251 return true;
19252 }
19253 return isAncestorRemoved(parent, mirror2);
19254 }
19255 function legacy_isTouchEvent(event) {
19256 return Boolean(event.changedTouches);
19257 }
19258 function polyfill$1(win) {
19259 if (win === void 0) win = window;
19260 if ("NodeList" in win && !win.NodeList.prototype.forEach) {
19261 win.NodeList.prototype.forEach = Array.prototype.forEach;
19262 }
19263 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
19264 win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
19265 }
19266 }
19267 function isSerializedIframe(n2, mirror2) {
19268 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
19269 }
19270 function isSerializedStylesheet(n2, mirror2) {
19271 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
19272 }
19273 function hasShadowRoot(n2) {
19274 if (!n2) return false;
19275 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) {
19276 return Boolean(n2.shadowRoot);
19277 }
19278 return Boolean(index.shadowRoot(n2));
19279 }
19280 var StyleSheetMirror = /*#__PURE__*/ function() {
19281 function StyleSheetMirror() {
19282 __publicField(this, "id", 1);
19283 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
19284 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
19285 }
19286 var _proto = StyleSheetMirror.prototype;
19287 _proto.getId = function getId(stylesheet) {
19288 var _this_styleIDMap_get;
19289 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
19290 };
19291 _proto.has = function has(stylesheet) {
19292 return this.styleIDMap.has(stylesheet);
19293 };
19294 /**
19295 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
19296 */ _proto.add = function add(stylesheet, id) {
19297 if (this.has(stylesheet)) return this.getId(stylesheet);
19298 var newId;
19299 if (id === void 0) {
19300 newId = this.id++;
19301 } else newId = id;
19302 this.styleIDMap.set(stylesheet, newId);
19303 this.idStyleMap.set(newId, stylesheet);
19304 return newId;
19305 };
19306 _proto.getStyle = function getStyle(id) {
19307 return this.idStyleMap.get(id) || null;
19308 };
19309 _proto.reset = function reset() {
19310 this.styleIDMap = /* @__PURE__ */ new WeakMap();
19311 this.idStyleMap = /* @__PURE__ */ new Map();
19312 this.id = 1;
19313 };
19314 _proto.generateId = function generateId() {
19315 return this.id++;
19316 };
19317 return StyleSheetMirror;
19318 }();
19319 function getShadowHost(n2) {
19320 var _a2;
19321 var shadowHost = null;
19322 if ("getRootNode" in n2 && ((_a2 = index.getRootNode(n2)) == null ? void 0 : _a2.nodeType) === Node.DOCUMENT_FRAGMENT_NODE && index.host(index.getRootNode(n2))) shadowHost = index.host(index.getRootNode(n2));
19323 return shadowHost;
19324 }
19325 function getRootShadowHost(n2) {
19326 var rootShadowHost = n2;
19327 var shadowHost;
19328 while(shadowHost = getShadowHost(rootShadowHost))rootShadowHost = shadowHost;
19329 return rootShadowHost;
19330 }
19331 function shadowHostInDom(n2) {
19332 var doc = n2.ownerDocument;
19333 if (!doc) return false;
19334 var shadowHost = getRootShadowHost(n2);
19335 return index.contains(doc, shadowHost);
19336 }
19337 function inDom(n2) {
19338 var doc = n2.ownerDocument;
19339 if (!doc) return false;
19340 return index.contains(doc, n2) || shadowHostInDom(n2);
19341 }
19342 var EventType = /* @__PURE__ */ function(EventType2) {
19343 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
19344 EventType2[EventType2["Load"] = 1] = "Load";
19345 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
19346 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
19347 EventType2[EventType2["Meta"] = 4] = "Meta";
19348 EventType2[EventType2["Custom"] = 5] = "Custom";
19349 EventType2[EventType2["Plugin"] = 6] = "Plugin";
19350 return EventType2;
19351 }(EventType || {});
19352 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
19353 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
19354 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
19355 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
19356 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
19357 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
19358 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
19359 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
19360 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
19361 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
19362 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
19363 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
19364 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
19365 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
19366 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
19367 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
19368 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
19369 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
19370 return IncrementalSource2;
19371 }(IncrementalSource || {});
19372 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
19373 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
19374 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
19375 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
19376 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
19377 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
19378 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
19379 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
19380 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
19381 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
19382 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
19383 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
19384 return MouseInteractions2;
19385 }(MouseInteractions || {});
19386 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
19387 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
19388 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
19389 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
19390 return PointerTypes2;
19391 }(PointerTypes || {});
19392 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
19393 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
19394 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
19395 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
19396 return CanvasContext2;
19397 }(CanvasContext || {});
19398 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
19399 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
19400 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
19401 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
19402 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
19403 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
19404 return MediaInteractions2;
19405 }(MediaInteractions || {});
19406 var NodeType = /* @__PURE__ */ function(NodeType2) {
19407 NodeType2[NodeType2["Document"] = 0] = "Document";
19408 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
19409 NodeType2[NodeType2["Element"] = 2] = "Element";
19410 NodeType2[NodeType2["Text"] = 3] = "Text";
19411 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
19412 NodeType2[NodeType2["Comment"] = 5] = "Comment";
19413 return NodeType2;
19414 }(NodeType || {});
19415 function isNodeInLinkedList(n2) {
19416 return "__ln" in n2;
19417 }
19418 var DoubleLinkedList = /*#__PURE__*/ function() {
19419 function DoubleLinkedList() {
19420 __publicField(this, "length", 0);
19421 __publicField(this, "head", null);
19422 __publicField(this, "tail", null);
19423 }
19424 var _proto = DoubleLinkedList.prototype;
19425 _proto.get = function get(position) {
19426 if (position >= this.length) {
19427 throw new Error("Position outside of list range");
19428 }
19429 var current = this.head;
19430 for(var index2 = 0; index2 < position; index2++){
19431 current = (current == null ? void 0 : current.next) || null;
19432 }
19433 return current;
19434 };
19435 _proto.addNode = function addNode(n2) {
19436 var node2 = {
19437 value: n2,
19438 previous: null,
19439 next: null
19440 };
19441 n2.__ln = node2;
19442 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
19443 var current = n2.previousSibling.__ln.next;
19444 node2.next = current;
19445 node2.previous = n2.previousSibling.__ln;
19446 n2.previousSibling.__ln.next = node2;
19447 if (current) {
19448 current.previous = node2;
19449 }
19450 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
19451 var current1 = n2.nextSibling.__ln.previous;
19452 node2.previous = current1;
19453 node2.next = n2.nextSibling.__ln;
19454 n2.nextSibling.__ln.previous = node2;
19455 if (current1) {
19456 current1.next = node2;
19457 }
19458 } else {
19459 if (this.head) {
19460 this.head.previous = node2;
19461 }
19462 node2.next = this.head;
19463 this.head = node2;
19464 }
19465 if (node2.next === null) {
19466 this.tail = node2;
19467 }
19468 this.length++;
19469 };
19470 _proto.removeNode = function removeNode(n2) {
19471 var current = n2.__ln;
19472 if (!this.head) {
19473 return;
19474 }
19475 if (!current.previous) {
19476 this.head = current.next;
19477 if (this.head) {
19478 this.head.previous = null;
19479 } else {
19480 this.tail = null;
19481 }
19482 } else {
19483 current.previous.next = current.next;
19484 if (current.next) {
19485 current.next.previous = current.previous;
19486 } else {
19487 this.tail = current.previous;
19488 }
19489 }
19490 if (n2.__ln) {
19491 delete n2.__ln;
19492 }
19493 this.length--;
19494 };
19495 return DoubleLinkedList;
19496 }();
19497 var moveKey = function(id, parentId) {
19498 return id + "@" + parentId;
19499 };
19500 var MutationBuffer = /*#__PURE__*/ function() {
19501 function MutationBuffer() {
19502 var _this = this;
19503 __publicField(this, "frozen", false);
19504 __publicField(this, "locked", false);
19505 __publicField(this, "texts", []);
19506 __publicField(this, "attributes", []);
19507 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
19508 __publicField(this, "removes", []);
19509 __publicField(this, "mapRemoves", []);
19510 __publicField(this, "movedMap", {});
19511 /**
19512 * the browser MutationObserver emits multiple mutations after
19513 * a delay for performance reasons, making tracing added nodes hard
19514 * in our `processMutations` callback function.
19515 * For example, if we append an element el_1 into body, and then append
19516 * another element el_2 into el_1, these two mutations may be passed to the
19517 * callback function together when the two operations were done.
19518 * Generally we need to trace child nodes of newly added nodes, but in this
19519 * case if we count el_2 as el_1's child node in the first mutation record,
19520 * then we will count el_2 again in the second mutation record which was
19521 * duplicated.
19522 * To avoid of duplicate counting added nodes, we use a Set to store
19523 * added nodes and its child nodes during iterate mutation records. Then
19524 * collect added nodes from the Set which have no duplicate copy. But
19525 * this also causes newly added nodes will not be serialized with id ASAP,
19526 * which means all the id related calculation should be lazy too.
19527 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
19528 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
19529 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
19530 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
19531 __publicField(this, "mutationCb");
19532 __publicField(this, "blockClass");
19533 __publicField(this, "blockSelector");
19534 __publicField(this, "maskTextClass");
19535 __publicField(this, "maskTextSelector");
19536 __publicField(this, "inlineStylesheet");
19537 __publicField(this, "maskInputOptions");
19538 __publicField(this, "maskTextFn");
19539 __publicField(this, "maskInputFn");
19540 __publicField(this, "keepIframeSrcFn");
19541 __publicField(this, "recordCanvas");
19542 __publicField(this, "inlineImages");
19543 __publicField(this, "slimDOMOptions");
19544 __publicField(this, "dataURLOptions");
19545 __publicField(this, "doc");
19546 __publicField(this, "mirror");
19547 __publicField(this, "iframeManager");
19548 __publicField(this, "stylesheetManager");
19549 __publicField(this, "shadowDomManager");
19550 __publicField(this, "canvasManager");
19551 __publicField(this, "processedNodeManager");
19552 __publicField(this, "unattachedDoc");
19553 __publicField(this, "processMutations", function(mutations) {
19554 mutations.forEach(_this.processMutation);
19555 _this.emit();
19556 });
19557 __publicField(this, "emit", function() {
19558 if (_this.frozen || _this.locked) {
19559 return;
19560 }
19561 var adds = [];
19562 var addedIds = /* @__PURE__ */ new Set();
19563 var addList = new DoubleLinkedList();
19564 var getNextId = function(n2) {
19565 var ns = n2;
19566 var nextId = IGNORED_NODE;
19567 while(nextId === IGNORED_NODE){
19568 ns = ns && ns.nextSibling;
19569 nextId = ns && _this.mirror.getId(ns);
19570 }
19571 return nextId;
19572 };
19573 var pushAdd = function(n2) {
19574 var parent = index.parentNode(n2);
19575 if (!parent || !inDom(n2)) {
19576 return;
19577 }
19578 var cssCaptured = false;
19579 if (n2.nodeType === Node.TEXT_NODE) {
19580 var parentTag = parent.tagName;
19581 if (parentTag === "TEXTAREA") {
19582 return;
19583 } else if (parentTag === "STYLE" && _this.addedSet.has(parent)) {
19584 cssCaptured = true;
19585 }
19586 }
19587 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
19588 var nextId = getNextId(n2);
19589 if (parentId === -1 || nextId === -1) {
19590 return addList.addNode(n2);
19591 }
19592 var sn = serializeNodeWithId(n2, {
19593 doc: _this.doc,
19594 mirror: _this.mirror,
19595 blockClass: _this.blockClass,
19596 blockSelector: _this.blockSelector,
19597 maskTextClass: _this.maskTextClass,
19598 maskTextSelector: _this.maskTextSelector,
19599 skipChild: true,
19600 newlyAddedElement: true,
19601 inlineStylesheet: _this.inlineStylesheet,
19602 maskInputOptions: _this.maskInputOptions,
19603 maskTextFn: _this.maskTextFn,
19604 maskInputFn: _this.maskInputFn,
19605 slimDOMOptions: _this.slimDOMOptions,
19606 dataURLOptions: _this.dataURLOptions,
19607 recordCanvas: _this.recordCanvas,
19608 inlineImages: _this.inlineImages,
19609 onSerialize: function(currentN) {
19610 if (isSerializedIframe(currentN, _this.mirror)) {
19611 _this.iframeManager.addIframe(currentN);
19612 }
19613 if (isSerializedStylesheet(currentN, _this.mirror)) {
19614 _this.stylesheetManager.trackLinkElement(currentN);
19615 }
19616 if (hasShadowRoot(n2)) {
19617 _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
19618 }
19619 },
19620 onIframeLoad: function(iframe, childSn) {
19621 _this.iframeManager.attachIframe(iframe, childSn);
19622 _this.shadowDomManager.observeAttachShadow(iframe);
19623 },
19624 onStylesheetLoad: function(link, childSn) {
19625 _this.stylesheetManager.attachLinkElement(link, childSn);
19626 },
19627 cssCaptured: cssCaptured
19628 });
19629 if (sn) {
19630 adds.push({
19631 parentId: parentId,
19632 nextId: nextId,
19633 node: sn
19634 });
19635 addedIds.add(sn.id);
19636 }
19637 };
19638 while(_this.mapRemoves.length){
19639 _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
19640 }
19641 for(var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;){
19642 var n2 = _step.value;
19643 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) {
19644 continue;
19645 }
19646 pushAdd(n2);
19647 }
19648 for(var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;){
19649 var n21 = _step1.value;
19650 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) {
19651 pushAdd(n21);
19652 } else if (isAncestorInSet(_this.movedSet, n21)) {
19653 pushAdd(n21);
19654 } else {
19655 _this.droppedSet.add(n21);
19656 }
19657 }
19658 var candidate = null;
19659 while(addList.length){
19660 var node2 = null;
19661 if (candidate) {
19662 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
19663 var nextId = getNextId(candidate.value);
19664 if (parentId !== -1 && nextId !== -1) {
19665 node2 = candidate;
19666 }
19667 }
19668 if (!node2) {
19669 var tailNode = addList.tail;
19670 while(tailNode){
19671 var _node = tailNode;
19672 tailNode = tailNode.previous;
19673 if (_node) {
19674 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
19675 var nextId1 = getNextId(_node.value);
19676 if (nextId1 === -1) continue;
19677 else if (parentId1 !== -1) {
19678 node2 = _node;
19679 break;
19680 } else {
19681 var unhandledNode = _node.value;
19682 var parent = index.parentNode(unhandledNode);
19683 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
19684 var shadowHost = index.host(parent);
19685 var parentId2 = _this.mirror.getId(shadowHost);
19686 if (parentId2 !== -1) {
19687 node2 = _node;
19688 break;
19689 }
19690 }
19691 }
19692 }
19693 }
19694 }
19695 if (!node2) {
19696 while(addList.head){
19697 addList.removeNode(addList.head.value);
19698 }
19699 break;
19700 }
19701 candidate = node2.previous;
19702 addList.removeNode(node2.value);
19703 pushAdd(node2.value);
19704 }
19705 var payload = {
19706 texts: _this.texts.map(function(text) {
19707 var n2 = text.node;
19708 var parent = index.parentNode(n2);
19709 if (parent && parent.tagName === "TEXTAREA") {
19710 _this.genTextAreaValueMutation(parent);
19711 }
19712 return {
19713 id: _this.mirror.getId(n2),
19714 value: text.value
19715 };
19716 }).filter(function(text) {
19717 return !addedIds.has(text.id);
19718 }).filter(function(text) {
19719 return _this.mirror.has(text.id);
19720 }),
19721 attributes: _this.attributes.map(function(attribute) {
19722 var attributes = attribute.attributes;
19723 if (typeof attributes.style === "string") {
19724 var diffAsStr = JSON.stringify(attribute.styleDiff);
19725 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
19726 if (diffAsStr.length < attributes.style.length) {
19727 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) {
19728 attributes.style = attribute.styleDiff;
19729 }
19730 }
19731 }
19732 return {
19733 id: _this.mirror.getId(attribute.node),
19734 attributes: attributes
19735 };
19736 }).filter(function(attribute) {
19737 return !addedIds.has(attribute.id);
19738 }).filter(function(attribute) {
19739 return _this.mirror.has(attribute.id);
19740 }),
19741 removes: _this.removes,
19742 adds: adds
19743 };
19744 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
19745 return;
19746 }
19747 _this.texts = [];
19748 _this.attributes = [];
19749 _this.attributeMap = /* @__PURE__ */ new WeakMap();
19750 _this.removes = [];
19751 _this.addedSet = /* @__PURE__ */ new Set();
19752 _this.movedSet = /* @__PURE__ */ new Set();
19753 _this.droppedSet = /* @__PURE__ */ new Set();
19754 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
19755 _this.movedMap = {};
19756 _this.mutationCb(payload);
19757 });
19758 __publicField(this, "genTextAreaValueMutation", function(textarea) {
19759 var item = _this.attributeMap.get(textarea);
19760 if (!item) {
19761 item = {
19762 node: textarea,
19763 attributes: {},
19764 styleDiff: {},
19765 _unchangedStyles: {}
19766 };
19767 _this.attributes.push(item);
19768 _this.attributeMap.set(textarea, item);
19769 }
19770 var value = Array.from(index.childNodes(textarea), function(cn) {
19771 return index.textContent(cn) || "";
19772 }).join("");
19773 item.attributes.value = maskInputValue({
19774 element: textarea,
19775 maskInputOptions: _this.maskInputOptions,
19776 tagName: textarea.tagName,
19777 type: getInputType(textarea),
19778 value: value,
19779 maskInputFn: _this.maskInputFn
19780 });
19781 });
19782 __publicField(this, "processMutation", function(m) {
19783 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) {
19784 return;
19785 }
19786 switch(m.type){
19787 case "characterData":
19788 {
19789 var value = index.textContent(m.target);
19790 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) {
19791 _this.texts.push({
19792 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
19793 node: m.target
19794 });
19795 }
19796 break;
19797 }
19798 case "attributes":
19799 {
19800 var target = m.target;
19801 var attributeName = m.attributeName;
19802 var value1 = m.target.getAttribute(attributeName);
19803 if (attributeName === "value") {
19804 var type = getInputType(target);
19805 value1 = maskInputValue({
19806 element: target,
19807 maskInputOptions: _this.maskInputOptions,
19808 tagName: target.tagName,
19809 type: type,
19810 value: value1,
19811 maskInputFn: _this.maskInputFn
19812 });
19813 }
19814 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) {
19815 return;
19816 }
19817 var item = _this.attributeMap.get(m.target);
19818 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) {
19819 if (!target.contentDocument) {
19820 attributeName = "rr_src";
19821 } else {
19822 return;
19823 }
19824 }
19825 if (!item) {
19826 item = {
19827 node: m.target,
19828 attributes: {},
19829 styleDiff: {},
19830 _unchangedStyles: {}
19831 };
19832 _this.attributes.push(item);
19833 _this.attributeMap.set(m.target, item);
19834 }
19835 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") {
19836 target.setAttribute("data-rr-is-password", "true");
19837 }
19838 if (!ignoreAttribute(target.tagName, attributeName)) {
19839 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
19840 if (attributeName === "style") {
19841 if (!_this.unattachedDoc) {
19842 try {
19843 _this.unattachedDoc = document.implementation.createHTMLDocument();
19844 } catch (e2) {
19845 _this.unattachedDoc = _this.doc;
19846 }
19847 }
19848 var old = _this.unattachedDoc.createElement("span");
19849 if (m.oldValue) {
19850 old.setAttribute("style", m.oldValue);
19851 }
19852 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;){
19853 var pname = _step.value;
19854 var newValue = target.style.getPropertyValue(pname);
19855 var newPriority = target.style.getPropertyPriority(pname);
19856 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
19857 if (newPriority === "") {
19858 item.styleDiff[pname] = newValue;
19859 } else {
19860 item.styleDiff[pname] = [
19861 newValue,
19862 newPriority
19863 ];
19864 }
19865 } else {
19866 item._unchangedStyles[pname] = [
19867 newValue,
19868 newPriority
19869 ];
19870 }
19871 }
19872 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;){
19873 var pname1 = _step1.value;
19874 if (target.style.getPropertyValue(pname1) === "") {
19875 item.styleDiff[pname1] = false;
19876 }
19877 }
19878 } else if (attributeName === "open" && target.tagName === "DIALOG") {
19879 if (target.matches("dialog:modal")) {
19880 item.attributes["rr_open_mode"] = "modal";
19881 } else {
19882 item.attributes["rr_open_mode"] = "non-modal";
19883 }
19884 }
19885 }
19886 break;
19887 }
19888 case "childList":
19889 {
19890 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
19891 if (m.target.tagName === "TEXTAREA") {
19892 _this.genTextAreaValueMutation(m.target);
19893 return;
19894 }
19895 m.addedNodes.forEach(function(n2) {
19896 return _this.genAdds(n2, m.target);
19897 });
19898 m.removedNodes.forEach(function(n2) {
19899 var nodeId = _this.mirror.getId(n2);
19900 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
19901 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) {
19902 return;
19903 }
19904 if (_this.addedSet.has(n2)) {
19905 deepDelete(_this.addedSet, n2);
19906 _this.droppedSet.add(n2);
19907 } else if (_this.addedSet.has(m.target) && nodeId === -1) ;
19908 else if (isAncestorRemoved(m.target, _this.mirror)) ;
19909 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) {
19910 deepDelete(_this.movedSet, n2);
19911 } else {
19912 _this.removes.push({
19913 parentId: parentId,
19914 id: nodeId,
19915 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
19916 });
19917 processRemoves(n2, _this.removesSubTreeCache);
19918 }
19919 _this.mapRemoves.push(n2);
19920 });
19921 break;
19922 }
19923 }
19924 });
19925 /**
19926 * Make sure you check if `n`'s parent is blocked before calling this function
19927 * */ __publicField(this, "genAdds", function(n2, target) {
19928 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
19929 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
19930 if (_this.mirror.hasNode(n2)) {
19931 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) {
19932 return;
19933 }
19934 _this.movedSet.add(n2);
19935 var targetId = null;
19936 if (target && _this.mirror.hasNode(target)) {
19937 targetId = _this.mirror.getId(target);
19938 }
19939 if (targetId && targetId !== -1) {
19940 _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
19941 }
19942 } else {
19943 _this.addedSet.add(n2);
19944 _this.droppedSet.delete(n2);
19945 }
19946 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
19947 index.childNodes(n2).forEach(function(childN) {
19948 return _this.genAdds(childN);
19949 });
19950 if (hasShadowRoot(n2)) {
19951 index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
19952 _this.processedNodeManager.add(childN, _this);
19953 _this.genAdds(childN, n2);
19954 });
19955 }
19956 }
19957 });
19958 }
19959 var _proto = MutationBuffer.prototype;
19960 _proto.init = function init(options) {
19961 var _this = this;
19962 [
19963 "mutationCb",
19964 "blockClass",
19965 "blockSelector",
19966 "maskTextClass",
19967 "maskTextSelector",
19968 "inlineStylesheet",
19969 "maskInputOptions",
19970 "maskTextFn",
19971 "maskInputFn",
19972 "keepIframeSrcFn",
19973 "recordCanvas",
19974 "inlineImages",
19975 "slimDOMOptions",
19976 "dataURLOptions",
19977 "doc",
19978 "mirror",
19979 "iframeManager",
19980 "stylesheetManager",
19981 "shadowDomManager",
19982 "canvasManager",
19983 "processedNodeManager"
19984 ].forEach(function(key) {
19985 _this[key] = options[key];
19986 });
19987 };
19988 _proto.freeze = function freeze() {
19989 this.frozen = true;
19990 this.canvasManager.freeze();
19991 };
19992 _proto.unfreeze = function unfreeze() {
19993 this.frozen = false;
19994 this.canvasManager.unfreeze();
19995 this.emit();
19996 };
19997 _proto.isFrozen = function isFrozen() {
19998 return this.frozen;
19999 };
20000 _proto.lock = function lock() {
20001 this.locked = true;
20002 this.canvasManager.lock();
20003 };
20004 _proto.unlock = function unlock() {
20005 this.locked = false;
20006 this.canvasManager.unlock();
20007 this.emit();
20008 };
20009 _proto.reset = function reset() {
20010 this.shadowDomManager.reset();
20011 this.canvasManager.reset();
20012 };
20013 return MutationBuffer;
20014 }();
20015 function deepDelete(addsSet, n2) {
20016 addsSet.delete(n2);
20017 index.childNodes(n2).forEach(function(childN) {
20018 return deepDelete(addsSet, childN);
20019 });
20020 }
20021 function processRemoves(n2, cache) {
20022 var queue = [
20023 n2
20024 ];
20025 while(queue.length){
20026 var next = queue.pop();
20027 if (cache.has(next)) continue;
20028 cache.add(next);
20029 index.childNodes(next).forEach(function(n22) {
20030 return queue.push(n22);
20031 });
20032 }
20033 return;
20034 }
20035 function isParentRemoved(removes, n2, mirror2) {
20036 if (removes.size === 0) return false;
20037 return _isParentRemoved(removes, n2);
20038 }
20039 function _isParentRemoved(removes, n2, _mirror2) {
20040 var node2 = index.parentNode(n2);
20041 if (!node2) return false;
20042 return removes.has(node2);
20043 }
20044 function isAncestorInSet(set, n2) {
20045 if (set.size === 0) return false;
20046 return _isAncestorInSet(set, n2);
20047 }
20048 function _isAncestorInSet(set, n2) {
20049 var parent = index.parentNode(n2);
20050 if (!parent) {
20051 return false;
20052 }
20053 if (set.has(parent)) {
20054 return true;
20055 }
20056 return _isAncestorInSet(set, parent);
20057 }
20058 var errorHandler;
20059 function registerErrorHandler(handler) {
20060 errorHandler = handler;
20061 }
20062 function unregisterErrorHandler() {
20063 errorHandler = void 0;
20064 }
20065 var callbackWrapper = function(cb) {
20066 if (!errorHandler) {
20067 return cb;
20068 }
20069 var rrwebWrapped = function() {
20070 for(var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++){
20071 rest[_key] = arguments[_key];
20072 }
20073 try {
20074 return cb.apply(void 0, [].concat(rest));
20075 } catch (error) {
20076 if (errorHandler && errorHandler(error) === true) {
20077 return;
20078 }
20079 throw error;
20080 }
20081 };
20082 return rrwebWrapped;
20083 };
20084 var mutationBuffers = [];
20085 function getEventTarget(event) {
20086 try {
20087 if ("composedPath" in event) {
20088 var path = event.composedPath();
20089 if (path.length) {
20090 return path[0];
20091 }
20092 } else if ("path" in event && event.path.length) {
20093 return event.path[0];
20094 }
20095 } catch (e) {}
20096 return event && event.target;
20097 }
20098 function initMutationObserver(options, rootEl) {
20099 var mutationBuffer = new MutationBuffer();
20100 mutationBuffers.push(mutationBuffer);
20101 mutationBuffer.init(options);
20102 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
20103 observer.observe(rootEl, {
20104 attributes: true,
20105 attributeOldValue: true,
20106 characterData: true,
20107 characterDataOldValue: true,
20108 childList: true,
20109 subtree: true
20110 });
20111 return observer;
20112 }
20113 function initMoveObserver(param) {
20114 var mousemoveCb = param.mousemoveCb, sampling = param.sampling, doc = param.doc, mirror2 = param.mirror;
20115 if (sampling.mousemove === false) {
20116 return function() {};
20117 }
20118 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
20119 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
20120 var positions = [];
20121 var timeBaseline;
20122 var wrappedCb = throttle(callbackWrapper(function(source) {
20123 var totalOffset = Date.now() - timeBaseline;
20124 mousemoveCb(positions.map(function(p) {
20125 p.timeOffset -= totalOffset;
20126 return p;
20127 }), source);
20128 positions = [];
20129 timeBaseline = null;
20130 }), callbackThreshold);
20131 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
20132 var target = getEventTarget(evt);
20133 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt, clientX = _ref.clientX, clientY = _ref.clientY;
20134 if (!timeBaseline) {
20135 timeBaseline = nowTimestamp();
20136 }
20137 positions.push({
20138 x: clientX,
20139 y: clientY,
20140 id: mirror2.getId(target),
20141 timeOffset: nowTimestamp() - timeBaseline
20142 });
20143 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
20144 }), threshold, {
20145 trailing: false
20146 }));
20147 var handlers = [
20148 on("mousemove", updatePosition, doc),
20149 on("touchmove", updatePosition, doc),
20150 on("drag", updatePosition, doc)
20151 ];
20152 return callbackWrapper(function() {
20153 handlers.forEach(function(h) {
20154 return h();
20155 });
20156 });
20157 }
20158 function initMouseInteractionObserver(param) {
20159 var mouseInteractionCb = param.mouseInteractionCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
20160 if (sampling.mouseInteraction === false) {
20161 return function() {};
20162 }
20163 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
20164 var handlers = [];
20165 var currentPointerType = null;
20166 var getHandler = function(eventKey) {
20167 return function(event) {
20168 var target = getEventTarget(event);
20169 if (isBlocked(target, blockClass, blockSelector, true)) {
20170 return;
20171 }
20172 var pointerType = null;
20173 var thisEventKey = eventKey;
20174 if ("pointerType" in event) {
20175 switch(event.pointerType){
20176 case "mouse":
20177 pointerType = PointerTypes.Mouse;
20178 break;
20179 case "touch":
20180 pointerType = PointerTypes.Touch;
20181 break;
20182 case "pen":
20183 pointerType = PointerTypes.Pen;
20184 break;
20185 }
20186 if (pointerType === PointerTypes.Touch) {
20187 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
20188 thisEventKey = "TouchStart";
20189 } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
20190 thisEventKey = "TouchEnd";
20191 }
20192 } else if (pointerType === PointerTypes.Pen) ;
20193 } else if (legacy_isTouchEvent(event)) {
20194 pointerType = PointerTypes.Touch;
20195 }
20196 if (pointerType !== null) {
20197 currentPointerType = pointerType;
20198 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
20199 pointerType = null;
20200 }
20201 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
20202 pointerType = currentPointerType;
20203 currentPointerType = null;
20204 }
20205 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
20206 if (!e2) {
20207 return;
20208 }
20209 var id = mirror2.getId(target);
20210 var clientX = e2.clientX, clientY = e2.clientY;
20211 callbackWrapper(mouseInteractionCb)(_extends({
20212 type: MouseInteractions[thisEventKey],
20213 id: id,
20214 x: clientX,
20215 y: clientY
20216 }, pointerType !== null && {
20217 pointerType: pointerType
20218 }));
20219 };
20220 };
20221 Object.keys(MouseInteractions).filter(function(key) {
20222 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
20223 }).forEach(function(eventKey) {
20224 var eventName = toLowerCase(eventKey);
20225 var handler = getHandler(eventKey);
20226 if (window.PointerEvent) {
20227 switch(MouseInteractions[eventKey]){
20228 case MouseInteractions.MouseDown:
20229 case MouseInteractions.MouseUp:
20230 eventName = eventName.replace("mouse", "pointer");
20231 break;
20232 case MouseInteractions.TouchStart:
20233 case MouseInteractions.TouchEnd:
20234 return;
20235 }
20236 }
20237 handlers.push(on(eventName, handler, doc));
20238 });
20239 return callbackWrapper(function() {
20240 handlers.forEach(function(h) {
20241 return h();
20242 });
20243 });
20244 }
20245 function initScrollObserver(param) {
20246 var scrollCb = param.scrollCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
20247 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
20248 var target = getEventTarget(evt);
20249 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
20250 return;
20251 }
20252 var id = mirror2.getId(target);
20253 if (target === doc && doc.defaultView) {
20254 var scrollLeftTop = getWindowScroll(doc.defaultView);
20255 scrollCb({
20256 id: id,
20257 x: scrollLeftTop.left,
20258 y: scrollLeftTop.top
20259 });
20260 } else {
20261 scrollCb({
20262 id: id,
20263 x: target.scrollLeft,
20264 y: target.scrollTop
20265 });
20266 }
20267 }), sampling.scroll || 100));
20268 return on("scroll", updatePosition, doc);
20269 }
20270 function initViewportResizeObserver(param, param1) {
20271 var viewportResizeCb = param.viewportResizeCb;
20272 var win = param1.win;
20273 var lastH = -1;
20274 var lastW = -1;
20275 var updateDimension = callbackWrapper(throttle(callbackWrapper(function() {
20276 var height = getWindowHeight();
20277 var width = getWindowWidth();
20278 if (lastH !== height || lastW !== width) {
20279 viewportResizeCb({
20280 width: Number(width),
20281 height: Number(height)
20282 });
20283 lastH = height;
20284 lastW = width;
20285 }
20286 }), 200));
20287 return on("resize", updateDimension, win);
20288 }
20289 var INPUT_TAGS = [
20290 "INPUT",
20291 "TEXTAREA",
20292 "SELECT"
20293 ];
20294 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
20295 function initInputObserver(param) {
20296 var inputCb = param.inputCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, ignoreClass = param.ignoreClass, ignoreSelector = param.ignoreSelector, maskInputOptions = param.maskInputOptions, maskInputFn = param.maskInputFn, sampling = param.sampling, userTriggeredOnInput = param.userTriggeredOnInput;
20297 function eventHandler(event) {
20298 var target = getEventTarget(event);
20299 var userTriggered = event.isTrusted;
20300 var tagName = target && target.tagName;
20301 if (target && tagName === "OPTION") {
20302 target = index.parentElement(target);
20303 }
20304 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
20305 return;
20306 }
20307 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {
20308 return;
20309 }
20310 var text = target.value;
20311 var isChecked = false;
20312 var type = getInputType(target) || "";
20313 if (type === "radio" || type === "checkbox") {
20314 isChecked = target.checked;
20315 } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
20316 text = maskInputValue({
20317 element: target,
20318 maskInputOptions: maskInputOptions,
20319 tagName: tagName,
20320 type: type,
20321 value: text,
20322 maskInputFn: maskInputFn
20323 });
20324 }
20325 cbWithDedup(target, userTriggeredOnInput ? {
20326 text: text,
20327 isChecked: isChecked,
20328 userTriggered: userTriggered
20329 } : {
20330 text: text,
20331 isChecked: isChecked
20332 });
20333 var name = target.name;
20334 if (type === "radio" && name && isChecked) {
20335 doc.querySelectorAll('input[type="radio"][name="' + name + '"]').forEach(function(el) {
20336 if (el !== target) {
20337 var text2 = el.value;
20338 cbWithDedup(el, userTriggeredOnInput ? {
20339 text: text2,
20340 isChecked: !isChecked,
20341 userTriggered: false
20342 } : {
20343 text: text2,
20344 isChecked: !isChecked
20345 });
20346 }
20347 });
20348 }
20349 }
20350 function cbWithDedup(target, v2) {
20351 var lastInputValue = lastInputValueMap.get(target);
20352 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
20353 lastInputValueMap.set(target, v2);
20354 var id = mirror2.getId(target);
20355 callbackWrapper(inputCb)(_extends({}, v2, {
20356 id: id
20357 }));
20358 }
20359 }
20360 var events = sampling.input === "last" ? [
20361 "change"
20362 ] : [
20363 "input",
20364 "change"
20365 ];
20366 var handlers = events.map(function(eventName) {
20367 return on(eventName, callbackWrapper(eventHandler), doc);
20368 });
20369 var currentWindow = doc.defaultView;
20370 if (!currentWindow) {
20371 return function() {
20372 handlers.forEach(function(h) {
20373 return h();
20374 });
20375 };
20376 }
20377 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
20378 var hookProperties = [
20379 [
20380 currentWindow.HTMLInputElement.prototype,
20381 "value"
20382 ],
20383 [
20384 currentWindow.HTMLInputElement.prototype,
20385 "checked"
20386 ],
20387 [
20388 currentWindow.HTMLSelectElement.prototype,
20389 "value"
20390 ],
20391 [
20392 currentWindow.HTMLTextAreaElement.prototype,
20393 "value"
20394 ],
20395 // Some UI library use selectedIndex to set select value
20396 [
20397 currentWindow.HTMLSelectElement.prototype,
20398 "selectedIndex"
20399 ],
20400 [
20401 currentWindow.HTMLOptionElement.prototype,
20402 "selected"
20403 ]
20404 ];
20405 if (propertyDescriptor && propertyDescriptor.set) {
20406 var _handlers;
20407 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
20408 return hookSetter(p[0], p[1], {
20409 set: function set() {
20410 callbackWrapper(eventHandler)({
20411 target: this,
20412 isTrusted: false
20413 });
20414 }
20415 }, false, currentWindow);
20416 })));
20417 }
20418 return callbackWrapper(function() {
20419 handlers.forEach(function(h) {
20420 return h();
20421 });
20422 });
20423 }
20424 function getNestedCSSRulePositions(rule2) {
20425 var positions = [];
20426 function recurse(childRule, pos) {
20427 if (hasNestedCSSRule("CSSGroupingRule") && _instanceof(childRule.parentRule, CSSGroupingRule) || hasNestedCSSRule("CSSMediaRule") && _instanceof(childRule.parentRule, CSSMediaRule) || hasNestedCSSRule("CSSSupportsRule") && _instanceof(childRule.parentRule, CSSSupportsRule) || hasNestedCSSRule("CSSConditionRule") && _instanceof(childRule.parentRule, CSSConditionRule)) {
20428 var rules2 = Array.from(childRule.parentRule.cssRules);
20429 var index2 = rules2.indexOf(childRule);
20430 pos.unshift(index2);
20431 } else if (childRule.parentStyleSheet) {
20432 var rules21 = Array.from(childRule.parentStyleSheet.cssRules);
20433 var index21 = rules21.indexOf(childRule);
20434 pos.unshift(index21);
20435 }
20436 return pos;
20437 }
20438 return recurse(rule2, positions);
20439 }
20440 function getIdAndStyleId(sheet, mirror2, styleMirror) {
20441 var id, styleId;
20442 if (!sheet) return {};
20443 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
20444 else styleId = styleMirror.getId(sheet);
20445 return {
20446 styleId: styleId,
20447 id: id
20448 };
20449 }
20450 function initStyleSheetObserver(param, param1) {
20451 var styleSheetRuleCb = param.styleSheetRuleCb, mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
20452 var win = param1.win;
20453 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
20454 return function() {};
20455 }
20456 var insertRule = win.CSSStyleSheet.prototype.insertRule;
20457 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
20458 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20459 var rule2 = argumentsList[0], index2 = argumentsList[1];
20460 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20461 if (id && id !== -1 || styleId && styleId !== -1) {
20462 styleSheetRuleCb({
20463 id: id,
20464 styleId: styleId,
20465 adds: [
20466 {
20467 rule: rule2,
20468 index: index2
20469 }
20470 ]
20471 });
20472 }
20473 return target.apply(thisArg, argumentsList);
20474 })
20475 });
20476 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
20477 if (index2 === void 0) index2 = this.cssRules.length;
20478 var rule2 = selector + " { " + styleBlock + " }";
20479 return win.CSSStyleSheet.prototype.insertRule.apply(this, [
20480 rule2,
20481 index2
20482 ]);
20483 };
20484 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
20485 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
20486 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20487 var index2 = argumentsList[0];
20488 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20489 if (id && id !== -1 || styleId && styleId !== -1) {
20490 styleSheetRuleCb({
20491 id: id,
20492 styleId: styleId,
20493 removes: [
20494 {
20495 index: index2
20496 }
20497 ]
20498 });
20499 }
20500 return target.apply(thisArg, argumentsList);
20501 })
20502 });
20503 win.CSSStyleSheet.prototype.removeRule = function(index2) {
20504 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [
20505 index2
20506 ]);
20507 };
20508 var replace;
20509 if (win.CSSStyleSheet.prototype.replace) {
20510 replace = win.CSSStyleSheet.prototype.replace;
20511 win.CSSStyleSheet.prototype.replace = new Proxy(replace, {
20512 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20513 var text = argumentsList[0];
20514 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20515 if (id && id !== -1 || styleId && styleId !== -1) {
20516 styleSheetRuleCb({
20517 id: id,
20518 styleId: styleId,
20519 replace: text
20520 });
20521 }
20522 return target.apply(thisArg, argumentsList);
20523 })
20524 });
20525 }
20526 var replaceSync;
20527 if (win.CSSStyleSheet.prototype.replaceSync) {
20528 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
20529 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
20530 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20531 var text = argumentsList[0];
20532 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20533 if (id && id !== -1 || styleId && styleId !== -1) {
20534 styleSheetRuleCb({
20535 id: id,
20536 styleId: styleId,
20537 replaceSync: text
20538 });
20539 }
20540 return target.apply(thisArg, argumentsList);
20541 })
20542 });
20543 }
20544 var supportedNestedCSSRuleTypes = {};
20545 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
20546 supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
20547 } else {
20548 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
20549 supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
20550 }
20551 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
20552 supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
20553 }
20554 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
20555 supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
20556 }
20557 }
20558 var unmodifiedFunctions = {};
20559 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
20560 var typeKey = param[0], type = param[1];
20561 unmodifiedFunctions[typeKey] = {
20562 // eslint-disable-next-line @typescript-eslint/unbound-method
20563 insertRule: type.prototype.insertRule,
20564 // eslint-disable-next-line @typescript-eslint/unbound-method
20565 deleteRule: type.prototype.deleteRule
20566 };
20567 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
20568 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20569 var rule2 = argumentsList[0], index2 = argumentsList[1];
20570 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20571 if (id && id !== -1 || styleId && styleId !== -1) {
20572 styleSheetRuleCb({
20573 id: id,
20574 styleId: styleId,
20575 adds: [
20576 {
20577 rule: rule2,
20578 index: [].concat(getNestedCSSRulePositions(thisArg), [
20579 index2 || 0
20580 ])
20581 }
20582 ]
20583 });
20584 }
20585 return target.apply(thisArg, argumentsList);
20586 })
20587 });
20588 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
20589 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20590 var index2 = argumentsList[0];
20591 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20592 if (id && id !== -1 || styleId && styleId !== -1) {
20593 styleSheetRuleCb({
20594 id: id,
20595 styleId: styleId,
20596 removes: [
20597 {
20598 index: [].concat(getNestedCSSRulePositions(thisArg), [
20599 index2
20600 ])
20601 }
20602 ]
20603 });
20604 }
20605 return target.apply(thisArg, argumentsList);
20606 })
20607 });
20608 });
20609 return callbackWrapper(function() {
20610 win.CSSStyleSheet.prototype.insertRule = insertRule;
20611 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
20612 replace && (win.CSSStyleSheet.prototype.replace = replace);
20613 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
20614 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
20615 var typeKey = param[0], type = param[1];
20616 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
20617 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
20618 });
20619 });
20620 }
20621 function initAdoptedStyleSheetObserver(param, host2) {
20622 var mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
20623 var _a2, _b, _c;
20624 var hostId = null;
20625 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
20626 else hostId = mirror2.getId(index.host(host2));
20627 var patchTarget = host2.nodeName === "#document" ? (_a2 = host2.defaultView) == null ? void 0 : _a2.Document : (_c = (_b = host2.ownerDocument) == null ? void 0 : _b.defaultView) == null ? void 0 : _c.ShadowRoot;
20628 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
20629 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
20630 Object.defineProperty(host2, "adoptedStyleSheets", {
20631 configurable: originalPropertyDescriptor.configurable,
20632 enumerable: originalPropertyDescriptor.enumerable,
20633 get: function get() {
20634 var _a3;
20635 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
20636 },
20637 set: function set(sheets) {
20638 var _a3;
20639 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
20640 if (hostId !== null && hostId !== -1) {
20641 try {
20642 stylesheetManager.adoptStyleSheets(sheets, hostId);
20643 } catch (e2) {}
20644 }
20645 return result2;
20646 }
20647 });
20648 return callbackWrapper(function() {
20649 Object.defineProperty(host2, "adoptedStyleSheets", {
20650 configurable: originalPropertyDescriptor.configurable,
20651 enumerable: originalPropertyDescriptor.enumerable,
20652 // eslint-disable-next-line @typescript-eslint/unbound-method
20653 get: originalPropertyDescriptor.get,
20654 // eslint-disable-next-line @typescript-eslint/unbound-method
20655 set: originalPropertyDescriptor.set
20656 });
20657 });
20658 }
20659 function initStyleDeclarationObserver(param, param1) {
20660 var styleDeclarationCb = param.styleDeclarationCb, mirror2 = param.mirror, ignoreCSSAttributes = param.ignoreCSSAttributes, stylesheetManager = param.stylesheetManager;
20661 var win = param1.win;
20662 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
20663 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {
20664 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20665 var _a2;
20666 var property = argumentsList[0], value = argumentsList[1], priority = argumentsList[2];
20667 if (ignoreCSSAttributes.has(property)) {
20668 return setProperty.apply(thisArg, [
20669 property,
20670 value,
20671 priority
20672 ]);
20673 }
20674 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20675 if (id && id !== -1 || styleId && styleId !== -1) {
20676 styleDeclarationCb({
20677 id: id,
20678 styleId: styleId,
20679 set: {
20680 property: property,
20681 value: value,
20682 priority: priority
20683 },
20684 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20685 index: getNestedCSSRulePositions(thisArg.parentRule)
20686 });
20687 }
20688 return target.apply(thisArg, argumentsList);
20689 })
20690 });
20691 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
20692 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
20693 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20694 var _a2;
20695 var property = argumentsList[0];
20696 if (ignoreCSSAttributes.has(property)) {
20697 return removeProperty.apply(thisArg, [
20698 property
20699 ]);
20700 }
20701 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20702 if (id && id !== -1 || styleId && styleId !== -1) {
20703 styleDeclarationCb({
20704 id: id,
20705 styleId: styleId,
20706 remove: {
20707 property: property
20708 },
20709 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20710 index: getNestedCSSRulePositions(thisArg.parentRule)
20711 });
20712 }
20713 return target.apply(thisArg, argumentsList);
20714 })
20715 });
20716 return callbackWrapper(function() {
20717 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
20718 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
20719 });
20720 }
20721 function initMediaInteractionObserver(param) {
20722 var mediaInteractionCb = param.mediaInteractionCb, blockClass = param.blockClass, blockSelector = param.blockSelector, mirror2 = param.mirror, sampling = param.sampling, doc = param.doc;
20723 var handler = callbackWrapper(function(type) {
20724 return throttle(callbackWrapper(function(event) {
20725 var target = getEventTarget(event);
20726 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
20727 return;
20728 }
20729 var currentTime = target.currentTime, volume = target.volume, muted = target.muted, playbackRate = target.playbackRate, loop = target.loop;
20730 mediaInteractionCb({
20731 type: type,
20732 id: mirror2.getId(target),
20733 currentTime: currentTime,
20734 volume: volume,
20735 muted: muted,
20736 playbackRate: playbackRate,
20737 loop: loop
20738 });
20739 }), sampling.media || 500);
20740 });
20741 var handlers = [
20742 on("play", handler(MediaInteractions.Play), doc),
20743 on("pause", handler(MediaInteractions.Pause), doc),
20744 on("seeked", handler(MediaInteractions.Seeked), doc),
20745 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
20746 on("ratechange", handler(MediaInteractions.RateChange), doc)
20747 ];
20748 return callbackWrapper(function() {
20749 handlers.forEach(function(h) {
20750 return h();
20751 });
20752 });
20753 }
20754 function initFontObserver(param) {
20755 var fontCb = param.fontCb, doc = param.doc;
20756 var win = doc.defaultView;
20757 if (!win) {
20758 return function() {};
20759 }
20760 var handlers = [];
20761 var fontMap = /* @__PURE__ */ new WeakMap();
20762 var originalFontFace = win.FontFace;
20763 win.FontFace = function FontFace2(family, source, descriptors) {
20764 var fontFace = new originalFontFace(family, source, descriptors);
20765 fontMap.set(fontFace, {
20766 family: family,
20767 buffer: typeof source !== "string",
20768 descriptors: descriptors,
20769 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
20770 });
20771 return fontFace;
20772 };
20773 var restoreHandler = patch(doc.fonts, "add", function(original) {
20774 return function(fontFace) {
20775 setTimeout(callbackWrapper(function() {
20776 var p = fontMap.get(fontFace);
20777 if (p) {
20778 fontCb(p);
20779 fontMap.delete(fontFace);
20780 }
20781 }), 0);
20782 return original.apply(this, [
20783 fontFace
20784 ]);
20785 };
20786 });
20787 handlers.push(function() {
20788 win.FontFace = originalFontFace;
20789 });
20790 handlers.push(restoreHandler);
20791 return callbackWrapper(function() {
20792 handlers.forEach(function(h) {
20793 return h();
20794 });
20795 });
20796 }
20797 function initSelectionObserver(param) {
20798 var doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, selectionCb = param.selectionCb;
20799 var collapsed = true;
20800 var updateSelection = callbackWrapper(function() {
20801 var selection = doc.getSelection();
20802 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
20803 collapsed = selection.isCollapsed || false;
20804 var ranges = [];
20805 var count = selection.rangeCount || 0;
20806 for(var i2 = 0; i2 < count; i2++){
20807 var range = selection.getRangeAt(i2);
20808 var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset;
20809 var blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
20810 if (blocked) continue;
20811 ranges.push({
20812 start: mirror2.getId(startContainer),
20813 startOffset: startOffset,
20814 end: mirror2.getId(endContainer),
20815 endOffset: endOffset
20816 });
20817 }
20818 selectionCb({
20819 ranges: ranges
20820 });
20821 });
20822 updateSelection();
20823 return on("selectionchange", updateSelection);
20824 }
20825 function initCustomElementObserver(param) {
20826 var doc = param.doc, customElementCb = param.customElementCb;
20827 var win = doc.defaultView;
20828 if (!win || !win.customElements) return function() {};
20829 var restoreHandler = patch(win.customElements, "define", function(original) {
20830 return function(name, constructor, options) {
20831 try {
20832 customElementCb({
20833 define: {
20834 name: name
20835 }
20836 });
20837 } catch (e2) {
20838 console.warn("Custom element callback failed for " + name);
20839 }
20840 return original.apply(this, [
20841 name,
20842 constructor,
20843 options
20844 ]);
20845 };
20846 });
20847 return restoreHandler;
20848 }
20849 function mergeHooks(o2, hooks) {
20850 var mutationCb = o2.mutationCb, mousemoveCb = o2.mousemoveCb, mouseInteractionCb = o2.mouseInteractionCb, scrollCb = o2.scrollCb, viewportResizeCb = o2.viewportResizeCb, inputCb = o2.inputCb, mediaInteractionCb = o2.mediaInteractionCb, styleSheetRuleCb = o2.styleSheetRuleCb, styleDeclarationCb = o2.styleDeclarationCb, canvasMutationCb = o2.canvasMutationCb, fontCb = o2.fontCb, selectionCb = o2.selectionCb, customElementCb = o2.customElementCb;
20851 o2.mutationCb = function() {
20852 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20853 p[_key] = arguments[_key];
20854 }
20855 if (hooks.mutation) {
20856 var _hooks;
20857 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
20858 }
20859 mutationCb.apply(void 0, [].concat(p));
20860 };
20861 o2.mousemoveCb = function() {
20862 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20863 p[_key] = arguments[_key];
20864 }
20865 if (hooks.mousemove) {
20866 var _hooks;
20867 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
20868 }
20869 mousemoveCb.apply(void 0, [].concat(p));
20870 };
20871 o2.mouseInteractionCb = function() {
20872 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20873 p[_key] = arguments[_key];
20874 }
20875 if (hooks.mouseInteraction) {
20876 var _hooks;
20877 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
20878 }
20879 mouseInteractionCb.apply(void 0, [].concat(p));
20880 };
20881 o2.scrollCb = function() {
20882 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20883 p[_key] = arguments[_key];
20884 }
20885 if (hooks.scroll) {
20886 var _hooks;
20887 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
20888 }
20889 scrollCb.apply(void 0, [].concat(p));
20890 };
20891 o2.viewportResizeCb = function() {
20892 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20893 p[_key] = arguments[_key];
20894 }
20895 if (hooks.viewportResize) {
20896 var _hooks;
20897 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
20898 }
20899 viewportResizeCb.apply(void 0, [].concat(p));
20900 };
20901 o2.inputCb = function() {
20902 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20903 p[_key] = arguments[_key];
20904 }
20905 if (hooks.input) {
20906 var _hooks;
20907 (_hooks = hooks).input.apply(_hooks, [].concat(p));
20908 }
20909 inputCb.apply(void 0, [].concat(p));
20910 };
20911 o2.mediaInteractionCb = function() {
20912 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20913 p[_key] = arguments[_key];
20914 }
20915 if (hooks.mediaInteaction) {
20916 var _hooks;
20917 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
20918 }
20919 mediaInteractionCb.apply(void 0, [].concat(p));
20920 };
20921 o2.styleSheetRuleCb = function() {
20922 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20923 p[_key] = arguments[_key];
20924 }
20925 if (hooks.styleSheetRule) {
20926 var _hooks;
20927 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
20928 }
20929 styleSheetRuleCb.apply(void 0, [].concat(p));
20930 };
20931 o2.styleDeclarationCb = function() {
20932 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20933 p[_key] = arguments[_key];
20934 }
20935 if (hooks.styleDeclaration) {
20936 var _hooks;
20937 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
20938 }
20939 styleDeclarationCb.apply(void 0, [].concat(p));
20940 };
20941 o2.canvasMutationCb = function() {
20942 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20943 p[_key] = arguments[_key];
20944 }
20945 if (hooks.canvasMutation) {
20946 var _hooks;
20947 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
20948 }
20949 canvasMutationCb.apply(void 0, [].concat(p));
20950 };
20951 o2.fontCb = function() {
20952 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20953 p[_key] = arguments[_key];
20954 }
20955 if (hooks.font) {
20956 var _hooks;
20957 (_hooks = hooks).font.apply(_hooks, [].concat(p));
20958 }
20959 fontCb.apply(void 0, [].concat(p));
20960 };
20961 o2.selectionCb = function() {
20962 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20963 p[_key] = arguments[_key];
20964 }
20965 if (hooks.selection) {
20966 var _hooks;
20967 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
20968 }
20969 selectionCb.apply(void 0, [].concat(p));
20970 };
20971 o2.customElementCb = function() {
20972 for(var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++){
20973 c2[_key] = arguments[_key];
20974 }
20975 if (hooks.customElement) {
20976 var _hooks;
20977 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
20978 }
20979 customElementCb.apply(void 0, [].concat(c2));
20980 };
20981 }
20982 function initObservers(o2, hooks) {
20983 if (hooks === void 0) hooks = {};
20984 var currentWindow = o2.doc.defaultView;
20985 if (!currentWindow) {
20986 return function() {};
20987 }
20988 mergeHooks(o2, hooks);
20989 var mutationObserver;
20990 if (o2.recordDOM) {
20991 mutationObserver = initMutationObserver(o2, o2.doc);
20992 }
20993 var mousemoveHandler = initMoveObserver(o2);
20994 var mouseInteractionHandler = initMouseInteractionObserver(o2);
20995 var scrollHandler = initScrollObserver(o2);
20996 var viewportResizeHandler = initViewportResizeObserver(o2, {
20997 win: currentWindow
20998 });
20999 var inputHandler = initInputObserver(o2);
21000 var mediaInteractionHandler = initMediaInteractionObserver(o2);
21001 var styleSheetObserver = function() {};
21002 var adoptedStyleSheetObserver = function() {};
21003 var styleDeclarationObserver = function() {};
21004 var fontObserver = function() {};
21005 if (o2.recordDOM) {
21006 styleSheetObserver = initStyleSheetObserver(o2, {
21007 win: currentWindow
21008 });
21009 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
21010 styleDeclarationObserver = initStyleDeclarationObserver(o2, {
21011 win: currentWindow
21012 });
21013 if (o2.collectFonts) {
21014 fontObserver = initFontObserver(o2);
21015 }
21016 }
21017 var selectionObserver = initSelectionObserver(o2);
21018 var customElementObserver = initCustomElementObserver(o2);
21019 var pluginHandlers = [];
21020 for(var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;){
21021 var plugin3 = _step.value;
21022 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
21023 }
21024 return callbackWrapper(function() {
21025 mutationBuffers.forEach(function(b) {
21026 return b.reset();
21027 });
21028 mutationObserver == null ? void 0 : mutationObserver.disconnect();
21029 mousemoveHandler();
21030 mouseInteractionHandler();
21031 scrollHandler();
21032 viewportResizeHandler();
21033 inputHandler();
21034 mediaInteractionHandler();
21035 styleSheetObserver();
21036 adoptedStyleSheetObserver();
21037 styleDeclarationObserver();
21038 fontObserver();
21039 selectionObserver();
21040 customElementObserver();
21041 pluginHandlers.forEach(function(h) {
21042 return h();
21043 });
21044 });
21045 }
21046 function hasNestedCSSRule(prop) {
21047 return typeof window[prop] !== "undefined";
21048 }
21049 function canMonkeyPatchNestedCSSRule(prop) {
21050 return Boolean(typeof window[prop] !== "undefined" && // Note: Generally, this check _shouldn't_ be necessary
21051 // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here
21052 window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
21053 }
21054 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
21055 function CrossOriginIframeMirror(generateIdFn) {
21056 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
21057 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
21058 this.generateIdFn = generateIdFn;
21059 }
21060 var _proto = CrossOriginIframeMirror.prototype;
21061 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
21062 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
21063 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
21064 var id = idToRemoteIdMap.get(remoteId);
21065 if (!id) {
21066 id = this.generateIdFn();
21067 idToRemoteIdMap.set(remoteId, id);
21068 remoteIdToIdMap.set(id, remoteId);
21069 }
21070 return id;
21071 };
21072 _proto.getIds = function getIds(iframe, remoteId) {
21073 var _this = this;
21074 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
21075 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
21076 return remoteId.map(function(id) {
21077 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
21078 });
21079 };
21080 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
21081 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
21082 if (typeof id !== "number") return id;
21083 var remoteId = remoteIdToIdMap.get(id);
21084 if (!remoteId) return -1;
21085 return remoteId;
21086 };
21087 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
21088 var _this = this;
21089 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
21090 return ids.map(function(id) {
21091 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
21092 });
21093 };
21094 _proto.reset = function reset(iframe) {
21095 if (!iframe) {
21096 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
21097 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
21098 return;
21099 }
21100 this.iframeIdToRemoteIdMap.delete(iframe);
21101 this.iframeRemoteIdToIdMap.delete(iframe);
21102 };
21103 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
21104 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
21105 if (!idToRemoteIdMap) {
21106 idToRemoteIdMap = /* @__PURE__ */ new Map();
21107 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
21108 }
21109 return idToRemoteIdMap;
21110 };
21111 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
21112 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
21113 if (!remoteIdToIdMap) {
21114 remoteIdToIdMap = /* @__PURE__ */ new Map();
21115 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
21116 }
21117 return remoteIdToIdMap;
21118 };
21119 return CrossOriginIframeMirror;
21120 }();
21121 var IframeManager = /*#__PURE__*/ function() {
21122 function IframeManager(options) {
21123 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
21124 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
21125 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
21126 __publicField(this, "crossOriginIframeStyleMirror");
21127 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
21128 __publicField(this, "mirror");
21129 __publicField(this, "mutationCb");
21130 __publicField(this, "wrappedEmit");
21131 __publicField(this, "loadListener");
21132 __publicField(this, "stylesheetManager");
21133 __publicField(this, "recordCrossOriginIframes");
21134 this.mutationCb = options.mutationCb;
21135 this.wrappedEmit = options.wrappedEmit;
21136 this.stylesheetManager = options.stylesheetManager;
21137 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
21138 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
21139 this.mirror = options.mirror;
21140 if (this.recordCrossOriginIframes) {
21141 window.addEventListener("message", this.handleMessage.bind(this));
21142 }
21143 }
21144 var _proto = IframeManager.prototype;
21145 _proto.addIframe = function addIframe(iframeEl) {
21146 this.iframes.set(iframeEl, true);
21147 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
21148 };
21149 _proto.addLoadListener = function addLoadListener(cb) {
21150 this.loadListener = cb;
21151 };
21152 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
21153 var _a2, _b;
21154 this.mutationCb({
21155 adds: [
21156 {
21157 parentId: this.mirror.getId(iframeEl),
21158 nextId: null,
21159 node: childSn
21160 }
21161 ],
21162 removes: [],
21163 texts: [],
21164 attributes: [],
21165 isAttachIframe: true
21166 });
21167 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null ? void 0 : _a2.addEventListener("message", this.handleMessage.bind(this));
21168 (_b = this.loadListener) == null ? void 0 : _b.call(this, iframeEl);
21169 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
21170 };
21171 _proto.handleMessage = function handleMessage(message) {
21172 var crossOriginMessageEvent = message;
21173 if (crossOriginMessageEvent.data.type !== "rrweb" || // To filter out the rrweb messages which are forwarded by some sites.
21174 crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
21175 var iframeSourceWindow = message.source;
21176 if (!iframeSourceWindow) return;
21177 var iframeEl = this.crossOriginIframeMap.get(message.source);
21178 if (!iframeEl) return;
21179 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
21180 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
21181 };
21182 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
21183 var _this = this;
21184 var _a2;
21185 switch(e2.type){
21186 case EventType.FullSnapshot:
21187 {
21188 this.crossOriginIframeMirror.reset(iframeEl);
21189 this.crossOriginIframeStyleMirror.reset(iframeEl);
21190 this.replaceIdOnNode(e2.data.node, iframeEl);
21191 var rootId = e2.data.node.id;
21192 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
21193 this.patchRootIdOnNode(e2.data.node, rootId);
21194 return {
21195 timestamp: e2.timestamp,
21196 type: EventType.IncrementalSnapshot,
21197 data: {
21198 source: IncrementalSource.Mutation,
21199 adds: [
21200 {
21201 parentId: this.mirror.getId(iframeEl),
21202 nextId: null,
21203 node: e2.data.node
21204 }
21205 ],
21206 removes: [],
21207 texts: [],
21208 attributes: [],
21209 isAttachIframe: true
21210 }
21211 };
21212 }
21213 case EventType.Meta:
21214 case EventType.Load:
21215 case EventType.DomContentLoaded:
21216 {
21217 return false;
21218 }
21219 case EventType.Plugin:
21220 {
21221 return e2;
21222 }
21223 case EventType.Custom:
21224 {
21225 this.replaceIds(e2.data.payload, iframeEl, [
21226 "id",
21227 "parentId",
21228 "previousId",
21229 "nextId"
21230 ]);
21231 return e2;
21232 }
21233 case EventType.IncrementalSnapshot:
21234 {
21235 switch(e2.data.source){
21236 case IncrementalSource.Mutation:
21237 {
21238 e2.data.adds.forEach(function(n2) {
21239 _this.replaceIds(n2, iframeEl, [
21240 "parentId",
21241 "nextId",
21242 "previousId"
21243 ]);
21244 _this.replaceIdOnNode(n2.node, iframeEl);
21245 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
21246 rootId && _this.patchRootIdOnNode(n2.node, rootId);
21247 });
21248 e2.data.removes.forEach(function(n2) {
21249 _this.replaceIds(n2, iframeEl, [
21250 "parentId",
21251 "id"
21252 ]);
21253 });
21254 e2.data.attributes.forEach(function(n2) {
21255 _this.replaceIds(n2, iframeEl, [
21256 "id"
21257 ]);
21258 });
21259 e2.data.texts.forEach(function(n2) {
21260 _this.replaceIds(n2, iframeEl, [
21261 "id"
21262 ]);
21263 });
21264 return e2;
21265 }
21266 case IncrementalSource.Drag:
21267 case IncrementalSource.TouchMove:
21268 case IncrementalSource.MouseMove:
21269 {
21270 e2.data.positions.forEach(function(p) {
21271 _this.replaceIds(p, iframeEl, [
21272 "id"
21273 ]);
21274 });
21275 return e2;
21276 }
21277 case IncrementalSource.ViewportResize:
21278 {
21279 return false;
21280 }
21281 case IncrementalSource.MediaInteraction:
21282 case IncrementalSource.MouseInteraction:
21283 case IncrementalSource.Scroll:
21284 case IncrementalSource.CanvasMutation:
21285 case IncrementalSource.Input:
21286 {
21287 this.replaceIds(e2.data, iframeEl, [
21288 "id"
21289 ]);
21290 return e2;
21291 }
21292 case IncrementalSource.StyleSheetRule:
21293 case IncrementalSource.StyleDeclaration:
21294 {
21295 this.replaceIds(e2.data, iframeEl, [
21296 "id"
21297 ]);
21298 this.replaceStyleIds(e2.data, iframeEl, [
21299 "styleId"
21300 ]);
21301 return e2;
21302 }
21303 case IncrementalSource.Font:
21304 {
21305 return e2;
21306 }
21307 case IncrementalSource.Selection:
21308 {
21309 e2.data.ranges.forEach(function(range) {
21310 _this.replaceIds(range, iframeEl, [
21311 "start",
21312 "end"
21313 ]);
21314 });
21315 return e2;
21316 }
21317 case IncrementalSource.AdoptedStyleSheet:
21318 {
21319 this.replaceIds(e2.data, iframeEl, [
21320 "id"
21321 ]);
21322 this.replaceStyleIds(e2.data, iframeEl, [
21323 "styleIds"
21324 ]);
21325 (_a2 = e2.data.styles) == null ? void 0 : _a2.forEach(function(style) {
21326 _this.replaceStyleIds(style, iframeEl, [
21327 "styleId"
21328 ]);
21329 });
21330 return e2;
21331 }
21332 }
21333 }
21334 }
21335 return false;
21336 };
21337 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
21338 for(var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;){
21339 var key = _step.value;
21340 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
21341 if (Array.isArray(obj[key])) {
21342 obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
21343 } else {
21344 obj[key] = iframeMirror.getId(iframeEl, obj[key]);
21345 }
21346 }
21347 return obj;
21348 };
21349 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
21350 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
21351 };
21352 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
21353 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
21354 };
21355 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
21356 var _this = this;
21357 this.replaceIds(node2, iframeEl, [
21358 "id",
21359 "rootId"
21360 ]);
21361 if ("childNodes" in node2) {
21362 node2.childNodes.forEach(function(child) {
21363 _this.replaceIdOnNode(child, iframeEl);
21364 });
21365 }
21366 };
21367 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
21368 var _this = this;
21369 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
21370 if ("childNodes" in node2) {
21371 node2.childNodes.forEach(function(child) {
21372 _this.patchRootIdOnNode(child, rootId);
21373 });
21374 }
21375 };
21376 return IframeManager;
21377 }();
21378 var ShadowDomManager = /*#__PURE__*/ function() {
21379 function ShadowDomManager(options) {
21380 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
21381 __publicField(this, "mutationCb");
21382 __publicField(this, "scrollCb");
21383 __publicField(this, "bypassOptions");
21384 __publicField(this, "mirror");
21385 __publicField(this, "restoreHandlers", []);
21386 this.mutationCb = options.mutationCb;
21387 this.scrollCb = options.scrollCb;
21388 this.bypassOptions = options.bypassOptions;
21389 this.mirror = options.mirror;
21390 this.init();
21391 }
21392 var _proto = ShadowDomManager.prototype;
21393 _proto.init = function init() {
21394 this.reset();
21395 this.patchAttachShadow(Element, document);
21396 };
21397 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
21398 var _this = this;
21399 if (!isNativeShadowDom(shadowRoot2)) return;
21400 if (this.shadowDoms.has(shadowRoot2)) return;
21401 this.shadowDoms.add(shadowRoot2);
21402 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
21403 doc: doc,
21404 mutationCb: this.mutationCb,
21405 mirror: this.mirror,
21406 shadowDomManager: this
21407 }), shadowRoot2);
21408 this.restoreHandlers.push(function() {
21409 return observer.disconnect();
21410 });
21411 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
21412 scrollCb: this.scrollCb,
21413 // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813
21414 // scroll is not allowed to pass the boundary, so we need to listen the shadow document
21415 doc: shadowRoot2,
21416 mirror: this.mirror
21417 })));
21418 setTimeout(function() {
21419 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
21420 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
21421 mirror: _this.mirror,
21422 stylesheetManager: _this.bypassOptions.stylesheetManager
21423 }, shadowRoot2));
21424 }, 0);
21425 };
21426 /**
21427 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
21428 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
21429 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
21430 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
21431 };
21432 /**
21433 * Patch 'attachShadow' to observe newly added shadow doms.
21434 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
21435 var manager = this;
21436 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
21437 return function(option) {
21438 var sRoot = original.call(this, option);
21439 var shadowRootEl = index.shadowRoot(this);
21440 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
21441 return sRoot;
21442 };
21443 }));
21444 };
21445 _proto.reset = function reset() {
21446 this.restoreHandlers.forEach(function(handler) {
21447 try {
21448 handler();
21449 } catch (e2) {}
21450 });
21451 this.restoreHandlers = [];
21452 this.shadowDoms = /* @__PURE__ */ new WeakSet();
21453 };
21454 return ShadowDomManager;
21455 }();
21456 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
21457 var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
21458 for(var i$1 = 0; i$1 < chars.length; i$1++){
21459 lookup[chars.charCodeAt(i$1)] = i$1;
21460 }
21461 var encode = function encode(arraybuffer) {
21462 var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";
21463 for(i2 = 0; i2 < len; i2 += 3){
21464 base64 += chars[bytes[i2] >> 2];
21465 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
21466 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
21467 base64 += chars[bytes[i2 + 2] & 63];
21468 }
21469 if (len % 3 === 2) {
21470 base64 = base64.substring(0, base64.length - 1) + "=";
21471 } else if (len % 3 === 1) {
21472 base64 = base64.substring(0, base64.length - 2) + "==";
21473 }
21474 return base64;
21475 };
21476 var canvasVarMap = /* @__PURE__ */ new Map();
21477 function variableListFor$1(ctx, ctor) {
21478 var contextMap = canvasVarMap.get(ctx);
21479 if (!contextMap) {
21480 contextMap = /* @__PURE__ */ new Map();
21481 canvasVarMap.set(ctx, contextMap);
21482 }
21483 if (!contextMap.has(ctor)) {
21484 contextMap.set(ctor, []);
21485 }
21486 return contextMap.get(ctor);
21487 }
21488 var saveWebGLVar = function(value, win, ctx) {
21489 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
21490 var name = value.constructor.name;
21491 var list2 = variableListFor$1(ctx, name);
21492 var index2 = list2.indexOf(value);
21493 if (index2 === -1) {
21494 index2 = list2.length;
21495 list2.push(value);
21496 }
21497 return index2;
21498 };
21499 function serializeArg(value, win, ctx) {
21500 if (_instanceof(value, Array)) {
21501 return value.map(function(arg) {
21502 return serializeArg(arg, win, ctx);
21503 });
21504 } else if (value === null) {
21505 return value;
21506 } else if (_instanceof(value, Float32Array) || _instanceof(value, Float64Array) || _instanceof(value, Int32Array) || _instanceof(value, Uint32Array) || _instanceof(value, Uint8Array) || _instanceof(value, Uint16Array) || _instanceof(value, Int16Array) || _instanceof(value, Int8Array) || _instanceof(value, Uint8ClampedArray)) {
21507 var name = value.constructor.name;
21508 return {
21509 rr_type: name,
21510 args: [
21511 Object.values(value)
21512 ]
21513 };
21514 } else if (// SharedArrayBuffer disabled on most browsers due to spectre.
21515 // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer
21516 // value instanceof SharedArrayBuffer ||
21517 _instanceof(value, ArrayBuffer)) {
21518 var name1 = value.constructor.name;
21519 var base64 = encode(value);
21520 return {
21521 rr_type: name1,
21522 base64: base64
21523 };
21524 } else if (_instanceof(value, DataView)) {
21525 var name2 = value.constructor.name;
21526 return {
21527 rr_type: name2,
21528 args: [
21529 serializeArg(value.buffer, win, ctx),
21530 value.byteOffset,
21531 value.byteLength
21532 ]
21533 };
21534 } else if (_instanceof(value, HTMLImageElement)) {
21535 var name3 = value.constructor.name;
21536 var src = value.src;
21537 return {
21538 rr_type: name3,
21539 src: src
21540 };
21541 } else if (_instanceof(value, HTMLCanvasElement)) {
21542 var name4 = "HTMLImageElement";
21543 var src1 = value.toDataURL();
21544 return {
21545 rr_type: name4,
21546 src: src1
21547 };
21548 } else if (_instanceof(value, ImageData)) {
21549 var name5 = value.constructor.name;
21550 return {
21551 rr_type: name5,
21552 args: [
21553 serializeArg(value.data, win, ctx),
21554 value.width,
21555 value.height
21556 ]
21557 };
21558 } else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
21559 var name6 = value.constructor.name;
21560 var index2 = saveWebGLVar(value, win, ctx);
21561 return {
21562 rr_type: name6,
21563 index: index2
21564 };
21565 }
21566 return value;
21567 }
21568 var serializeArgs = function(args, win, ctx) {
21569 return args.map(function(arg) {
21570 return serializeArg(arg, win, ctx);
21571 });
21572 };
21573 var isInstanceOfWebGLObject = function(value, win) {
21574 var webGLConstructorNames = [
21575 "WebGLActiveInfo",
21576 "WebGLBuffer",
21577 "WebGLFramebuffer",
21578 "WebGLProgram",
21579 "WebGLRenderbuffer",
21580 "WebGLShader",
21581 "WebGLShaderPrecisionFormat",
21582 "WebGLTexture",
21583 "WebGLUniformLocation",
21584 "WebGLVertexArrayObject",
21585 // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.
21586 "WebGLVertexArrayObjectOES"
21587 ];
21588 var supportedWebGLConstructorNames = webGLConstructorNames.filter(function(name) {
21589 return typeof win[name] === "function";
21590 });
21591 return Boolean(supportedWebGLConstructorNames.find(function(name) {
21592 return _instanceof(value, win[name]);
21593 }));
21594 };
21595 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
21596 var _loop = function() {
21597 var prop = _step.value;
21598 try {
21599 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") {
21600 return "continue";
21601 }
21602 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
21603 return function() {
21604 var _this = this;
21605 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
21606 args[_key] = arguments[_key];
21607 }
21608 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
21609 setTimeout(function() {
21610 var recordArgs = serializeArgs(args, win, _this);
21611 cb(_this.canvas, {
21612 type: CanvasContext["2D"],
21613 property: prop,
21614 args: recordArgs
21615 });
21616 }, 0);
21617 }
21618 return original.apply(this, args);
21619 };
21620 });
21621 handlers.push(restoreHandler);
21622 } catch (e) {
21623 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
21624 set: function set(v2) {
21625 cb(this.canvas, {
21626 type: CanvasContext["2D"],
21627 property: prop,
21628 args: [
21629 v2
21630 ],
21631 setter: true
21632 });
21633 }
21634 });
21635 handlers.push(hookHandler);
21636 }
21637 };
21638 var handlers = [];
21639 var props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
21640 for(var _iterator = _create_for_of_iterator_helper_loose(props2D), _step; !(_step = _iterator()).done;)_loop();
21641 return function() {
21642 handlers.forEach(function(h) {
21643 return h();
21644 });
21645 };
21646 }
21647 function getNormalizedContextName(contextType) {
21648 return contextType === "experimental-webgl" ? "webgl" : contextType;
21649 }
21650 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
21651 var handlers = [];
21652 try {
21653 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
21654 return function(contextType) {
21655 for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
21656 args[_key - 1] = arguments[_key];
21657 }
21658 if (!isBlocked(this, blockClass, blockSelector, true)) {
21659 var ctxName = getNormalizedContextName(contextType);
21660 if (!("__context" in this)) this.__context = ctxName;
21661 if (setPreserveDrawingBufferToTrue && [
21662 "webgl",
21663 "webgl2"
21664 ].includes(ctxName)) {
21665 if (args[0] && _type_of(args[0]) === "object") {
21666 var contextAttributes = args[0];
21667 if (!contextAttributes.preserveDrawingBuffer) {
21668 contextAttributes.preserveDrawingBuffer = true;
21669 }
21670 } else {
21671 args.splice(0, 1, {
21672 preserveDrawingBuffer: true
21673 });
21674 }
21675 }
21676 }
21677 return original.apply(this, [].concat([
21678 contextType
21679 ], args));
21680 };
21681 });
21682 handlers.push(restoreHandler);
21683 } catch (e) {
21684 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
21685 }
21686 return function() {
21687 handlers.forEach(function(h) {
21688 return h();
21689 });
21690 };
21691 }
21692 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
21693 var _loop = function() {
21694 var prop = _step.value;
21695 if (//prop.startsWith('get') || // e.g. getProgramParameter, but too risky
21696 [
21697 "isContextLost",
21698 "canvas",
21699 "drawingBufferWidth",
21700 "drawingBufferHeight"
21701 ].includes(prop)) {
21702 return "continue";
21703 }
21704 try {
21705 if (typeof prototype[prop] !== "function") {
21706 return "continue";
21707 }
21708 var restoreHandler = patch(prototype, prop, function(original) {
21709 return function() {
21710 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
21711 args[_key] = arguments[_key];
21712 }
21713 var result2 = original.apply(this, args);
21714 saveWebGLVar(result2, win, this);
21715 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
21716 var recordArgs = serializeArgs(args, win, this);
21717 var mutation = {
21718 type: type,
21719 property: prop,
21720 args: recordArgs
21721 };
21722 cb(this.canvas, mutation);
21723 }
21724 return result2;
21725 };
21726 });
21727 handlers.push(restoreHandler);
21728 } catch (e) {
21729 var hookHandler = hookSetter(prototype, prop, {
21730 set: function set(v2) {
21731 cb(this.canvas, {
21732 type: type,
21733 property: prop,
21734 args: [
21735 v2
21736 ],
21737 setter: true
21738 });
21739 }
21740 });
21741 handlers.push(hookHandler);
21742 }
21743 };
21744 var handlers = [];
21745 var props = Object.getOwnPropertyNames(prototype);
21746 for(var _iterator = _create_for_of_iterator_helper_loose(props), _step; !(_step = _iterator()).done;)_loop();
21747 return handlers;
21748 }
21749 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
21750 var _handlers;
21751 var handlers = [];
21752 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
21753 if (typeof win.WebGL2RenderingContext !== "undefined") {
21754 var _handlers1;
21755 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
21756 }
21757 return function() {
21758 handlers.forEach(function(h) {
21759 return h();
21760 });
21761 };
21762 }
21763 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
21764 var decodeBase64 = function(base64) {
21765 return Uint8Array.from(atob(base64), function(c2) {
21766 return c2.charCodeAt(0);
21767 });
21768 };
21769 var blob = typeof window !== "undefined" && window.Blob && new Blob([
21770 decodeBase64(encodedJs)
21771 ], {
21772 type: "text/javascript;charset=utf-8"
21773 });
21774 function WorkerWrapper(options) {
21775 var objURL;
21776 try {
21777 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
21778 if (!objURL) throw "";
21779 var worker = new Worker(objURL, {
21780 name: options == null ? void 0 : options.name
21781 });
21782 worker.addEventListener("error", function() {
21783 (window.URL || window.webkitURL).revokeObjectURL(objURL);
21784 });
21785 return worker;
21786 } catch (e2) {
21787 return new Worker("data:text/javascript;base64," + encodedJs, {
21788 name: options == null ? void 0 : options.name
21789 });
21790 } finally{
21791 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
21792 }
21793 }
21794 var CanvasManager = /*#__PURE__*/ function() {
21795 function CanvasManager(options) {
21796 var _this = this;
21797 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
21798 __publicField(this, "rafStamps", {
21799 latestId: 0,
21800 invokeId: null
21801 });
21802 __publicField(this, "mirror");
21803 __publicField(this, "mutationCb");
21804 __publicField(this, "resetObservers");
21805 __publicField(this, "frozen", false);
21806 __publicField(this, "locked", false);
21807 __publicField(this, "processMutation", function(target, mutation) {
21808 var newFrame = _this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId;
21809 if (newFrame || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
21810 if (!_this.pendingCanvasMutations.has(target)) {
21811 _this.pendingCanvasMutations.set(target, []);
21812 }
21813 _this.pendingCanvasMutations.get(target).push(mutation);
21814 });
21815 var _options_sampling = options.sampling, sampling = _options_sampling === void 0 ? "all" : _options_sampling, win = options.win, blockClass = options.blockClass, blockSelector = options.blockSelector, recordCanvas = options.recordCanvas, dataURLOptions = options.dataURLOptions;
21816 this.mutationCb = options.mutationCb;
21817 this.mirror = options.mirror;
21818 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
21819 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
21820 dataURLOptions: dataURLOptions
21821 });
21822 }
21823 var _proto = CanvasManager.prototype;
21824 _proto.reset = function reset() {
21825 this.pendingCanvasMutations.clear();
21826 this.resetObservers && this.resetObservers();
21827 };
21828 _proto.freeze = function freeze() {
21829 this.frozen = true;
21830 };
21831 _proto.unfreeze = function unfreeze() {
21832 this.frozen = false;
21833 };
21834 _proto.lock = function lock() {
21835 this.locked = true;
21836 };
21837 _proto.unlock = function unlock() {
21838 this.locked = false;
21839 };
21840 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
21841 var _this = this;
21842 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
21843 var snapshotInProgressMap = /* @__PURE__ */ new Map();
21844 var worker = new WorkerWrapper();
21845 worker.onmessage = function(e2) {
21846 var id = e2.data.id;
21847 snapshotInProgressMap.set(id, false);
21848 if (!("base64" in e2.data)) return;
21849 var _e2_data = e2.data, base64 = _e2_data.base64, type = _e2_data.type, width = _e2_data.width, height = _e2_data.height;
21850 _this.mutationCb({
21851 id: id,
21852 type: CanvasContext["2D"],
21853 commands: [
21854 {
21855 property: "clearRect",
21856 // wipe canvas
21857 args: [
21858 0,
21859 0,
21860 width,
21861 height
21862 ]
21863 },
21864 {
21865 property: "drawImage",
21866 // draws (semi-transparent) image
21867 args: [
21868 {
21869 rr_type: "ImageBitmap",
21870 args: [
21871 {
21872 rr_type: "Blob",
21873 data: [
21874 {
21875 rr_type: "ArrayBuffer",
21876 base64: base64
21877 }
21878 ],
21879 type: type
21880 }
21881 ]
21882 },
21883 0,
21884 0
21885 ]
21886 }
21887 ]
21888 });
21889 };
21890 var timeBetweenSnapshots = 1e3 / fps;
21891 var lastSnapshotTime = 0;
21892 var rafId;
21893 var getCanvas = function() {
21894 var matchedCanvas = [];
21895 win.document.querySelectorAll("canvas").forEach(function(canvas) {
21896 if (!isBlocked(canvas, blockClass, blockSelector, true)) {
21897 matchedCanvas.push(canvas);
21898 }
21899 });
21900 return matchedCanvas;
21901 };
21902 var takeCanvasSnapshots = function(timestamp) {
21903 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
21904 rafId = requestAnimationFrame(takeCanvasSnapshots);
21905 return;
21906 }
21907 lastSnapshotTime = timestamp;
21908 var _this1 = _this;
21909 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
21910 var _a2, id, context, bitmap;
21911 return _ts_generator(this, function(_state) {
21912 switch(_state.label){
21913 case 0:
21914 id = _this1.mirror.getId(canvas);
21915 if (snapshotInProgressMap.get(id)) return [
21916 2
21917 ];
21918 if (canvas.width === 0 || canvas.height === 0) return [
21919 2
21920 ];
21921 snapshotInProgressMap.set(id, true);
21922 if ([
21923 "webgl",
21924 "webgl2"
21925 ].includes(canvas.__context)) {
21926 context = canvas.getContext(canvas.__context);
21927 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) {
21928 context.clear(context.COLOR_BUFFER_BIT);
21929 }
21930 }
21931 return [
21932 4,
21933 createImageBitmap(canvas)
21934 ];
21935 case 1:
21936 bitmap = _state.sent();
21937 worker.postMessage({
21938 id: id,
21939 bitmap: bitmap,
21940 width: canvas.width,
21941 height: canvas.height,
21942 dataURLOptions: options.dataURLOptions
21943 }, [
21944 bitmap
21945 ]);
21946 return [
21947 2
21948 ];
21949 }
21950 });
21951 }));
21952 rafId = requestAnimationFrame(takeCanvasSnapshots);
21953 };
21954 rafId = requestAnimationFrame(takeCanvasSnapshots);
21955 this.resetObservers = function() {
21956 canvasContextReset();
21957 cancelAnimationFrame(rafId);
21958 };
21959 };
21960 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
21961 this.startRAFTimestamping();
21962 this.startPendingCanvasMutationFlusher();
21963 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
21964 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
21965 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
21966 this.resetObservers = function() {
21967 canvasContextReset();
21968 canvas2DReset();
21969 canvasWebGL1and2Reset();
21970 };
21971 };
21972 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
21973 var _this = this;
21974 requestAnimationFrame(function() {
21975 return _this.flushPendingCanvasMutations();
21976 });
21977 };
21978 _proto.startRAFTimestamping = function startRAFTimestamping() {
21979 var _this = this;
21980 var setLatestRAFTimestamp = function(timestamp) {
21981 _this.rafStamps.latestId = timestamp;
21982 requestAnimationFrame(setLatestRAFTimestamp);
21983 };
21984 requestAnimationFrame(setLatestRAFTimestamp);
21985 };
21986 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
21987 var _this = this;
21988 this.pendingCanvasMutations.forEach(function(_values, canvas) {
21989 var id = _this.mirror.getId(canvas);
21990 _this.flushPendingCanvasMutationFor(canvas, id);
21991 });
21992 requestAnimationFrame(function() {
21993 return _this.flushPendingCanvasMutations();
21994 });
21995 };
21996 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
21997 if (this.frozen || this.locked) {
21998 return;
21999 }
22000 var valuesWithType = this.pendingCanvasMutations.get(canvas);
22001 if (!valuesWithType || id === -1) return;
22002 var values = valuesWithType.map(function(value) {
22003 value.type; var rest = _object_without_properties_loose(value, [
22004 "type"
22005 ]);
22006 return rest;
22007 });
22008 var type = valuesWithType[0].type;
22009 this.mutationCb({
22010 id: id,
22011 type: type,
22012 commands: values
22013 });
22014 this.pendingCanvasMutations.delete(canvas);
22015 };
22016 return CanvasManager;
22017 }();
22018 var StylesheetManager = /*#__PURE__*/ function() {
22019 function StylesheetManager(options) {
22020 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
22021 __publicField(this, "mutationCb");
22022 __publicField(this, "adoptedStyleSheetCb");
22023 __publicField(this, "styleMirror", new StyleSheetMirror());
22024 this.mutationCb = options.mutationCb;
22025 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
22026 }
22027 var _proto = StylesheetManager.prototype;
22028 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
22029 if ("_cssText" in childSn.attributes) this.mutationCb({
22030 adds: [],
22031 removes: [],
22032 texts: [],
22033 attributes: [
22034 {
22035 id: childSn.id,
22036 attributes: childSn.attributes
22037 }
22038 ]
22039 });
22040 this.trackLinkElement(linkEl);
22041 };
22042 _proto.trackLinkElement = function trackLinkElement(linkEl) {
22043 if (this.trackedLinkElements.has(linkEl)) return;
22044 this.trackedLinkElements.add(linkEl);
22045 this.trackStylesheetInLinkElement(linkEl);
22046 };
22047 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
22048 var _this, _loop = function() {
22049 var sheet = _step.value;
22050 var styleId = void 0;
22051 if (!_this.styleMirror.has(sheet)) {
22052 styleId = _this.styleMirror.add(sheet);
22053 styles.push({
22054 styleId: styleId,
22055 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
22056 return {
22057 rule: stringifyRule(r2, sheet.href),
22058 index: index2
22059 };
22060 })
22061 });
22062 } else styleId = _this.styleMirror.getId(sheet);
22063 adoptedStyleSheetData.styleIds.push(styleId);
22064 };
22065 if (sheets.length === 0) return;
22066 var adoptedStyleSheetData = {
22067 id: hostId,
22068 styleIds: []
22069 };
22070 var styles = [];
22071 for(var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;)_this = this, _loop();
22072 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
22073 this.adoptedStyleSheetCb(adoptedStyleSheetData);
22074 };
22075 _proto.reset = function reset() {
22076 this.styleMirror.reset();
22077 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
22078 };
22079 // TODO: take snapshot on stylesheet reload by applying event listener
22080 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
22081 return StylesheetManager;
22082 }();
22083 var ProcessedNodeManager = /*#__PURE__*/ function() {
22084 function ProcessedNodeManager() {
22085 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
22086 __publicField(this, "active", false);
22087 }
22088 var _proto = ProcessedNodeManager.prototype;
22089 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
22090 var buffers = this.nodeMap.get(node2);
22091 return buffers && Array.from(buffers).some(function(buffer) {
22092 return buffer !== thisBuffer;
22093 });
22094 };
22095 _proto.add = function add(node2, buffer) {
22096 var _this = this;
22097 if (!this.active) {
22098 this.active = true;
22099 requestAnimationFrame(function() {
22100 _this.nodeMap = /* @__PURE__ */ new WeakMap();
22101 _this.active = false;
22102 });
22103 }
22104 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
22105 };
22106 _proto.destroy = function destroy() {};
22107 return ProcessedNodeManager;
22108 }();
22109 var wrappedEmit;
22110 var takeFullSnapshot$1;
22111 var canvasManager;
22112 var recording = false;
22113 try {
22114 if (Array.from([
22115 1
22116 ], function(x2) {
22117 return x2 * 2;
22118 })[0] !== 2) {
22119 var cleanFrame = document.createElement("iframe");
22120 document.body.appendChild(cleanFrame);
22121 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
22122 document.body.removeChild(cleanFrame);
22123 }
22124 } catch (err) {
22125 console.debug("Unable to override Array.from", err);
22126 }
22127 var mirror = createMirror$2();
22128 function record(options) {
22129 if (options === void 0) options = {};
22130 var emit = options.emit, checkoutEveryNms = options.checkoutEveryNms, checkoutEveryNth = options.checkoutEveryNth, _options_blockClass = options.blockClass, blockClass = _options_blockClass === void 0 ? "rr-block" : _options_blockClass, _options_blockSelector = options.blockSelector, blockSelector = _options_blockSelector === void 0 ? null : _options_blockSelector, _options_ignoreClass = options.ignoreClass, ignoreClass = _options_ignoreClass === void 0 ? "rr-ignore" : _options_ignoreClass, _options_ignoreSelector = options.ignoreSelector, ignoreSelector = _options_ignoreSelector === void 0 ? null : _options_ignoreSelector, _options_maskTextClass = options.maskTextClass, maskTextClass = _options_maskTextClass === void 0 ? "rr-mask" : _options_maskTextClass, _options_maskTextSelector = options.maskTextSelector, maskTextSelector = _options_maskTextSelector === void 0 ? null : _options_maskTextSelector, _options_inlineStylesheet = options.inlineStylesheet, inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet, maskAllInputs = options.maskAllInputs, _maskInputOptions = options.maskInputOptions, _slimDOMOptions = options.slimDOMOptions, maskInputFn = options.maskInputFn, maskTextFn = options.maskTextFn, hooks = options.hooks, packFn = options.packFn, _options_sampling = options.sampling, sampling = _options_sampling === void 0 ? {} : _options_sampling, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, mousemoveWait = options.mousemoveWait, _options_recordDOM = options.recordDOM, recordDOM = _options_recordDOM === void 0 ? true : _options_recordDOM, _options_recordCanvas = options.recordCanvas, recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas, _options_recordCrossOriginIframes = options.recordCrossOriginIframes, recordCrossOriginIframes = _options_recordCrossOriginIframes === void 0 ? false : _options_recordCrossOriginIframes, _options_recordAfter = options.recordAfter, recordAfter = _options_recordAfter === void 0 ? options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load" : _options_recordAfter, _options_userTriggeredOnInput = options.userTriggeredOnInput, userTriggeredOnInput = _options_userTriggeredOnInput === void 0 ? false : _options_userTriggeredOnInput, _options_collectFonts = options.collectFonts, collectFonts = _options_collectFonts === void 0 ? false : _options_collectFonts, _options_inlineImages = options.inlineImages, inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages, plugins = options.plugins, _options_keepIframeSrcFn = options.keepIframeSrcFn, keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
22131 return false;
22132 } : _options_keepIframeSrcFn, _options_ignoreCSSAttributes = options.ignoreCSSAttributes, ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes, errorHandler2 = options.errorHandler;
22133 registerErrorHandler(errorHandler2);
22134 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
22135 var passEmitsToParent = false;
22136 if (!inEmittingFrame) {
22137 try {
22138 if (window.parent.document) {
22139 passEmitsToParent = false;
22140 }
22141 } catch (e2) {
22142 passEmitsToParent = true;
22143 }
22144 }
22145 if (inEmittingFrame && !emit) {
22146 throw new Error("emit function is required");
22147 }
22148 if (!inEmittingFrame && !passEmitsToParent) {
22149 return function() {};
22150 }
22151 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
22152 sampling.mousemove = mousemoveWait;
22153 }
22154 mirror.reset();
22155 var maskInputOptions = maskAllInputs === true ? {
22156 color: true,
22157 date: true,
22158 "datetime-local": true,
22159 email: true,
22160 month: true,
22161 number: true,
22162 range: true,
22163 search: true,
22164 tel: true,
22165 text: true,
22166 time: true,
22167 url: true,
22168 week: true,
22169 textarea: true,
22170 select: true,
22171 password: true,
22172 hidden: true
22173 } : _maskInputOptions !== void 0 ? _maskInputOptions : {
22174 password: true
22175 };
22176 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
22177 script: true,
22178 comment: true,
22179 headFavicon: true,
22180 headWhitespace: true,
22181 headMetaSocial: true,
22182 headMetaRobots: true,
22183 headMetaHttpEquiv: true,
22184 headMetaVerification: true,
22185 // the following are off for slimDOMOptions === true,
22186 // as they destroy some (hidden) info:
22187 headMetaAuthorship: _slimDOMOptions === "all",
22188 headMetaDescKeywords: _slimDOMOptions === "all",
22189 headTitleMutations: _slimDOMOptions === "all"
22190 } : _slimDOMOptions ? _slimDOMOptions : {};
22191 polyfill$1();
22192 var lastFullSnapshotEvent;
22193 var incrementalSnapshotCount = 0;
22194 var eventProcessor = function(e2) {
22195 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
22196 var plugin3 = _step.value;
22197 if (plugin3.eventProcessor) {
22198 e2 = plugin3.eventProcessor(e2);
22199 }
22200 }
22201 if (packFn && // Disable packing events which will be emitted to parent frames.
22202 !passEmitsToParent) {
22203 e2 = packFn(e2);
22204 }
22205 return e2;
22206 };
22207 wrappedEmit = function(r2, isCheckout) {
22208 var _a2;
22209 var e2 = r2;
22210 e2.timestamp = nowTimestamp();
22211 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {
22212 mutationBuffers.forEach(function(buf) {
22213 return buf.unfreeze();
22214 });
22215 }
22216 if (inEmittingFrame) {
22217 emit == null ? void 0 : emit(eventProcessor(e2), isCheckout);
22218 } else if (passEmitsToParent) {
22219 var message = {
22220 type: "rrweb",
22221 event: eventProcessor(e2),
22222 origin: window.location.origin,
22223 isCheckout: isCheckout
22224 };
22225 window.parent.postMessage(message, "*");
22226 }
22227 if (e2.type === EventType.FullSnapshot) {
22228 lastFullSnapshotEvent = e2;
22229 incrementalSnapshotCount = 0;
22230 } else if (e2.type === EventType.IncrementalSnapshot) {
22231 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {
22232 return;
22233 }
22234 incrementalSnapshotCount++;
22235 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
22236 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
22237 if (exceedCount || exceedTime) {
22238 takeFullSnapshot$1(true);
22239 }
22240 }
22241 };
22242 var wrappedMutationEmit = function(m) {
22243 wrappedEmit({
22244 type: EventType.IncrementalSnapshot,
22245 data: _extends({
22246 source: IncrementalSource.Mutation
22247 }, m)
22248 });
22249 };
22250 var wrappedScrollEmit = function(p) {
22251 return wrappedEmit({
22252 type: EventType.IncrementalSnapshot,
22253 data: _extends({
22254 source: IncrementalSource.Scroll
22255 }, p)
22256 });
22257 };
22258 var wrappedCanvasMutationEmit = function(p) {
22259 return wrappedEmit({
22260 type: EventType.IncrementalSnapshot,
22261 data: _extends({
22262 source: IncrementalSource.CanvasMutation
22263 }, p)
22264 });
22265 };
22266 var wrappedAdoptedStyleSheetEmit = function(a2) {
22267 return wrappedEmit({
22268 type: EventType.IncrementalSnapshot,
22269 data: _extends({
22270 source: IncrementalSource.AdoptedStyleSheet
22271 }, a2)
22272 });
22273 };
22274 var stylesheetManager = new StylesheetManager({
22275 mutationCb: wrappedMutationEmit,
22276 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
22277 });
22278 var iframeManager = new IframeManager({
22279 mirror: mirror,
22280 mutationCb: wrappedMutationEmit,
22281 stylesheetManager: stylesheetManager,
22282 recordCrossOriginIframes: recordCrossOriginIframes,
22283 wrappedEmit: wrappedEmit
22284 });
22285 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
22286 var plugin3 = _step.value;
22287 if (plugin3.getMirror) plugin3.getMirror({
22288 nodeMirror: mirror,
22289 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
22290 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
22291 });
22292 }
22293 var processedNodeManager = new ProcessedNodeManager();
22294 canvasManager = new CanvasManager({
22295 recordCanvas: recordCanvas,
22296 mutationCb: wrappedCanvasMutationEmit,
22297 win: window,
22298 blockClass: blockClass,
22299 blockSelector: blockSelector,
22300 mirror: mirror,
22301 sampling: sampling.canvas,
22302 dataURLOptions: dataURLOptions
22303 });
22304 var shadowDomManager = new ShadowDomManager({
22305 mutationCb: wrappedMutationEmit,
22306 scrollCb: wrappedScrollEmit,
22307 bypassOptions: {
22308 blockClass: blockClass,
22309 blockSelector: blockSelector,
22310 maskTextClass: maskTextClass,
22311 maskTextSelector: maskTextSelector,
22312 inlineStylesheet: inlineStylesheet,
22313 maskInputOptions: maskInputOptions,
22314 dataURLOptions: dataURLOptions,
22315 maskTextFn: maskTextFn,
22316 maskInputFn: maskInputFn,
22317 recordCanvas: recordCanvas,
22318 inlineImages: inlineImages,
22319 sampling: sampling,
22320 slimDOMOptions: slimDOMOptions,
22321 iframeManager: iframeManager,
22322 stylesheetManager: stylesheetManager,
22323 canvasManager: canvasManager,
22324 keepIframeSrcFn: keepIframeSrcFn,
22325 processedNodeManager: processedNodeManager
22326 },
22327 mirror: mirror
22328 });
22329 takeFullSnapshot$1 = function(isCheckout) {
22330 if (isCheckout === void 0) isCheckout = false;
22331 if (!recordDOM) {
22332 return;
22333 }
22334 wrappedEmit({
22335 type: EventType.Meta,
22336 data: {
22337 href: window.location.href,
22338 width: getWindowWidth(),
22339 height: getWindowHeight()
22340 }
22341 }, isCheckout);
22342 stylesheetManager.reset();
22343 shadowDomManager.init();
22344 mutationBuffers.forEach(function(buf) {
22345 return buf.lock();
22346 });
22347 var node2 = snapshot(document, {
22348 mirror: mirror,
22349 blockClass: blockClass,
22350 blockSelector: blockSelector,
22351 maskTextClass: maskTextClass,
22352 maskTextSelector: maskTextSelector,
22353 inlineStylesheet: inlineStylesheet,
22354 maskAllInputs: maskInputOptions,
22355 maskTextFn: maskTextFn,
22356 maskInputFn: maskInputFn,
22357 slimDOM: slimDOMOptions,
22358 dataURLOptions: dataURLOptions,
22359 recordCanvas: recordCanvas,
22360 inlineImages: inlineImages,
22361 onSerialize: function(n2) {
22362 if (isSerializedIframe(n2, mirror)) {
22363 iframeManager.addIframe(n2);
22364 }
22365 if (isSerializedStylesheet(n2, mirror)) {
22366 stylesheetManager.trackLinkElement(n2);
22367 }
22368 if (hasShadowRoot(n2)) {
22369 shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
22370 }
22371 },
22372 onIframeLoad: function(iframe, childSn) {
22373 iframeManager.attachIframe(iframe, childSn);
22374 shadowDomManager.observeAttachShadow(iframe);
22375 },
22376 onStylesheetLoad: function(linkEl, childSn) {
22377 stylesheetManager.attachLinkElement(linkEl, childSn);
22378 },
22379 keepIframeSrcFn: keepIframeSrcFn
22380 });
22381 if (!node2) {
22382 return console.warn("Failed to snapshot the document");
22383 }
22384 wrappedEmit({
22385 type: EventType.FullSnapshot,
22386 data: {
22387 node: node2,
22388 initialOffset: getWindowScroll(window)
22389 }
22390 }, isCheckout);
22391 mutationBuffers.forEach(function(buf) {
22392 return buf.unlock();
22393 });
22394 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
22395 };
22396 try {
22397 var handlers = [];
22398 var observe = function(doc) {
22399 var _a2;
22400 return callbackWrapper(initObservers)({
22401 mutationCb: wrappedMutationEmit,
22402 mousemoveCb: function(positions, source) {
22403 return wrappedEmit({
22404 type: EventType.IncrementalSnapshot,
22405 data: {
22406 source: source,
22407 positions: positions
22408 }
22409 });
22410 },
22411 mouseInteractionCb: function(d) {
22412 return wrappedEmit({
22413 type: EventType.IncrementalSnapshot,
22414 data: _extends({
22415 source: IncrementalSource.MouseInteraction
22416 }, d)
22417 });
22418 },
22419 scrollCb: wrappedScrollEmit,
22420 viewportResizeCb: function(d) {
22421 return wrappedEmit({
22422 type: EventType.IncrementalSnapshot,
22423 data: _extends({
22424 source: IncrementalSource.ViewportResize
22425 }, d)
22426 });
22427 },
22428 inputCb: function(v2) {
22429 return wrappedEmit({
22430 type: EventType.IncrementalSnapshot,
22431 data: _extends({
22432 source: IncrementalSource.Input
22433 }, v2)
22434 });
22435 },
22436 mediaInteractionCb: function(p) {
22437 return wrappedEmit({
22438 type: EventType.IncrementalSnapshot,
22439 data: _extends({
22440 source: IncrementalSource.MediaInteraction
22441 }, p)
22442 });
22443 },
22444 styleSheetRuleCb: function(r2) {
22445 return wrappedEmit({
22446 type: EventType.IncrementalSnapshot,
22447 data: _extends({
22448 source: IncrementalSource.StyleSheetRule
22449 }, r2)
22450 });
22451 },
22452 styleDeclarationCb: function(r2) {
22453 return wrappedEmit({
22454 type: EventType.IncrementalSnapshot,
22455 data: _extends({
22456 source: IncrementalSource.StyleDeclaration
22457 }, r2)
22458 });
22459 },
22460 canvasMutationCb: wrappedCanvasMutationEmit,
22461 fontCb: function(p) {
22462 return wrappedEmit({
22463 type: EventType.IncrementalSnapshot,
22464 data: _extends({
22465 source: IncrementalSource.Font
22466 }, p)
22467 });
22468 },
22469 selectionCb: function(p) {
22470 wrappedEmit({
22471 type: EventType.IncrementalSnapshot,
22472 data: _extends({
22473 source: IncrementalSource.Selection
22474 }, p)
22475 });
22476 },
22477 customElementCb: function(c2) {
22478 wrappedEmit({
22479 type: EventType.IncrementalSnapshot,
22480 data: _extends({
22481 source: IncrementalSource.CustomElement
22482 }, c2)
22483 });
22484 },
22485 blockClass: blockClass,
22486 ignoreClass: ignoreClass,
22487 ignoreSelector: ignoreSelector,
22488 maskTextClass: maskTextClass,
22489 maskTextSelector: maskTextSelector,
22490 maskInputOptions: maskInputOptions,
22491 inlineStylesheet: inlineStylesheet,
22492 sampling: sampling,
22493 recordDOM: recordDOM,
22494 recordCanvas: recordCanvas,
22495 inlineImages: inlineImages,
22496 userTriggeredOnInput: userTriggeredOnInput,
22497 collectFonts: collectFonts,
22498 doc: doc,
22499 maskInputFn: maskInputFn,
22500 maskTextFn: maskTextFn,
22501 keepIframeSrcFn: keepIframeSrcFn,
22502 blockSelector: blockSelector,
22503 slimDOMOptions: slimDOMOptions,
22504 dataURLOptions: dataURLOptions,
22505 mirror: mirror,
22506 iframeManager: iframeManager,
22507 stylesheetManager: stylesheetManager,
22508 shadowDomManager: shadowDomManager,
22509 processedNodeManager: processedNodeManager,
22510 canvasManager: canvasManager,
22511 ignoreCSSAttributes: ignoreCSSAttributes,
22512 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
22513 return p.observer;
22514 })) == null ? void 0 : _a2.map(function(p) {
22515 return {
22516 observer: p.observer,
22517 options: p.options,
22518 callback: function(payload) {
22519 return wrappedEmit({
22520 type: EventType.Plugin,
22521 data: {
22522 plugin: p.name,
22523 payload: payload
22524 }
22525 });
22526 }
22527 };
22528 })) || []
22529 }, hooks);
22530 };
22531 iframeManager.addLoadListener(function(iframeEl) {
22532 try {
22533 handlers.push(observe(iframeEl.contentDocument));
22534 } catch (error) {
22535 console.warn(error);
22536 }
22537 });
22538 var init = function() {
22539 takeFullSnapshot$1();
22540 handlers.push(observe(document));
22541 recording = true;
22542 };
22543 if (document.readyState === "interactive" || document.readyState === "complete") {
22544 init();
22545 } else {
22546 handlers.push(on("DOMContentLoaded", function() {
22547 wrappedEmit({
22548 type: EventType.DomContentLoaded,
22549 data: {}
22550 });
22551 if (recordAfter === "DOMContentLoaded") init();
22552 }));
22553 handlers.push(on("load", function() {
22554 wrappedEmit({
22555 type: EventType.Load,
22556 data: {}
22557 });
22558 if (recordAfter === "load") init();
22559 }, window));
22560 }
22561 return function() {
22562 handlers.forEach(function(handler) {
22563 try {
22564 handler();
22565 } catch (error) {
22566 var msg = String(error).toLowerCase();
22567 if (!msg.includes("cross-origin")) {
22568 console.warn(error);
22569 }
22570 }
22571 });
22572 processedNodeManager.destroy();
22573 recording = false;
22574 unregisterErrorHandler();
22575 };
22576 } catch (error) {
22577 console.warn(error);
22578 }
22579 }
22580 record.addCustomEvent = function(tag, payload) {
22581 if (!recording) {
22582 throw new Error("please add custom event after start recording");
22583 }
22584 wrappedEmit({
22585 type: EventType.Custom,
22586 data: {
22587 tag: tag,
22588 payload: payload
22589 }
22590 });
22591 };
22592 record.freezePage = function() {
22593 mutationBuffers.forEach(function(buf) {
22594 return buf.freeze();
22595 });
22596 };
22597 record.takeFullSnapshot = function(isCheckout) {
22598 if (!recording) {
22599 throw new Error("please take full snapshot after start recording");
22600 }
22601 takeFullSnapshot$1(isCheckout);
22602 };
22603 record.mirror = mirror;
22604 var n;
22605 !function(t2) {
22606 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
22607 }(n || (n = {}));
22608 record.addCustomEvent;
22609 record.freezePage;
22610 record.takeFullSnapshot;
22611
22612 var setImmediate = win['setImmediate'];
22613 var builtInProp, cycle, schedulingQueue,
22614 ToString = Object.prototype.toString,
22615 timer = (typeof setImmediate !== 'undefined') ?
22616 function timer(fn) { return setImmediate(fn); } :
22617 setTimeout;
22618
22619 // dammit, IE8.
22620 try {
22621 Object.defineProperty({},'x',{});
22622 builtInProp = function builtInProp(obj,name,val,config) {
22623 return Object.defineProperty(obj,name,{
22624 value: val,
22625 writable: true,
22626 configurable: config !== false
22627 });
22628 };
22629 }
22630 catch (err) {
22631 builtInProp = function builtInProp(obj,name,val) {
22632 obj[name] = val;
22633 return obj;
22634 };
22635 }
22636
22637 // Note: using a queue instead of array for efficiency
22638 schedulingQueue = (function Queue() {
22639 var first, last, item;
22640
22641 function Item(fn,self) {
22642 this.fn = fn;
22643 this.self = self;
22644 this.next = void 0;
22645 }
22646
22647 return {
22648 add: function add(fn,self) {
22649 item = new Item(fn,self);
22650 if (last) {
22651 last.next = item;
22652 }
22653 else {
22654 first = item;
22655 }
22656 last = item;
22657 item = void 0;
22658 },
22659 drain: function drain() {
22660 var f = first;
22661 first = last = cycle = void 0;
22662
22663 while (f) {
22664 f.fn.call(f.self);
22665 f = f.next;
22666 }
22667 }
22668 };
22669 })();
22670
22671 function schedule(fn,self) {
22672 schedulingQueue.add(fn,self);
22673 if (!cycle) {
22674 cycle = timer(schedulingQueue.drain);
22675 }
22676 }
22677
22678 // promise duck typing
22679 function isThenable(o) {
22680 var _then, oType = typeof o;
22681
22682 if (o !== null && (oType === 'object' || oType === 'function')) {
22683 _then = o.then;
22684 }
22685 return typeof _then === 'function' ? _then : false;
22686 }
22687
22688 function notify() {
22689 for (var i=0; i<this.chain.length; i++) {
22690 notifyIsolated(
22691 this,
22692 (this.state === 1) ? this.chain[i].success : this.chain[i].failure,
22693 this.chain[i]
22694 );
22695 }
22696 this.chain.length = 0;
22697 }
22698
22699 // NOTE: This is a separate function to isolate
22700 // the `try..catch` so that other code can be
22701 // optimized better
22702 function notifyIsolated(self,cb,chain) {
22703 var ret, _then;
22704 try {
22705 if (cb === false) {
22706 chain.reject(self.msg);
22707 }
22708 else {
22709 if (cb === true) {
22710 ret = self.msg;
22711 }
22712 else {
22713 ret = cb.call(void 0,self.msg);
22714 }
22715
22716 if (ret === chain.promise) {
22717 chain.reject(TypeError('Promise-chain cycle'));
22718 }
22719 // eslint-disable-next-line no-cond-assign
22720 else if (_then = isThenable(ret)) {
22721 _then.call(ret,chain.resolve,chain.reject);
22722 }
22723 else {
22724 chain.resolve(ret);
22725 }
22726 }
22727 }
22728 catch (err) {
22729 chain.reject(err);
22730 }
22731 }
22732
22733 function resolve(msg) {
22734 var _then, self = this;
22735
22736 // already triggered?
22737 if (self.triggered) { return; }
22738
22739 self.triggered = true;
22740
22741 // unwrap
22742 if (self.def) {
22743 self = self.def;
22744 }
22745
22746 try {
22747 // eslint-disable-next-line no-cond-assign
22748 if (_then = isThenable(msg)) {
22749 schedule(function(){
22750 var defWrapper = new MakeDefWrapper(self);
22751 try {
22752 _then.call(msg,
22753 function $resolve$(){ resolve.apply(defWrapper,arguments); },
22754 function $reject$(){ reject.apply(defWrapper,arguments); }
22755 );
22756 }
22757 catch (err) {
22758 reject.call(defWrapper,err);
22759 }
22760 });
22761 }
22762 else {
22763 self.msg = msg;
22764 self.state = 1;
22765 if (self.chain.length > 0) {
22766 schedule(notify,self);
22767 }
22768 }
22769 }
22770 catch (err) {
22771 reject.call(new MakeDefWrapper(self),err);
22772 }
22773 }
22774
22775 function reject(msg) {
22776 var self = this;
22777
22778 // already triggered?
22779 if (self.triggered) { return; }
22780
22781 self.triggered = true;
22782
22783 // unwrap
22784 if (self.def) {
22785 self = self.def;
22786 }
22787
22788 self.msg = msg;
22789 self.state = 2;
22790 if (self.chain.length > 0) {
22791 schedule(notify,self);
22792 }
22793 }
22794
22795 function iteratePromises(Constructor,arr,resolver,rejecter) {
22796 for (var idx=0; idx<arr.length; idx++) {
22797 (function IIFE(idx){
22798 Constructor.resolve(arr[idx])
22799 .then(
22800 function $resolver$(msg){
22801 resolver(idx,msg);
22802 },
22803 rejecter
22804 );
22805 })(idx);
22806 }
22807 }
22808
22809 function MakeDefWrapper(self) {
22810 this.def = self;
22811 this.triggered = false;
22812 }
22813
22814 function MakeDef(self) {
22815 this.promise = self;
22816 this.state = 0;
22817 this.triggered = false;
22818 this.chain = [];
22819 this.msg = void 0;
22820 }
22821
22822 function NpoPromise(executor) {
22823 if (typeof executor !== 'function') {
22824 throw TypeError('Not a function');
22825 }
22826
22827 if (this['__NPO__'] !== 0) {
22828 throw TypeError('Not a promise');
22829 }
22830
22831 // instance shadowing the inherited "brand"
22832 // to signal an already "initialized" promise
22833 this['__NPO__'] = 1;
22834
22835 var def = new MakeDef(this);
22836
22837 this['then'] = function then(success,failure) {
22838 var o = {
22839 success: typeof success === 'function' ? success : true,
22840 failure: typeof failure === 'function' ? failure : false
22841 };
22842 // Note: `then(..)` itself can be borrowed to be used against
22843 // a different promise constructor for making the chained promise,
22844 // by substituting a different `this` binding.
22845 o.promise = new this.constructor(function extractChain(resolve,reject) {
22846 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22847 throw TypeError('Not a function');
22848 }
22849
22850 o.resolve = resolve;
22851 o.reject = reject;
22852 });
22853 def.chain.push(o);
22854
22855 if (def.state !== 0) {
22856 schedule(notify,def);
22857 }
22858
22859 return o.promise;
22860 };
22861 this['catch'] = function $catch$(failure) {
22862 return this.then(void 0,failure);
22863 };
22864
22865 try {
22866 executor.call(
22867 void 0,
22868 function publicResolve(msg){
22869 resolve.call(def,msg);
22870 },
22871 function publicReject(msg) {
22872 reject.call(def,msg);
22873 }
22874 );
22875 }
22876 catch (err) {
22877 reject.call(def,err);
22878 }
22879 }
22880
22881 var PromisePrototype = builtInProp({},'constructor',NpoPromise,
22882 /*configurable=*/false
22883 );
22884
22885 // Note: Android 4 cannot use `Object.defineProperty(..)` here
22886 NpoPromise.prototype = PromisePrototype;
22887
22888 // built-in "brand" to signal an "uninitialized" promise
22889 builtInProp(PromisePrototype,'__NPO__',0,
22890 /*configurable=*/false
22891 );
22892
22893 builtInProp(NpoPromise,'resolve',function Promise$resolve(msg) {
22894 var Constructor = this;
22895
22896 // spec mandated checks
22897 // note: best "isPromise" check that's practical for now
22898 if (msg && typeof msg === 'object' && msg['__NPO__'] === 1) {
22899 return msg;
22900 }
22901
22902 return new Constructor(function executor(resolve,reject){
22903 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22904 throw TypeError('Not a function');
22905 }
22906
22907 resolve(msg);
22908 });
22909 });
22910
22911 builtInProp(NpoPromise,'reject',function Promise$reject(msg) {
22912 return new this(function executor(resolve,reject){
22913 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22914 throw TypeError('Not a function');
22915 }
22916
22917 reject(msg);
22918 });
22919 });
22920
22921 builtInProp(NpoPromise,'all',function Promise$all(arr) {
22922 var Constructor = this;
22923
22924 // spec mandated checks
22925 if (ToString.call(arr) !== '[object Array]') {
22926 return Constructor.reject(TypeError('Not an array'));
22927 }
22928 if (arr.length === 0) {
22929 return Constructor.resolve([]);
22930 }
22931
22932 return new Constructor(function executor(resolve,reject){
22933 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22934 throw TypeError('Not a function');
22935 }
22936
22937 var len = arr.length, msgs = Array(len), count = 0;
22938
22939 iteratePromises(Constructor,arr,function resolver(idx,msg) {
22940 msgs[idx] = msg;
22941 if (++count === len) {
22942 resolve(msgs);
22943 }
22944 },reject);
22945 });
22946 });
22947
22948 builtInProp(NpoPromise,'race',function Promise$race(arr) {
22949 var Constructor = this;
22950
22951 // spec mandated checks
22952 if (ToString.call(arr) !== '[object Array]') {
22953 return Constructor.reject(TypeError('Not an array'));
22954 }
22955
22956 return new Constructor(function executor(resolve,reject){
22957 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22958 throw TypeError('Not a function');
22959 }
22960
22961 iteratePromises(Constructor,arr,function resolver(idx,msg){
22962 resolve(msg);
22963 },reject);
22964 });
22965 });
22966
22967 var PromisePolyfill;
22968 if (typeof Promise !== 'undefined' && Promise.toString().indexOf('[native code]') !== -1) {
22969 PromisePolyfill = Promise;
22970 } else {
22971 PromisePolyfill = NpoPromise;
22972 }
22973
22974 var Config = {
22975 DEBUG: false,
22976 LIB_VERSION: '2.71.1'
22977 };
22978
22979 /* eslint camelcase: "off", eqeqeq: "off" */
22980
22981 // Maximum allowed session recording length
22982 var MAX_RECORDING_MS = 24 * 60 * 60 * 1000; // 24 hours
22983 // Maximum allowed value for minimum session recording length
22984 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1000; // 8 seconds
22985
22986 /*
22987 * Saved references to long variable names, so that closure compiler can
22988 * minimize file size.
22989 */
22990
22991 var ArrayProto = Array.prototype,
22992 FuncProto = Function.prototype,
22993 ObjProto = Object.prototype,
22994 slice = ArrayProto.slice,
22995 toString = ObjProto.toString,
22996 hasOwnProperty = ObjProto.hasOwnProperty,
22997 windowConsole = win.console,
22998 navigator = win.navigator,
22999 document$1 = win.document,
23000 windowOpera = win.opera,
23001 screen = win.screen,
23002 userAgent = navigator.userAgent;
23003
23004 var nativeBind = FuncProto.bind,
23005 nativeForEach = ArrayProto.forEach,
23006 nativeIndexOf = ArrayProto.indexOf,
23007 nativeMap = ArrayProto.map,
23008 nativeIsArray = Array.isArray,
23009 breaker = {};
23010
23011 var _ = {
23012 trim: function(str) {
23013 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
23014 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
23015 }
23016 };
23017
23018 // Console override
23019 var console$1 = {
23020 /** @type {function(...*)} */
23021 log: function() {
23022 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23023 try {
23024 windowConsole.log.apply(windowConsole, arguments);
23025 } catch (err) {
23026 _.each(arguments, function(arg) {
23027 windowConsole.log(arg);
23028 });
23029 }
23030 }
23031 },
23032 /** @type {function(...*)} */
23033 warn: function() {
23034 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23035 var args = ['Mixpanel warning:'].concat(_.toArray(arguments));
23036 try {
23037 windowConsole.warn.apply(windowConsole, args);
23038 } catch (err) {
23039 _.each(args, function(arg) {
23040 windowConsole.warn(arg);
23041 });
23042 }
23043 }
23044 },
23045 /** @type {function(...*)} */
23046 error: function() {
23047 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23048 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
23049 try {
23050 windowConsole.error.apply(windowConsole, args);
23051 } catch (err) {
23052 _.each(args, function(arg) {
23053 windowConsole.error(arg);
23054 });
23055 }
23056 }
23057 },
23058 /** @type {function(...*)} */
23059 critical: function() {
23060 if (!_.isUndefined(windowConsole) && windowConsole) {
23061 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
23062 try {
23063 windowConsole.error.apply(windowConsole, args);
23064 } catch (err) {
23065 _.each(args, function(arg) {
23066 windowConsole.error(arg);
23067 });
23068 }
23069 }
23070 }
23071 };
23072
23073 var log_func_with_prefix = function(func, prefix) {
23074 return function() {
23075 arguments[0] = '[' + prefix + '] ' + arguments[0];
23076 return func.apply(console$1, arguments);
23077 };
23078 };
23079 var console_with_prefix = function(prefix) {
23080 return {
23081 log: log_func_with_prefix(console$1.log, prefix),
23082 error: log_func_with_prefix(console$1.error, prefix),
23083 critical: log_func_with_prefix(console$1.critical, prefix)
23084 };
23085 };
23086
23087
23088 var safewrap = function(f) {
23089 return function() {
23090 try {
23091 return f.apply(this, arguments);
23092 } catch (e) {
23093 console$1.critical('Implementation error. Please turn on debug and contact support@mixpanel.com.');
23094 if (Config.DEBUG){
23095 console$1.critical(e);
23096 }
23097 }
23098 };
23099 };
23100
23101 var safewrapClass = function(klass) {
23102 var proto = klass.prototype;
23103 for (var func in proto) {
23104 if (typeof(proto[func]) === 'function') {
23105 proto[func] = safewrap(proto[func]);
23106 }
23107 }
23108 };
23109
23110
23111 // UNDERSCORE
23112 // Embed part of the Underscore Library
23113 _.bind = function(func, context) {
23114 var args, bound;
23115 if (nativeBind && func.bind === nativeBind) {
23116 return nativeBind.apply(func, slice.call(arguments, 1));
23117 }
23118 if (!_.isFunction(func)) {
23119 throw new TypeError();
23120 }
23121 args = slice.call(arguments, 2);
23122 bound = function() {
23123 if (!(this instanceof bound)) {
23124 return func.apply(context, args.concat(slice.call(arguments)));
23125 }
23126 var ctor = {};
23127 ctor.prototype = func.prototype;
23128 var self = new ctor();
23129 ctor.prototype = null;
23130 var result = func.apply(self, args.concat(slice.call(arguments)));
23131 if (Object(result) === result) {
23132 return result;
23133 }
23134 return self;
23135 };
23136 return bound;
23137 };
23138
23139 /**
23140 * @param {*=} obj
23141 * @param {function(...*)=} iterator
23142 * @param {Object=} context
23143 */
23144 _.each = function(obj, iterator, context) {
23145 if (obj === null || obj === undefined) {
23146 return;
23147 }
23148 if (nativeForEach && obj.forEach === nativeForEach) {
23149 obj.forEach(iterator, context);
23150 } else if (obj.length === +obj.length) {
23151 for (var i = 0, l = obj.length; i < l; i++) {
23152 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
23153 return;
23154 }
23155 }
23156 } else {
23157 for (var key in obj) {
23158 if (hasOwnProperty.call(obj, key)) {
23159 if (iterator.call(context, obj[key], key, obj) === breaker) {
23160 return;
23161 }
23162 }
23163 }
23164 }
23165 };
23166
23167 _.extend = function(obj) {
23168 _.each(slice.call(arguments, 1), function(source) {
23169 for (var prop in source) {
23170 if (source[prop] !== void 0) {
23171 obj[prop] = source[prop];
23172 }
23173 }
23174 });
23175 return obj;
23176 };
23177
23178 _.isArray = nativeIsArray || function(obj) {
23179 return toString.call(obj) === '[object Array]';
23180 };
23181
23182 // from a comment on http://dbj.org/dbj/?p=286
23183 // fails on only one very rare and deliberate custom object:
23184 // var bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
23185 _.isFunction = function(f) {
23186 try {
23187 return /^\s*\bfunction\b/.test(f);
23188 } catch (x) {
23189 return false;
23190 }
23191 };
23192
23193 _.isArguments = function(obj) {
23194 return !!(obj && hasOwnProperty.call(obj, 'callee'));
23195 };
23196
23197 _.toArray = function(iterable) {
23198 if (!iterable) {
23199 return [];
23200 }
23201 if (iterable.toArray) {
23202 return iterable.toArray();
23203 }
23204 if (_.isArray(iterable)) {
23205 return slice.call(iterable);
23206 }
23207 if (_.isArguments(iterable)) {
23208 return slice.call(iterable);
23209 }
23210 return _.values(iterable);
23211 };
23212
23213 _.map = function(arr, callback, context) {
23214 if (nativeMap && arr.map === nativeMap) {
23215 return arr.map(callback, context);
23216 } else {
23217 var results = [];
23218 _.each(arr, function(item) {
23219 results.push(callback.call(context, item));
23220 });
23221 return results;
23222 }
23223 };
23224
23225 _.keys = function(obj) {
23226 var results = [];
23227 if (obj === null) {
23228 return results;
23229 }
23230 _.each(obj, function(value, key) {
23231 results[results.length] = key;
23232 });
23233 return results;
23234 };
23235
23236 _.values = function(obj) {
23237 var results = [];
23238 if (obj === null) {
23239 return results;
23240 }
23241 _.each(obj, function(value) {
23242 results[results.length] = value;
23243 });
23244 return results;
23245 };
23246
23247 _.include = function(obj, target) {
23248 var found = false;
23249 if (obj === null) {
23250 return found;
23251 }
23252 if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
23253 return obj.indexOf(target) != -1;
23254 }
23255 _.each(obj, function(value) {
23256 if (found || (found = (value === target))) {
23257 return breaker;
23258 }
23259 });
23260 return found;
23261 };
23262
23263 _.includes = function(str, needle) {
23264 return str.indexOf(needle) !== -1;
23265 };
23266
23267 // Underscore Addons
23268 _.inherit = function(subclass, superclass) {
23269 subclass.prototype = new superclass();
23270 subclass.prototype.constructor = subclass;
23271 subclass.superclass = superclass.prototype;
23272 return subclass;
23273 };
23274
23275 _.isObject = function(obj) {
23276 return (obj === Object(obj) && !_.isArray(obj));
23277 };
23278
23279 _.isEmptyObject = function(obj) {
23280 if (_.isObject(obj)) {
23281 for (var key in obj) {
23282 if (hasOwnProperty.call(obj, key)) {
23283 return false;
23284 }
23285 }
23286 return true;
23287 }
23288 return false;
23289 };
23290
23291 _.isUndefined = function(obj) {
23292 return obj === void 0;
23293 };
23294
23295 _.isString = function(obj) {
23296 return toString.call(obj) == '[object String]';
23297 };
23298
23299 _.isDate = function(obj) {
23300 return toString.call(obj) == '[object Date]';
23301 };
23302
23303 _.isNumber = function(obj) {
23304 return toString.call(obj) == '[object Number]';
23305 };
23306
23307 _.isElement = function(obj) {
23308 return !!(obj && obj.nodeType === 1);
23309 };
23310
23311 _.encodeDates = function(obj) {
23312 _.each(obj, function(v, k) {
23313 if (_.isDate(v)) {
23314 obj[k] = _.formatDate(v);
23315 } else if (_.isObject(v)) {
23316 obj[k] = _.encodeDates(v); // recurse
23317 }
23318 });
23319 return obj;
23320 };
23321
23322 _.timestamp = function() {
23323 Date.now = Date.now || function() {
23324 return +new Date;
23325 };
23326 return Date.now();
23327 };
23328
23329 _.formatDate = function(d) {
23330 // YYYY-MM-DDTHH:MM:SS in UTC
23331 function pad(n) {
23332 return n < 10 ? '0' + n : n;
23333 }
23334 return d.getUTCFullYear() + '-' +
23335 pad(d.getUTCMonth() + 1) + '-' +
23336 pad(d.getUTCDate()) + 'T' +
23337 pad(d.getUTCHours()) + ':' +
23338 pad(d.getUTCMinutes()) + ':' +
23339 pad(d.getUTCSeconds());
23340 };
23341
23342 _.strip_empty_properties = function(p) {
23343 var ret = {};
23344 _.each(p, function(v, k) {
23345 if (_.isString(v) && v.length > 0) {
23346 ret[k] = v;
23347 }
23348 });
23349 return ret;
23350 };
23351
23352 /*
23353 * this function returns a copy of object after truncating it. If
23354 * passed an Array or Object it will iterate through obj and
23355 * truncate all the values recursively.
23356 */
23357 _.truncate = function(obj, length) {
23358 var ret;
23359
23360 if (typeof(obj) === 'string') {
23361 ret = obj.slice(0, length);
23362 } else if (_.isArray(obj)) {
23363 ret = [];
23364 _.each(obj, function(val) {
23365 ret.push(_.truncate(val, length));
23366 });
23367 } else if (_.isObject(obj)) {
23368 ret = {};
23369 _.each(obj, function(val, key) {
23370 ret[key] = _.truncate(val, length);
23371 });
23372 } else {
23373 ret = obj;
23374 }
23375
23376 return ret;
23377 };
23378
23379 _.JSONEncode = (function() {
23380 return function(mixed_val) {
23381 var value = mixed_val;
23382 var quote = function(string) {
23383 var escapable = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // eslint-disable-line no-control-regex
23384 var meta = { // table of character substitutions
23385 '\b': '\\b',
23386 '\t': '\\t',
23387 '\n': '\\n',
23388 '\f': '\\f',
23389 '\r': '\\r',
23390 '"': '\\"',
23391 '\\': '\\\\'
23392 };
23393
23394 escapable.lastIndex = 0;
23395 return escapable.test(string) ?
23396 '"' + string.replace(escapable, function(a) {
23397 var c = meta[a];
23398 return typeof c === 'string' ? c :
23399 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
23400 }) + '"' :
23401 '"' + string + '"';
23402 };
23403
23404 var str = function(key, holder) {
23405 var gap = '';
23406 var indent = ' ';
23407 var i = 0; // The loop counter.
23408 var k = ''; // The member key.
23409 var v = ''; // The member value.
23410 var length = 0;
23411 var mind = gap;
23412 var partial = [];
23413 var value = holder[key];
23414
23415 // If the value has a toJSON method, call it to obtain a replacement value.
23416 if (value && typeof value === 'object' &&
23417 typeof value.toJSON === 'function') {
23418 value = value.toJSON(key);
23419 }
23420
23421 // What happens next depends on the value's type.
23422 switch (typeof value) {
23423 case 'string':
23424 return quote(value);
23425
23426 case 'number':
23427 // JSON numbers must be finite. Encode non-finite numbers as null.
23428 return isFinite(value) ? String(value) : 'null';
23429
23430 case 'boolean':
23431 case 'null':
23432 // If the value is a boolean or null, convert it to a string. Note:
23433 // typeof null does not produce 'null'. The case is included here in
23434 // the remote chance that this gets fixed someday.
23435
23436 return String(value);
23437
23438 case 'object':
23439 // If the type is 'object', we might be dealing with an object or an array or
23440 // null.
23441 // Due to a specification blunder in ECMAScript, typeof null is 'object',
23442 // so watch out for that case.
23443 if (!value) {
23444 return 'null';
23445 }
23446
23447 // Make an array to hold the partial results of stringifying this object value.
23448 gap += indent;
23449 partial = [];
23450
23451 // Is the value an array?
23452 if (toString.apply(value) === '[object Array]') {
23453 // The value is an array. Stringify every element. Use null as a placeholder
23454 // for non-JSON values.
23455
23456 length = value.length;
23457 for (i = 0; i < length; i += 1) {
23458 partial[i] = str(i, value) || 'null';
23459 }
23460
23461 // Join all of the elements together, separated with commas, and wrap them in
23462 // brackets.
23463 v = partial.length === 0 ? '[]' :
23464 gap ? '[\n' + gap +
23465 partial.join(',\n' + gap) + '\n' +
23466 mind + ']' :
23467 '[' + partial.join(',') + ']';
23468 gap = mind;
23469 return v;
23470 }
23471
23472 // Iterate through all of the keys in the object.
23473 for (k in value) {
23474 if (hasOwnProperty.call(value, k)) {
23475 v = str(k, value);
23476 if (v) {
23477 partial.push(quote(k) + (gap ? ': ' : ':') + v);
23478 }
23479 }
23480 }
23481
23482 // Join all of the member texts together, separated with commas,
23483 // and wrap them in braces.
23484 v = partial.length === 0 ? '{}' :
23485 gap ? '{' + partial.join(',') + '' +
23486 mind + '}' : '{' + partial.join(',') + '}';
23487 gap = mind;
23488 return v;
23489 }
23490 };
23491
23492 // Make a fake root object containing our value under the key of ''.
23493 // Return the result of stringifying the value.
23494 return str('', {
23495 '': value
23496 });
23497 };
23498 })();
23499
23500 /**
23501 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
23502 * Slightly modified to throw a real Error rather than a POJO
23503 */
23504 _.JSONDecode = (function() {
23505 var at, // The index of the current character
23506 ch, // The current character
23507 escapee = {
23508 '"': '"',
23509 '\\': '\\',
23510 '/': '/',
23511 'b': '\b',
23512 'f': '\f',
23513 'n': '\n',
23514 'r': '\r',
23515 't': '\t'
23516 },
23517 text,
23518 error = function(m) {
23519 var e = new SyntaxError(m);
23520 e.at = at;
23521 e.text = text;
23522 throw e;
23523 },
23524 next = function(c) {
23525 // If a c parameter is provided, verify that it matches the current character.
23526 if (c && c !== ch) {
23527 error('Expected \'' + c + '\' instead of \'' + ch + '\'');
23528 }
23529 // Get the next character. When there are no more characters,
23530 // return the empty string.
23531 ch = text.charAt(at);
23532 at += 1;
23533 return ch;
23534 },
23535 number = function() {
23536 // Parse a number value.
23537 var number,
23538 string = '';
23539
23540 if (ch === '-') {
23541 string = '-';
23542 next('-');
23543 }
23544 while (ch >= '0' && ch <= '9') {
23545 string += ch;
23546 next();
23547 }
23548 if (ch === '.') {
23549 string += '.';
23550 while (next() && ch >= '0' && ch <= '9') {
23551 string += ch;
23552 }
23553 }
23554 if (ch === 'e' || ch === 'E') {
23555 string += ch;
23556 next();
23557 if (ch === '-' || ch === '+') {
23558 string += ch;
23559 next();
23560 }
23561 while (ch >= '0' && ch <= '9') {
23562 string += ch;
23563 next();
23564 }
23565 }
23566 number = +string;
23567 if (!isFinite(number)) {
23568 error('Bad number');
23569 } else {
23570 return number;
23571 }
23572 },
23573
23574 string = function() {
23575 // Parse a string value.
23576 var hex,
23577 i,
23578 string = '',
23579 uffff;
23580 // When parsing for string values, we must look for " and \ characters.
23581 if (ch === '"') {
23582 while (next()) {
23583 if (ch === '"') {
23584 next();
23585 return string;
23586 }
23587 if (ch === '\\') {
23588 next();
23589 if (ch === 'u') {
23590 uffff = 0;
23591 for (i = 0; i < 4; i += 1) {
23592 hex = parseInt(next(), 16);
23593 if (!isFinite(hex)) {
23594 break;
23595 }
23596 uffff = uffff * 16 + hex;
23597 }
23598 string += String.fromCharCode(uffff);
23599 } else if (typeof escapee[ch] === 'string') {
23600 string += escapee[ch];
23601 } else {
23602 break;
23603 }
23604 } else {
23605 string += ch;
23606 }
23607 }
23608 }
23609 error('Bad string');
23610 },
23611 white = function() {
23612 // Skip whitespace.
23613 while (ch && ch <= ' ') {
23614 next();
23615 }
23616 },
23617 word = function() {
23618 // true, false, or null.
23619 switch (ch) {
23620 case 't':
23621 next('t');
23622 next('r');
23623 next('u');
23624 next('e');
23625 return true;
23626 case 'f':
23627 next('f');
23628 next('a');
23629 next('l');
23630 next('s');
23631 next('e');
23632 return false;
23633 case 'n':
23634 next('n');
23635 next('u');
23636 next('l');
23637 next('l');
23638 return null;
23639 }
23640 error('Unexpected "' + ch + '"');
23641 },
23642 value, // Placeholder for the value function.
23643 array = function() {
23644 // Parse an array value.
23645 var array = [];
23646
23647 if (ch === '[') {
23648 next('[');
23649 white();
23650 if (ch === ']') {
23651 next(']');
23652 return array; // empty array
23653 }
23654 while (ch) {
23655 array.push(value());
23656 white();
23657 if (ch === ']') {
23658 next(']');
23659 return array;
23660 }
23661 next(',');
23662 white();
23663 }
23664 }
23665 error('Bad array');
23666 },
23667 object = function() {
23668 // Parse an object value.
23669 var key,
23670 object = {};
23671
23672 if (ch === '{') {
23673 next('{');
23674 white();
23675 if (ch === '}') {
23676 next('}');
23677 return object; // empty object
23678 }
23679 while (ch) {
23680 key = string();
23681 white();
23682 next(':');
23683 if (Object.hasOwnProperty.call(object, key)) {
23684 error('Duplicate key "' + key + '"');
23685 }
23686 object[key] = value();
23687 white();
23688 if (ch === '}') {
23689 next('}');
23690 return object;
23691 }
23692 next(',');
23693 white();
23694 }
23695 }
23696 error('Bad object');
23697 };
23698
23699 value = function() {
23700 // Parse a JSON value. It could be an object, an array, a string,
23701 // a number, or a word.
23702 white();
23703 switch (ch) {
23704 case '{':
23705 return object();
23706 case '[':
23707 return array();
23708 case '"':
23709 return string();
23710 case '-':
23711 return number();
23712 default:
23713 return ch >= '0' && ch <= '9' ? number() : word();
23714 }
23715 };
23716
23717 // Return the json_parse function. It will have access to all of the
23718 // above functions and variables.
23719 return function(source) {
23720 var result;
23721
23722 text = source;
23723 at = 0;
23724 ch = ' ';
23725 result = value();
23726 white();
23727 if (ch) {
23728 error('Syntax error');
23729 }
23730
23731 return result;
23732 };
23733 })();
23734
23735 _.base64Encode = function(data) {
23736 var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
23737 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
23738 ac = 0,
23739 enc = '',
23740 tmp_arr = [];
23741
23742 if (!data) {
23743 return data;
23744 }
23745
23746 data = _.utf8Encode(data);
23747
23748 do { // pack three octets into four hexets
23749 o1 = data.charCodeAt(i++);
23750 o2 = data.charCodeAt(i++);
23751 o3 = data.charCodeAt(i++);
23752
23753 bits = o1 << 16 | o2 << 8 | o3;
23754
23755 h1 = bits >> 18 & 0x3f;
23756 h2 = bits >> 12 & 0x3f;
23757 h3 = bits >> 6 & 0x3f;
23758 h4 = bits & 0x3f;
23759
23760 // use hexets to index into b64, and append result to encoded string
23761 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
23762 } while (i < data.length);
23763
23764 enc = tmp_arr.join('');
23765
23766 switch (data.length % 3) {
23767 case 1:
23768 enc = enc.slice(0, -2) + '==';
23769 break;
23770 case 2:
23771 enc = enc.slice(0, -1) + '=';
23772 break;
23773 }
23774
23775 return enc;
23776 };
23777
23778 _.utf8Encode = function(string) {
23779 string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
23780
23781 var utftext = '',
23782 start,
23783 end;
23784 var stringl = 0,
23785 n;
23786
23787 start = end = 0;
23788 stringl = string.length;
23789
23790 for (n = 0; n < stringl; n++) {
23791 var c1 = string.charCodeAt(n);
23792 var enc = null;
23793
23794 if (c1 < 128) {
23795 end++;
23796 } else if ((c1 > 127) && (c1 < 2048)) {
23797 enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
23798 } else {
23799 enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
23800 }
23801 if (enc !== null) {
23802 if (end > start) {
23803 utftext += string.substring(start, end);
23804 }
23805 utftext += enc;
23806 start = end = n + 1;
23807 }
23808 }
23809
23810 if (end > start) {
23811 utftext += string.substring(start, string.length);
23812 }
23813
23814 return utftext;
23815 };
23816
23817 _.UUID = function() {
23818 try {
23819 // use native Crypto API when available
23820 return win['crypto']['randomUUID']();
23821 } catch (err) {
23822 // fall back to generating our own UUID
23823 // based on https://gist.github.com/scwood/3bff42cc005cc20ab7ec98f0d8e1d59d
23824 var uuid = new Array(36);
23825 for (var i = 0; i < 36; i++) {
23826 uuid[i] = Math.floor(Math.random() * 16);
23827 }
23828 uuid[14] = 4; // set bits 12-15 of time-high-and-version to 0100
23829 uuid[19] = uuid[19] &= -5; // set bit 6 of clock-seq-and-reserved to zero
23830 uuid[19] = uuid[19] |= (1 << 3); // set bit 7 of clock-seq-and-reserved to one
23831 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
23832
23833 return _.map(uuid, function(x) {
23834 return x.toString(16);
23835 }).join('');
23836 }
23837 };
23838
23839 // _.isBlockedUA()
23840 // This is to block various web spiders from executing our JS and
23841 // sending false tracking data
23842 var BLOCKED_UA_STRS = [
23843 'ahrefsbot',
23844 'ahrefssiteaudit',
23845 'amazonbot',
23846 'baiduspider',
23847 'bingbot',
23848 'bingpreview',
23849 'chrome-lighthouse',
23850 'facebookexternal',
23851 'petalbot',
23852 'pinterest',
23853 'screaming frog',
23854 'yahoo! slurp',
23855 'yandex',
23856
23857 // a whole bunch of goog-specific crawlers
23858 // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
23859 'adsbot-google',
23860 'apis-google',
23861 'duplexweb-google',
23862 'feedfetcher-google',
23863 'google favicon',
23864 'google web preview',
23865 'google-read-aloud',
23866 'googlebot',
23867 'googleweblight',
23868 'mediapartners-google',
23869 'storebot-google'
23870 ];
23871 _.isBlockedUA = function(ua) {
23872 var i;
23873 ua = ua.toLowerCase();
23874 for (i = 0; i < BLOCKED_UA_STRS.length; i++) {
23875 if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) {
23876 return true;
23877 }
23878 }
23879 return false;
23880 };
23881
23882 /**
23883 * @param {Object=} formdata
23884 * @param {string=} arg_separator
23885 */
23886 _.HTTPBuildQuery = function(formdata, arg_separator) {
23887 var use_val, use_key, tmp_arr = [];
23888
23889 if (_.isUndefined(arg_separator)) {
23890 arg_separator = '&';
23891 }
23892
23893 _.each(formdata, function(val, key) {
23894 use_val = encodeURIComponent(val.toString());
23895 use_key = encodeURIComponent(key);
23896 tmp_arr[tmp_arr.length] = use_key + '=' + use_val;
23897 });
23898
23899 return tmp_arr.join(arg_separator);
23900 };
23901
23902 _.getQueryParam = function(url, param) {
23903 // Expects a raw URL
23904
23905 param = param.replace(/[[]/g, '\\[').replace(/[\]]/g, '\\]');
23906 var regexS = '[\\?&]' + param + '=([^&#]*)',
23907 regex = new RegExp(regexS),
23908 results = regex.exec(url);
23909 if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {
23910 return '';
23911 } else {
23912 var result = results[1];
23913 try {
23914 result = decodeURIComponent(result);
23915 } catch(err) {
23916 console$1.error('Skipping decoding for malformed query param: ' + result);
23917 }
23918 return result.replace(/\+/g, ' ');
23919 }
23920 };
23921
23922
23923 // _.cookie
23924 // Methods partially borrowed from quirksmode.org/js/cookies.html
23925 _.cookie = {
23926 get: function(name) {
23927 var nameEQ = name + '=';
23928 var ca = document$1.cookie.split(';');
23929 for (var i = 0; i < ca.length; i++) {
23930 var c = ca[i];
23931 while (c.charAt(0) == ' ') {
23932 c = c.substring(1, c.length);
23933 }
23934 if (c.indexOf(nameEQ) === 0) {
23935 return decodeURIComponent(c.substring(nameEQ.length, c.length));
23936 }
23937 }
23938 return null;
23939 },
23940
23941 parse: function(name) {
23942 var cookie;
23943 try {
23944 cookie = _.JSONDecode(_.cookie.get(name)) || {};
23945 } catch (err) {
23946 // noop
23947 }
23948 return cookie;
23949 },
23950
23951 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
23952 var cdomain = '',
23953 expires = '',
23954 secure = '';
23955
23956 if (domain_override) {
23957 cdomain = '; domain=' + domain_override;
23958 } else if (is_cross_subdomain) {
23959 var domain = extract_domain(document$1.location.hostname);
23960 cdomain = domain ? '; domain=.' + domain : '';
23961 }
23962
23963 if (seconds) {
23964 var date = new Date();
23965 date.setTime(date.getTime() + (seconds * 1000));
23966 expires = '; expires=' + date.toGMTString();
23967 }
23968
23969 if (is_cross_site) {
23970 is_secure = true;
23971 secure = '; SameSite=None';
23972 }
23973 if (is_secure) {
23974 secure += '; secure';
23975 }
23976
23977 document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
23978 },
23979
23980 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
23981 var cdomain = '', expires = '', secure = '';
23982
23983 if (domain_override) {
23984 cdomain = '; domain=' + domain_override;
23985 } else if (is_cross_subdomain) {
23986 var domain = extract_domain(document$1.location.hostname);
23987 cdomain = domain ? '; domain=.' + domain : '';
23988 }
23989
23990 if (days) {
23991 var date = new Date();
23992 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
23993 expires = '; expires=' + date.toGMTString();
23994 }
23995
23996 if (is_cross_site) {
23997 is_secure = true;
23998 secure = '; SameSite=None';
23999 }
24000 if (is_secure) {
24001 secure += '; secure';
24002 }
24003
24004 var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
24005 document$1.cookie = new_cookie_val;
24006 return new_cookie_val;
24007 },
24008
24009 remove: function(name, is_cross_subdomain, domain_override) {
24010 _.cookie.set(name, '', -1, is_cross_subdomain, false, false, domain_override);
24011 }
24012 };
24013
24014 var _testStorageSupported = function (storage) {
24015 var supported = true;
24016 try {
24017 var key = '__mplss_' + cheap_guid(8),
24018 val = 'xyz';
24019 storage.setItem(key, val);
24020 if (storage.getItem(key) !== val) {
24021 supported = false;
24022 }
24023 storage.removeItem(key);
24024 } catch (err) {
24025 supported = false;
24026 }
24027 return supported;
24028 };
24029
24030 var _localStorageSupported = null;
24031 var localStorageSupported = function(storage, forceCheck) {
24032 if (_localStorageSupported !== null && !forceCheck) {
24033 return _localStorageSupported;
24034 }
24035 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
24036 };
24037
24038 var _sessionStorageSupported = null;
24039 var sessionStorageSupported = function(storage, forceCheck) {
24040 if (_sessionStorageSupported !== null && !forceCheck) {
24041 return _sessionStorageSupported;
24042 }
24043 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
24044 };
24045
24046 function _storageWrapper(storage, name, is_supported_fn) {
24047 var log_error = function(msg) {
24048 console$1.error(name + ' error: ' + msg);
24049 };
24050
24051 return {
24052 is_supported: function(forceCheck) {
24053 var supported = is_supported_fn(storage, forceCheck);
24054 if (!supported) {
24055 console$1.error(name + ' unsupported');
24056 }
24057 return supported;
24058 },
24059 error: log_error,
24060 get: function(key) {
24061 try {
24062 return storage.getItem(key);
24063 } catch (err) {
24064 log_error(err);
24065 }
24066 return null;
24067 },
24068 parse: function(key) {
24069 try {
24070 return _.JSONDecode(storage.getItem(key)) || {};
24071 } catch (err) {
24072 // noop
24073 }
24074 return null;
24075 },
24076 set: function(key, value) {
24077 try {
24078 storage.setItem(key, value);
24079 } catch (err) {
24080 log_error(err);
24081 }
24082 },
24083 remove: function(key) {
24084 try {
24085 storage.removeItem(key);
24086 } catch (err) {
24087 log_error(err);
24088 }
24089 }
24090 };
24091 }
24092
24093 _.localStorage = _storageWrapper(win.localStorage, 'localStorage', localStorageSupported);
24094 _.sessionStorage = _storageWrapper(win.sessionStorage, 'sessionStorage', sessionStorageSupported);
24095
24096 _.register_event = (function() {
24097 // written by Dean Edwards, 2005
24098 // with input from Tino Zijdel - crisp@xs4all.nl
24099 // with input from Carl Sverre - mail@carlsverre.com
24100 // with input from Mixpanel
24101 // http://dean.edwards.name/weblog/2005/10/add-event/
24102 // https://gist.github.com/1930440
24103
24104 /**
24105 * @param {Object} element
24106 * @param {string} type
24107 * @param {function(...*)} handler
24108 * @param {boolean=} oldSchool
24109 * @param {boolean=} useCapture
24110 */
24111 var register_event = function(element, type, handler, oldSchool, useCapture) {
24112 if (!element) {
24113 console$1.error('No valid element provided to register_event');
24114 return;
24115 }
24116
24117 if (element.addEventListener && !oldSchool) {
24118 element.addEventListener(type, handler, !!useCapture);
24119 } else {
24120 var ontype = 'on' + type;
24121 var old_handler = element[ontype]; // can be undefined
24122 element[ontype] = makeHandler(element, handler, old_handler);
24123 }
24124 };
24125
24126 function makeHandler(element, new_handler, old_handlers) {
24127 var handler = function(event) {
24128 event = event || fixEvent(win.event);
24129
24130 // this basically happens in firefox whenever another script
24131 // overwrites the onload callback and doesn't pass the event
24132 // object to previously defined callbacks. All the browsers
24133 // that don't define window.event implement addEventListener
24134 // so the dom_loaded handler will still be fired as usual.
24135 if (!event) {
24136 return undefined;
24137 }
24138
24139 var ret = true;
24140 var old_result, new_result;
24141
24142 if (_.isFunction(old_handlers)) {
24143 old_result = old_handlers(event);
24144 }
24145 new_result = new_handler.call(element, event);
24146
24147 if ((false === old_result) || (false === new_result)) {
24148 ret = false;
24149 }
24150
24151 return ret;
24152 };
24153
24154 return handler;
24155 }
24156
24157 function fixEvent(event) {
24158 if (event) {
24159 event.preventDefault = fixEvent.preventDefault;
24160 event.stopPropagation = fixEvent.stopPropagation;
24161 }
24162 return event;
24163 }
24164 fixEvent.preventDefault = function() {
24165 this.returnValue = false;
24166 };
24167 fixEvent.stopPropagation = function() {
24168 this.cancelBubble = true;
24169 };
24170
24171 return register_event;
24172 })();
24173
24174
24175 var TOKEN_MATCH_REGEX = new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');
24176
24177 _.dom_query = (function() {
24178 /* document.getElementsBySelector(selector)
24179 - returns an array of element objects from the current document
24180 matching the CSS selector. Selectors can contain element names,
24181 class names and ids and can be nested. For example:
24182
24183 elements = document.getElementsBySelector('div#main p a.external')
24184
24185 Will return an array of all 'a' elements with 'external' in their
24186 class attribute that are contained inside 'p' elements that are
24187 contained inside the 'div' element which has id="main"
24188
24189 New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
24190 See http://www.w3.org/TR/css3-selectors/#attribute-selectors
24191
24192 Version 0.4 - Simon Willison, March 25th 2003
24193 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
24194 -- Opera 7 fails
24195
24196 Version 0.5 - Carl Sverre, Jan 7th 2013
24197 -- Now uses jQuery-esque `hasClass` for testing class name
24198 equality. This fixes a bug related to '-' characters being
24199 considered not part of a 'word' in regex.
24200 */
24201
24202 function getAllChildren(e) {
24203 // Returns all children of element. Workaround required for IE5/Windows. Ugh.
24204 return e.all ? e.all : e.getElementsByTagName('*');
24205 }
24206
24207 var bad_whitespace = /[\t\r\n]/g;
24208
24209 function hasClass(elem, selector) {
24210 var className = ' ' + selector + ' ';
24211 return ((' ' + elem.className + ' ').replace(bad_whitespace, ' ').indexOf(className) >= 0);
24212 }
24213
24214 function getElementsBySelector(selector) {
24215 // Attempt to fail gracefully in lesser browsers
24216 if (!document$1.getElementsByTagName) {
24217 return [];
24218 }
24219 // Split selector in to tokens
24220 var tokens = selector.split(' ');
24221 var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;
24222 var currentContext = [document$1];
24223 for (i = 0; i < tokens.length; i++) {
24224 token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
24225 if (token.indexOf('#') > -1) {
24226 // Token is an ID selector
24227 bits = token.split('#');
24228 tagName = bits[0];
24229 var id = bits[1];
24230 var element = document$1.getElementById(id);
24231 if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
24232 // element not found or tag with that ID not found, return false
24233 return [];
24234 }
24235 // Set currentContext to contain just this element
24236 currentContext = [element];
24237 continue; // Skip to next token
24238 }
24239 if (token.indexOf('.') > -1) {
24240 // Token contains a class selector
24241 bits = token.split('.');
24242 tagName = bits[0];
24243 var className = bits[1];
24244 if (!tagName) {
24245 tagName = '*';
24246 }
24247 // Get elements matching tag, filter them for class selector
24248 found = [];
24249 foundCount = 0;
24250 for (j = 0; j < currentContext.length; j++) {
24251 if (tagName == '*') {
24252 elements = getAllChildren(currentContext[j]);
24253 } else {
24254 elements = currentContext[j].getElementsByTagName(tagName);
24255 }
24256 for (k = 0; k < elements.length; k++) {
24257 found[foundCount++] = elements[k];
24258 }
24259 }
24260 currentContext = [];
24261 currentContextIndex = 0;
24262 for (j = 0; j < found.length; j++) {
24263 if (found[j].className &&
24264 _.isString(found[j].className) && // some SVG elements have classNames which are not strings
24265 hasClass(found[j], className)
24266 ) {
24267 currentContext[currentContextIndex++] = found[j];
24268 }
24269 }
24270 continue; // Skip to next token
24271 }
24272 // Code to deal with attribute selectors
24273 var token_match = token.match(TOKEN_MATCH_REGEX);
24274 if (token_match) {
24275 tagName = token_match[1];
24276 var attrName = token_match[2];
24277 var attrOperator = token_match[3];
24278 var attrValue = token_match[4];
24279 if (!tagName) {
24280 tagName = '*';
24281 }
24282 // Grab all of the tagName elements within current context
24283 found = [];
24284 foundCount = 0;
24285 for (j = 0; j < currentContext.length; j++) {
24286 if (tagName == '*') {
24287 elements = getAllChildren(currentContext[j]);
24288 } else {
24289 elements = currentContext[j].getElementsByTagName(tagName);
24290 }
24291 for (k = 0; k < elements.length; k++) {
24292 found[foundCount++] = elements[k];
24293 }
24294 }
24295 currentContext = [];
24296 currentContextIndex = 0;
24297 var checkFunction; // This function will be used to filter the elements
24298 switch (attrOperator) {
24299 case '=': // Equality
24300 checkFunction = function(e) {
24301 return (e.getAttribute(attrName) == attrValue);
24302 };
24303 break;
24304 case '~': // Match one of space seperated words
24305 checkFunction = function(e) {
24306 return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
24307 };
24308 break;
24309 case '|': // Match start with value followed by optional hyphen
24310 checkFunction = function(e) {
24311 return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
24312 };
24313 break;
24314 case '^': // Match starts with value
24315 checkFunction = function(e) {
24316 return (e.getAttribute(attrName).indexOf(attrValue) === 0);
24317 };
24318 break;
24319 case '$': // Match ends with value - fails with "Warning" in Opera 7
24320 checkFunction = function(e) {
24321 return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
24322 };
24323 break;
24324 case '*': // Match ends with value
24325 checkFunction = function(e) {
24326 return (e.getAttribute(attrName).indexOf(attrValue) > -1);
24327 };
24328 break;
24329 default:
24330 // Just test for existence of attribute
24331 checkFunction = function(e) {
24332 return e.getAttribute(attrName);
24333 };
24334 }
24335 currentContext = [];
24336 currentContextIndex = 0;
24337 for (j = 0; j < found.length; j++) {
24338 if (checkFunction(found[j])) {
24339 currentContext[currentContextIndex++] = found[j];
24340 }
24341 }
24342 // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
24343 continue; // Skip to next token
24344 }
24345 // If we get here, token is JUST an element (not a class or ID selector)
24346 tagName = token;
24347 found = [];
24348 foundCount = 0;
24349 for (j = 0; j < currentContext.length; j++) {
24350 elements = currentContext[j].getElementsByTagName(tagName);
24351 for (k = 0; k < elements.length; k++) {
24352 found[foundCount++] = elements[k];
24353 }
24354 }
24355 currentContext = found;
24356 }
24357 return currentContext;
24358 }
24359
24360 return function(query) {
24361 if (_.isElement(query)) {
24362 return [query];
24363 } else if (_.isObject(query) && !_.isUndefined(query.length)) {
24364 return query;
24365 } else {
24366 return getElementsBySelector.call(this, query);
24367 }
24368 };
24369 })();
24370
24371 var CAMPAIGN_KEYWORDS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'utm_id', 'utm_source_platform','utm_campaign_id', 'utm_creative_format', 'utm_marketing_tactic'];
24372 var CLICK_IDS = ['dclid', 'fbclid', 'gclid', 'ko_click_id', 'li_fat_id', 'msclkid', 'sccid', 'ttclid', 'twclid', 'wbraid'];
24373
24374 _.info = {
24375 campaignParams: function(default_value) {
24376 var kw = '',
24377 params = {};
24378 _.each(CAMPAIGN_KEYWORDS, function(kwkey) {
24379 kw = _.getQueryParam(document$1.URL, kwkey);
24380 if (kw.length) {
24381 params[kwkey] = kw;
24382 } else if (default_value !== undefined) {
24383 params[kwkey] = default_value;
24384 }
24385 });
24386
24387 return params;
24388 },
24389
24390 clickParams: function() {
24391 var id = '',
24392 params = {};
24393 _.each(CLICK_IDS, function(idkey) {
24394 id = _.getQueryParam(document$1.URL, idkey);
24395 if (id.length) {
24396 params[idkey] = id;
24397 }
24398 });
24399
24400 return params;
24401 },
24402
24403 marketingParams: function() {
24404 return _.extend(_.info.campaignParams(), _.info.clickParams());
24405 },
24406
24407 searchEngine: function(referrer) {
24408 if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
24409 return 'google';
24410 } else if (referrer.search('https?://(.*)bing.com') === 0) {
24411 return 'bing';
24412 } else if (referrer.search('https?://(.*)yahoo.com') === 0) {
24413 return 'yahoo';
24414 } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
24415 return 'duckduckgo';
24416 } else {
24417 return null;
24418 }
24419 },
24420
24421 searchInfo: function(referrer) {
24422 var search = _.info.searchEngine(referrer),
24423 param = (search != 'yahoo') ? 'q' : 'p',
24424 ret = {};
24425
24426 if (search !== null) {
24427 ret['$search_engine'] = search;
24428
24429 var keyword = _.getQueryParam(referrer, param);
24430 if (keyword.length) {
24431 ret['mp_keyword'] = keyword;
24432 }
24433 }
24434
24435 return ret;
24436 },
24437
24438 /**
24439 * This function detects which browser is running this script.
24440 * The order of the checks are important since many user agents
24441 * include key words used in later checks.
24442 */
24443 browser: function(user_agent, vendor, opera) {
24444 vendor = vendor || ''; // vendor is undefined for at least IE9
24445 if (opera || _.includes(user_agent, ' OPR/')) {
24446 if (_.includes(user_agent, 'Mini')) {
24447 return 'Opera Mini';
24448 }
24449 return 'Opera';
24450 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
24451 return 'BlackBerry';
24452 } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {
24453 return 'Internet Explorer Mobile';
24454 } else if (_.includes(user_agent, 'SamsungBrowser/')) {
24455 // https://developer.samsung.com/internet/user-agent-string-format
24456 return 'Samsung Internet';
24457 } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {
24458 return 'Microsoft Edge';
24459 } else if (_.includes(user_agent, 'FBIOS')) {
24460 return 'Facebook Mobile';
24461 } else if (_.includes(user_agent, 'Whale/')) {
24462 // https://user-agents.net/browsers/whale-browser
24463 return 'Whale Browser';
24464 } else if (_.includes(user_agent, 'Chrome')) {
24465 return 'Chrome';
24466 } else if (_.includes(user_agent, 'CriOS')) {
24467 return 'Chrome iOS';
24468 } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {
24469 return 'UC Browser';
24470 } else if (_.includes(user_agent, 'FxiOS')) {
24471 return 'Firefox iOS';
24472 } else if (_.includes(vendor, 'Apple')) {
24473 if (_.includes(user_agent, 'Mobile')) {
24474 return 'Mobile Safari';
24475 }
24476 return 'Safari';
24477 } else if (_.includes(user_agent, 'Android')) {
24478 return 'Android Mobile';
24479 } else if (_.includes(user_agent, 'Konqueror')) {
24480 return 'Konqueror';
24481 } else if (_.includes(user_agent, 'Firefox')) {
24482 return 'Firefox';
24483 } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {
24484 return 'Internet Explorer';
24485 } else if (_.includes(user_agent, 'Gecko')) {
24486 return 'Mozilla';
24487 } else {
24488 return '';
24489 }
24490 },
24491
24492 /**
24493 * This function detects which browser version is running this script,
24494 * parsing major and minor version (e.g., 42.1). User agent strings from:
24495 * http://www.useragentstring.com/pages/useragentstring.php
24496 */
24497 browserVersion: function(userAgent, vendor, opera) {
24498 var browser = _.info.browser(userAgent, vendor, opera);
24499 var versionRegexs = {
24500 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
24501 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
24502 'Chrome': /Chrome\/(\d+(\.\d+)?)/,
24503 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
24504 'UC Browser' : /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
24505 'Safari': /Version\/(\d+(\.\d+)?)/,
24506 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
24507 'Opera': /(Opera|OPR)\/(\d+(\.\d+)?)/,
24508 'Firefox': /Firefox\/(\d+(\.\d+)?)/,
24509 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
24510 'Konqueror': /Konqueror:(\d+(\.\d+)?)/,
24511 'BlackBerry': /BlackBerry (\d+(\.\d+)?)/,
24512 'Android Mobile': /android\s(\d+(\.\d+)?)/,
24513 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
24514 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
24515 'Mozilla': /rv:(\d+(\.\d+)?)/,
24516 'Whale Browser': /Whale\/(\d+(\.\d+)?)/
24517 };
24518 var regex = versionRegexs[browser];
24519 if (regex === undefined) {
24520 return null;
24521 }
24522 var matches = userAgent.match(regex);
24523 if (!matches) {
24524 return null;
24525 }
24526 return parseFloat(matches[matches.length - 2]);
24527 },
24528
24529 os: function() {
24530 var a = userAgent;
24531 if (/Windows/i.test(a)) {
24532 if (/Phone/.test(a) || /WPDesktop/.test(a)) {
24533 return 'Windows Phone';
24534 }
24535 return 'Windows';
24536 } else if (/(iPhone|iPad|iPod)/.test(a)) {
24537 return 'iOS';
24538 } else if (/Android/.test(a)) {
24539 return 'Android';
24540 } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
24541 return 'BlackBerry';
24542 } else if (/Mac/i.test(a)) {
24543 return 'Mac OS X';
24544 } else if (/Linux/.test(a)) {
24545 return 'Linux';
24546 } else if (/CrOS/.test(a)) {
24547 return 'Chrome OS';
24548 } else {
24549 return '';
24550 }
24551 },
24552
24553 device: function(user_agent) {
24554 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {
24555 return 'Windows Phone';
24556 } else if (/iPad/.test(user_agent)) {
24557 return 'iPad';
24558 } else if (/iPod/.test(user_agent)) {
24559 return 'iPod Touch';
24560 } else if (/iPhone/.test(user_agent)) {
24561 return 'iPhone';
24562 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
24563 return 'BlackBerry';
24564 } else if (/Android/.test(user_agent)) {
24565 return 'Android';
24566 } else {
24567 return '';
24568 }
24569 },
24570
24571 referringDomain: function(referrer) {
24572 var split = referrer.split('/');
24573 if (split.length >= 3) {
24574 return split[2];
24575 }
24576 return '';
24577 },
24578
24579 currentUrl: function() {
24580 return win.location.href;
24581 },
24582
24583 properties: function(extra_props) {
24584 if (typeof extra_props !== 'object') {
24585 extra_props = {};
24586 }
24587 return _.extend(_.strip_empty_properties({
24588 '$os': _.info.os(),
24589 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
24590 '$referrer': document$1.referrer,
24591 '$referring_domain': _.info.referringDomain(document$1.referrer),
24592 '$device': _.info.device(userAgent)
24593 }), {
24594 '$current_url': _.info.currentUrl(),
24595 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera),
24596 '$screen_height': screen.height,
24597 '$screen_width': screen.width,
24598 'mp_lib': 'web',
24599 '$lib_version': Config.LIB_VERSION,
24600 '$insert_id': cheap_guid(),
24601 'time': _.timestamp() / 1000 // epoch time in seconds
24602 }, _.strip_empty_properties(extra_props));
24603 },
24604
24605 people_properties: function() {
24606 return _.extend(_.strip_empty_properties({
24607 '$os': _.info.os(),
24608 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera)
24609 }), {
24610 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera)
24611 });
24612 },
24613
24614 mpPageViewProperties: function() {
24615 return _.strip_empty_properties({
24616 'current_page_title': document$1.title,
24617 'current_domain': win.location.hostname,
24618 'current_url_path': win.location.pathname,
24619 'current_url_protocol': win.location.protocol,
24620 'current_url_search': win.location.search
24621 });
24622 }
24623 };
24624
24625 /**
24626 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
24627 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
24628 */
24629 var batchedThrottle = function (fn, waitMs) {
24630 var timeoutPromise = null;
24631 var throttledItems = [];
24632 return function (item) {
24633 var self = this;
24634 throttledItems.push(item);
24635
24636 if (!timeoutPromise) {
24637 timeoutPromise = new PromisePolyfill(function (resolve) {
24638 setTimeout(function () {
24639 var returnValue = fn.apply(self, [throttledItems]);
24640 timeoutPromise = null;
24641 throttledItems = [];
24642 resolve(returnValue);
24643 }, waitMs);
24644 });
24645 }
24646 return timeoutPromise;
24647 };
24648 };
24649
24650 var cheap_guid = function(maxlen) {
24651 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
24652 return maxlen ? guid.substring(0, maxlen) : guid;
24653 };
24654
24655 /**
24656 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
24657 * https://www.w3.org/TR/trace-context/#traceparent-header
24658 */
24659 var generateTraceparent = function() {
24660 var traceID = _.UUID().replace(/-/g, '');
24661 var parentID = _.UUID().replace(/-/g, '').substring(0, 16);
24662
24663 // Sampled trace
24664 var traceFlags = '01';
24665
24666 return '00-' + traceID + '-' + parentID + '-' + traceFlags;
24667 };
24668
24669 // naive way to extract domain name (example.com) from full hostname (my.sub.example.com)
24670 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
24671 // this next one attempts to account for some ccSLDs, e.g. extracting oxford.ac.uk from www.oxford.ac.uk
24672 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
24673 /**
24674 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
24675 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
24676 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
24677 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
24678 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
24679 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
24680 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
24681 * offers the 'cookie_domain' config option to set it explicitly.
24682 * @example
24683 * extract_domain('my.sub.example.com')
24684 * // 'example.com'
24685 */
24686 var extract_domain = function(hostname) {
24687 var domain_regex = DOMAIN_MATCH_REGEX;
24688 var parts = hostname.split('.');
24689 var tld = parts[parts.length - 1];
24690 if (tld.length > 4 || tld === 'com' || tld === 'org') {
24691 domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
24692 }
24693 var matches = hostname.match(domain_regex);
24694 return matches ? matches[0] : '';
24695 };
24696
24697 /**
24698 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
24699 * @returns {boolean}
24700 */
24701 var isOnline = function() {
24702 var onLine = win.navigator['onLine'];
24703 return _.isUndefined(onLine) || onLine;
24704 };
24705
24706 var NOOP_FUNC = function () {};
24707
24708 var JSONStringify = null, JSONParse = null;
24709 if (typeof JSON !== 'undefined') {
24710 JSONStringify = JSON.stringify;
24711 JSONParse = JSON.parse;
24712 }
24713 JSONStringify = JSONStringify || _.JSONEncode;
24714 JSONParse = JSONParse || _.JSONDecode;
24715
24716 // UNMINIFIED EXPORTS (for closure compiler)
24717 _['info'] = _.info;
24718 _['info']['browser'] = _.info.browser;
24719 _['info']['browserVersion'] = _.info.browserVersion;
24720 _['info']['device'] = _.info.device;
24721 _['info']['properties'] = _.info.properties;
24722 _['isBlockedUA'] = _.isBlockedUA;
24723 _['isEmptyObject'] = _.isEmptyObject;
24724 _['isObject'] = _.isObject;
24725 _['JSONDecode'] = _.JSONDecode;
24726 _['JSONEncode'] = _.JSONEncode;
24727 _['toArray'] = _.toArray;
24728 _['NPO'] = NpoPromise;
24729
24730 var MIXPANEL_DB_NAME = 'mixpanelBrowserDb';
24731
24732 var RECORDING_EVENTS_STORE_NAME = 'mixpanelRecordingEvents';
24733 var RECORDING_REGISTRY_STORE_NAME = 'mixpanelRecordingRegistry';
24734
24735 // note: increment the version number when adding new object stores
24736 var DB_VERSION = 1;
24737 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
24738
24739 /**
24740 * @type {import('./wrapper').StorageWrapper}
24741 */
24742 var IDBStorageWrapper = function (storeName) {
24743 /**
24744 * @type {Promise<IDBDatabase>|null}
24745 */
24746 this.dbPromise = null;
24747 this.storeName = storeName;
24748 };
24749
24750 IDBStorageWrapper.prototype._openDb = function () {
24751 return new PromisePolyfill(function (resolve, reject) {
24752 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
24753 openRequest['onerror'] = function () {
24754 reject(openRequest.error);
24755 };
24756
24757 openRequest['onsuccess'] = function () {
24758 resolve(openRequest.result);
24759 };
24760
24761 openRequest['onupgradeneeded'] = function (ev) {
24762 var db = ev.target.result;
24763
24764 OBJECT_STORES.forEach(function (storeName) {
24765 db.createObjectStore(storeName);
24766 });
24767 };
24768 });
24769 };
24770
24771 IDBStorageWrapper.prototype.init = function () {
24772 if (!win.indexedDB) {
24773 return PromisePolyfill.reject('indexedDB is not supported in this browser');
24774 }
24775
24776 if (!this.dbPromise) {
24777 this.dbPromise = this._openDb();
24778 }
24779
24780 return this.dbPromise
24781 .then(function (dbOrError) {
24782 if (dbOrError instanceof win['IDBDatabase']) {
24783 return PromisePolyfill.resolve();
24784 } else {
24785 return PromisePolyfill.reject(dbOrError);
24786 }
24787 });
24788 };
24789
24790 IDBStorageWrapper.prototype.isInitialized = function () {
24791 return !!this.dbPromise;
24792 };
24793
24794 /**
24795 * @param {IDBTransactionMode} mode
24796 * @param {function(IDBObjectStore): void} storeCb
24797 */
24798 IDBStorageWrapper.prototype.makeTransaction = function (mode, storeCb) {
24799 var storeName = this.storeName;
24800 var doTransaction = function (db) {
24801 return new PromisePolyfill(function (resolve, reject) {
24802 var transaction = db.transaction(storeName, mode);
24803 transaction.oncomplete = function () {
24804 resolve(transaction);
24805 };
24806 transaction.onabort = transaction.onerror = function () {
24807 reject(transaction.error);
24808 };
24809
24810 storeCb(transaction.objectStore(storeName));
24811 });
24812 };
24813
24814 return this.dbPromise
24815 .then(doTransaction)
24816 .catch(function (err) {
24817 if (err && err['name'] === 'InvalidStateError') {
24818 // try reopening the DB if the connection is closed
24819 this.dbPromise = this._openDb();
24820 return this.dbPromise.then(doTransaction);
24821 } else {
24822 return PromisePolyfill.reject(err);
24823 }
24824 }.bind(this));
24825 };
24826
24827 IDBStorageWrapper.prototype.setItem = function (key, value) {
24828 return this.makeTransaction('readwrite', function (objectStore) {
24829 objectStore.put(value, key);
24830 });
24831 };
24832
24833 IDBStorageWrapper.prototype.getItem = function (key) {
24834 var req;
24835 return this.makeTransaction('readonly', function (objectStore) {
24836 req = objectStore.get(key);
24837 }).then(function () {
24838 return req.result;
24839 });
24840 };
24841
24842 IDBStorageWrapper.prototype.removeItem = function (key) {
24843 return this.makeTransaction('readwrite', function (objectStore) {
24844 objectStore.delete(key);
24845 });
24846 };
24847
24848 IDBStorageWrapper.prototype.getAll = function () {
24849 var req;
24850 return this.makeTransaction('readonly', function (objectStore) {
24851 req = objectStore.getAll();
24852 }).then(function () {
24853 return req.result;
24854 });
24855 };
24856
24857 /**
24858 * GDPR utils
24859 *
24860 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
24861 * and privacy for all individuals within the European Union. It addresses the export of personal
24862 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
24863 * over their personal data and to simplify the regulatory environment for international business
24864 * by unifying the regulation within the EU.
24865 *
24866 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
24867 * These functions are used internally by the SDK and are not intended to be publicly exposed.
24868 */
24869
24870
24871 /**
24872 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
24873 * @callback trackFunction
24874 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
24875 * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
24876 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
24877 */
24878
24879 /** Public **/
24880
24881 var GDPR_DEFAULT_PERSISTENCE_PREFIX = '__mp_opt_in_out_';
24882
24883 /**
24884 * Opt the user in to data tracking and cookies/localstorage for the given token
24885 * @param {string} token - Mixpanel project tracking token
24886 * @param {Object} [options]
24887 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
24888 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
24889 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
24890 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24891 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24892 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
24893 * @param {string} [options.cookieDomain] - custom cookie domain
24894 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24895 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
24896 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
24897 */
24898 function optIn(token, options) {
24899 _optInOut(true, token, options);
24900 }
24901
24902 /**
24903 * Opt the user out of data tracking and cookies/localstorage for the given token
24904 * @param {string} token - Mixpanel project tracking token
24905 * @param {Object} [options]
24906 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24907 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24908 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
24909 * @param {string} [options.cookieDomain] - custom cookie domain
24910 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24911 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
24912 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
24913 */
24914 function optOut(token, options) {
24915 _optInOut(false, token, options);
24916 }
24917
24918 /**
24919 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
24920 * @param {string} token - Mixpanel project tracking token
24921 * @param {Object} [options]
24922 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24923 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24924 * @returns {boolean} whether the user has opted in to the given opt type
24925 */
24926 function hasOptedIn(token, options) {
24927 return _getStorageValue(token, options) === '1';
24928 }
24929
24930 /**
24931 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
24932 * @param {string} token - Mixpanel project tracking token
24933 * @param {Object} [options]
24934 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24935 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24936 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
24937 * @returns {boolean} whether the user has opted out of the given opt type
24938 */
24939 function hasOptedOut(token, options) {
24940 if (_hasDoNotTrackFlagOn(options)) {
24941 console$1.warn('This browser has "Do Not Track" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the "Do Not Track" browser setting, initialize the Mixpanel instance with the config "ignore_dnt: true"');
24942 return true;
24943 }
24944 var optedOut = _getStorageValue(token, options) === '0';
24945 if (optedOut) {
24946 console$1.warn('You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.');
24947 }
24948 return optedOut;
24949 }
24950
24951 /**
24952 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24953 * If the user has opted out, return early instead of executing the method.
24954 * If a callback argument was provided, execute it passing the 0 error code.
24955 * @param {function} method - wrapped method to be executed if the user has not opted out
24956 * @returns {*} the result of executing method OR undefined if the user has opted out
24957 */
24958 function addOptOutCheckMixpanelLib(method) {
24959 return _addOptOutCheck(method, function(name) {
24960 return this.get_config(name);
24961 });
24962 }
24963
24964 /**
24965 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24966 * If the user has opted out, return early instead of executing the method.
24967 * If a callback argument was provided, execute it passing the 0 error code.
24968 * @param {function} method - wrapped method to be executed if the user has not opted out
24969 * @returns {*} the result of executing method OR undefined if the user has opted out
24970 */
24971 function addOptOutCheckMixpanelPeople(method) {
24972 return _addOptOutCheck(method, function(name) {
24973 return this._get_config(name);
24974 });
24975 }
24976
24977 /**
24978 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24979 * If the user has opted out, return early instead of executing the method.
24980 * If a callback argument was provided, execute it passing the 0 error code.
24981 * @param {function} method - wrapped method to be executed if the user has not opted out
24982 * @returns {*} the result of executing method OR undefined if the user has opted out
24983 */
24984 function addOptOutCheckMixpanelGroup(method) {
24985 return _addOptOutCheck(method, function(name) {
24986 return this._get_config(name);
24987 });
24988 }
24989
24990 /**
24991 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
24992 * @param {string} token - Mixpanel project tracking token
24993 * @param {Object} [options]
24994 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24995 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24996 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
24997 * @param {string} [options.cookieDomain] - custom cookie domain
24998 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24999 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
25000 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
25001 */
25002 function clearOptInOut(token, options) {
25003 options = options || {};
25004 _getStorage(options).remove(
25005 _getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain
25006 );
25007 }
25008
25009 /** Private **/
25010
25011 /**
25012 * Get storage util
25013 * @param {Object} [options]
25014 * @param {string} [options.persistenceType]
25015 * @returns {object} either _.cookie or _.localstorage
25016 */
25017 function _getStorage(options) {
25018 options = options || {};
25019 return options.persistenceType === 'localStorage' ? _.localStorage : _.cookie;
25020 }
25021
25022 /**
25023 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
25024 * @param {string} token - Mixpanel project tracking token
25025 * @param {Object} [options]
25026 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25027 * @returns {string} the name of the cookie for the given opt type
25028 */
25029 function _getStorageKey(token, options) {
25030 options = options || {};
25031 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
25032 }
25033
25034 /**
25035 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
25036 * @param {string} token - Mixpanel project tracking token
25037 * @param {Object} [options]
25038 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25039 * @returns {string} the value of the cookie for the given opt type
25040 */
25041 function _getStorageValue(token, options) {
25042 return _getStorage(options).get(_getStorageKey(token, options));
25043 }
25044
25045 /**
25046 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
25047 * @param {Object} [options]
25048 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
25049 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
25050 * @returns {boolean} whether the DNT setting is true
25051 */
25052 function _hasDoNotTrackFlagOn(options) {
25053 if (options && options.ignoreDnt) {
25054 return false;
25055 }
25056 var win$1 = (options && options.window) || win;
25057 var nav = win$1['navigator'] || {};
25058 var hasDntOn = false;
25059
25060 _.each([
25061 nav['doNotTrack'], // standard
25062 nav['msDoNotTrack'],
25063 win$1['doNotTrack']
25064 ], function(dntValue) {
25065 if (_.includes([true, 1, '1', 'yes'], dntValue)) {
25066 hasDntOn = true;
25067 }
25068 });
25069
25070 return hasDntOn;
25071 }
25072
25073 /**
25074 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
25075 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
25076 * @param {string} token - Mixpanel project tracking token
25077 * @param {Object} [options]
25078 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
25079 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
25080 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
25081 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25082 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
25083 * @param {string} [options.cookieDomain] - custom cookie domain
25084 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
25085 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
25086 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
25087 */
25088 function _optInOut(optValue, token, options) {
25089 if (!_.isString(token) || !token.length) {
25090 console$1.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
25091 return;
25092 }
25093
25094 options = options || {};
25095
25096 _getStorage(options).set(
25097 _getStorageKey(token, options),
25098 optValue ? 1 : 0,
25099 _.isNumber(options.cookieExpiration) ? options.cookieExpiration : null,
25100 !!options.crossSubdomainCookie,
25101 !!options.secureCookie,
25102 !!options.crossSiteCookie,
25103 options.cookieDomain
25104 );
25105
25106 if (options.track && optValue) { // only track event if opting in (optValue=true)
25107 options.track(options.trackEventName || '$opt_in', options.trackProperties, {
25108 'send_immediately': true
25109 });
25110 }
25111 }
25112
25113 /**
25114 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
25115 * If the user has opted out, return early instead of executing the method.
25116 * If a callback argument was provided, execute it passing the 0 error code.
25117 * @param {function} method - wrapped method to be executed if the user has not opted out
25118 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
25119 * @returns {*} the result of executing method OR undefined if the user has opted out
25120 */
25121 function _addOptOutCheck(method, getConfigValue) {
25122 return function() {
25123 var optedOut = false;
25124
25125 try {
25126 var token = getConfigValue.call(this, 'token');
25127 var ignoreDnt = getConfigValue.call(this, 'ignore_dnt');
25128 var persistenceType = getConfigValue.call(this, 'opt_out_tracking_persistence_type');
25129 var persistencePrefix = getConfigValue.call(this, 'opt_out_tracking_cookie_prefix');
25130 var win = getConfigValue.call(this, 'window'); // used to override window during browser tests
25131
25132 if (token) { // if there was an issue getting the token, continue method execution as normal
25133 optedOut = hasOptedOut(token, {
25134 ignoreDnt: ignoreDnt,
25135 persistenceType: persistenceType,
25136 persistencePrefix: persistencePrefix,
25137 window: win
25138 });
25139 }
25140 } catch(err) {
25141 console$1.error('Unexpected error when checking tracking opt-out status: ' + err);
25142 }
25143
25144 if (!optedOut) {
25145 return method.apply(this, arguments);
25146 }
25147
25148 var callback = arguments[arguments.length - 1];
25149 if (typeof(callback) === 'function') {
25150 callback(0);
25151 }
25152
25153 return;
25154 };
25155 }
25156
25157 var logger$6 = console_with_prefix('lock');
25158
25159 /**
25160 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
25161 * window/tab at a time will be able to access shared resources.
25162 *
25163 * Based on the Alur and Taubenfeld fast lock
25164 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
25165 * with an added timeout to ensure there will be eventual progress in the event
25166 * that a window is closed in the middle of the callback.
25167 *
25168 * Implementation based on the original version by David Wolever (https://github.com/wolever)
25169 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
25170 *
25171 * @example
25172 * const myLock = new SharedLock('some-key');
25173 * myLock.withLock(function() {
25174 * console.log('I hold the mutex!');
25175 * });
25176 *
25177 * @constructor
25178 */
25179 var SharedLock = function(key, options) {
25180 options = options || {};
25181
25182 this.storageKey = key;
25183 this.storage = options.storage || win.localStorage;
25184 this.pollIntervalMS = options.pollIntervalMS || 100;
25185 this.timeoutMS = options.timeoutMS || 2000;
25186
25187 // dependency-inject promise implementation for testing purposes
25188 this.promiseImpl = options.promiseImpl || PromisePolyfill;
25189 };
25190
25191 // pass in a specific pid to test contention scenarios; otherwise
25192 // it is chosen randomly for each acquisition attempt
25193 SharedLock.prototype.withLock = function(lockedCB, pid) {
25194 var Promise = this.promiseImpl;
25195 return new Promise(_.bind(function (resolve, reject) {
25196 var i = pid || (new Date().getTime() + '|' + Math.random());
25197 var startTime = new Date().getTime();
25198 var key = this.storageKey;
25199 var pollIntervalMS = this.pollIntervalMS;
25200 var timeoutMS = this.timeoutMS;
25201 var storage = this.storage;
25202
25203 var keyX = key + ':X';
25204 var keyY = key + ':Y';
25205 var keyZ = key + ':Z';
25206
25207 var delay = function(cb) {
25208 if (new Date().getTime() - startTime > timeoutMS) {
25209 logger$6.error('Timeout waiting for mutex on ' + key + '; clearing lock. [' + i + ']');
25210 storage.removeItem(keyZ);
25211 storage.removeItem(keyY);
25212 loop();
25213 return;
25214 }
25215 setTimeout(function() {
25216 try {
25217 cb();
25218 } catch(err) {
25219 reject(err);
25220 }
25221 }, pollIntervalMS * (Math.random() + 0.1));
25222 };
25223
25224 var waitFor = function(predicate, cb) {
25225 if (predicate()) {
25226 cb();
25227 } else {
25228 delay(function() {
25229 waitFor(predicate, cb);
25230 });
25231 }
25232 };
25233
25234 var getSetY = function() {
25235 var valY = storage.getItem(keyY);
25236 if (valY && valY !== i) { // if Y == i then this process already has the lock (useful for test cases)
25237 return false;
25238 } else {
25239 storage.setItem(keyY, i);
25240 if (storage.getItem(keyY) === i) {
25241 return true;
25242 } else {
25243 if (!localStorageSupported(storage, true)) {
25244 reject(new Error('localStorage support dropped while acquiring lock'));
25245 }
25246 return false;
25247 }
25248 }
25249 };
25250
25251 var loop = function() {
25252 storage.setItem(keyX, i);
25253
25254 waitFor(getSetY, function() {
25255 if (storage.getItem(keyX) === i) {
25256 criticalSection();
25257 return;
25258 }
25259
25260 delay(function() {
25261 if (storage.getItem(keyY) !== i) {
25262 loop();
25263 return;
25264 }
25265 waitFor(function() {
25266 return !storage.getItem(keyZ);
25267 }, criticalSection);
25268 });
25269 });
25270 };
25271
25272 var criticalSection = function() {
25273 storage.setItem(keyZ, '1');
25274 var removeLock = function () {
25275 storage.removeItem(keyZ);
25276 if (storage.getItem(keyY) === i) {
25277 storage.removeItem(keyY);
25278 }
25279 if (storage.getItem(keyX) === i) {
25280 storage.removeItem(keyX);
25281 }
25282 };
25283
25284 lockedCB()
25285 .then(function (ret) {
25286 removeLock();
25287 resolve(ret);
25288 })
25289 .catch(function (err) {
25290 removeLock();
25291 reject(err);
25292 });
25293 };
25294
25295 try {
25296 if (localStorageSupported(storage, true)) {
25297 loop();
25298 } else {
25299 throw new Error('localStorage support check failed');
25300 }
25301 } catch(err) {
25302 reject(err);
25303 }
25304 }, this));
25305 };
25306
25307 /**
25308 * @type {import('./wrapper').StorageWrapper}
25309 */
25310 var LocalStorageWrapper = function (storageOverride) {
25311 this.storage = storageOverride || win.localStorage;
25312 };
25313
25314 LocalStorageWrapper.prototype.init = function () {
25315 return PromisePolyfill.resolve();
25316 };
25317
25318 LocalStorageWrapper.prototype.isInitialized = function () {
25319 return true;
25320 };
25321
25322 LocalStorageWrapper.prototype.setItem = function (key, value) {
25323 return new PromisePolyfill(_.bind(function (resolve, reject) {
25324 try {
25325 this.storage.setItem(key, JSONStringify(value));
25326 } catch (e) {
25327 reject(e);
25328 }
25329 resolve();
25330 }, this));
25331 };
25332
25333 LocalStorageWrapper.prototype.getItem = function (key) {
25334 return new PromisePolyfill(_.bind(function (resolve, reject) {
25335 var item;
25336 try {
25337 item = JSONParse(this.storage.getItem(key));
25338 } catch (e) {
25339 reject(e);
25340 }
25341 resolve(item);
25342 }, this));
25343 };
25344
25345 LocalStorageWrapper.prototype.removeItem = function (key) {
25346 return new PromisePolyfill(_.bind(function (resolve, reject) {
25347 try {
25348 this.storage.removeItem(key);
25349 } catch (e) {
25350 reject(e);
25351 }
25352 resolve();
25353 }, this));
25354 };
25355
25356 var logger$5 = console_with_prefix('batch');
25357
25358 /**
25359 * RequestQueue: queue for batching API requests with localStorage backup for retries.
25360 * Maintains an in-memory queue which represents the source of truth for the current
25361 * page, but also writes all items out to a copy in the browser's localStorage, which
25362 * can be read on subsequent pageloads and retried. For batchability, all the request
25363 * items in the queue should be of the same type (events, people updates, group updates)
25364 * so they can be sent in a single request to the same API endpoint.
25365 *
25366 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
25367 * the same site to access the same persisted data, they must share the same localStorage
25368 * key (for instance based on project token and queue type). Therefore access to the
25369 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
25370 * simultaneously open windows/tabs from overwriting each other's data (which would lead
25371 * to data loss in some situations).
25372 * @constructor
25373 */
25374 var RequestQueue = function (storageKey, options) {
25375 options = options || {};
25376 this.storageKey = storageKey;
25377 this.usePersistence = options.usePersistence;
25378 if (this.usePersistence) {
25379 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
25380 this.lock = new SharedLock(storageKey, {
25381 storage: options.sharedLockStorage || win.localStorage,
25382 timeoutMS: options.sharedLockTimeoutMS,
25383 });
25384 }
25385 this.reportError = options.errorReporter || _.bind(logger$5.error, logger$5);
25386
25387 this.pid = options.pid || null; // pass pid to test out storage lock contention scenarios
25388
25389 this.memQueue = [];
25390 this.initialized = false;
25391
25392 if (options.enqueueThrottleMs) {
25393 this.enqueuePersisted = batchedThrottle(_.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
25394 } else {
25395 this.enqueuePersisted = _.bind(function (queueEntry) {
25396 return this._enqueuePersisted([queueEntry]);
25397 }, this);
25398 }
25399 };
25400
25401 RequestQueue.prototype.ensureInit = function () {
25402 if (this.initialized || !this.usePersistence) {
25403 return PromisePolyfill.resolve();
25404 }
25405
25406 return this.queueStorage
25407 .init()
25408 .then(_.bind(function () {
25409 this.initialized = true;
25410 }, this))
25411 .catch(_.bind(function (err) {
25412 this.reportError('Error initializing queue persistence. Disabling persistence', err);
25413 this.initialized = true;
25414 this.usePersistence = false;
25415 }, this));
25416 };
25417
25418 /**
25419 * Add one item to queues (memory and localStorage). The queued entry includes
25420 * the given item along with an auto-generated ID and a "flush-after" timestamp.
25421 * It is expected that the item will be sent over the network and dequeued
25422 * before the flush-after time; if this doesn't happen it is considered orphaned
25423 * (e.g., the original tab where it was enqueued got closed before it could be
25424 * sent) and the item can be sent by any tab that finds it in localStorage.
25425 *
25426 * The final callback param is called with a param indicating success or
25427 * failure of the enqueue operation; it is asynchronous because the localStorage
25428 * lock is asynchronous.
25429 */
25430 RequestQueue.prototype.enqueue = function (item, flushInterval) {
25431 var queueEntry = {
25432 'id': cheap_guid(),
25433 'flushAfter': new Date().getTime() + flushInterval * 2,
25434 'payload': item
25435 };
25436
25437 if (!this.usePersistence) {
25438 this.memQueue.push(queueEntry);
25439 return PromisePolyfill.resolve(true);
25440 } else {
25441 return this.enqueuePersisted(queueEntry);
25442 }
25443 };
25444
25445 RequestQueue.prototype._enqueuePersisted = function (queueEntries) {
25446 var enqueueItem = _.bind(function () {
25447 return this.ensureInit()
25448 .then(_.bind(function () {
25449 return this.readFromStorage();
25450 }, this))
25451 .then(_.bind(function (storedQueue) {
25452 return this.saveToStorage(storedQueue.concat(queueEntries));
25453 }, this))
25454 .then(_.bind(function (succeeded) {
25455 // only add to in-memory queue when storage succeeds
25456 if (succeeded) {
25457 this.memQueue = this.memQueue.concat(queueEntries);
25458 }
25459
25460 return succeeded;
25461 }, this))
25462 .catch(_.bind(function (err) {
25463 this.reportError('Error enqueueing items', err, queueEntries);
25464 return false;
25465 }, this));
25466 }, this);
25467
25468 return this.lock
25469 .withLock(enqueueItem, this.pid)
25470 .catch(_.bind(function (err) {
25471 this.reportError('Error acquiring storage lock', err);
25472 return false;
25473 }, this));
25474 };
25475
25476 /**
25477 * Read out the given number of queue entries. If this.memQueue
25478 * has fewer than batchSize items, then look for "orphaned" items
25479 * in the persisted queue (items where the 'flushAfter' time has
25480 * already passed).
25481 */
25482 RequestQueue.prototype.fillBatch = function (batchSize) {
25483 var batch = this.memQueue.slice(0, batchSize);
25484 if (this.usePersistence && batch.length < batchSize) {
25485 // don't need lock just to read events; localStorage is thread-safe
25486 // and the worst that could happen is a duplicate send of some
25487 // orphaned events, which will be deduplicated on the server side
25488 return this.ensureInit()
25489 .then(_.bind(function () {
25490 return this.readFromStorage();
25491 }, this))
25492 .then(_.bind(function (storedQueue) {
25493 if (storedQueue.length) {
25494 // item IDs already in batch; don't duplicate out of storage
25495 var idsInBatch = {}; // poor man's Set
25496 _.each(batch, function (item) {
25497 idsInBatch[item['id']] = true;
25498 });
25499
25500 for (var i = 0; i < storedQueue.length; i++) {
25501 var item = storedQueue[i];
25502 if (new Date().getTime() > item['flushAfter'] && !idsInBatch[item['id']]) {
25503 item.orphaned = true;
25504 batch.push(item);
25505 if (batch.length >= batchSize) {
25506 break;
25507 }
25508 }
25509 }
25510 }
25511
25512 return batch;
25513 }, this));
25514 } else {
25515 return PromisePolyfill.resolve(batch);
25516 }
25517 };
25518
25519 /**
25520 * Remove items with matching 'id' from array (immutably)
25521 * also remove any item without a valid id (e.g., malformed
25522 * storage entries).
25523 */
25524 var filterOutIDsAndInvalid = function (items, idSet) {
25525 var filteredItems = [];
25526 _.each(items, function (item) {
25527 if (item['id'] && !idSet[item['id']]) {
25528 filteredItems.push(item);
25529 }
25530 });
25531 return filteredItems;
25532 };
25533
25534 /**
25535 * Remove items with matching IDs from both in-memory queue
25536 * and persisted queue
25537 */
25538 RequestQueue.prototype.removeItemsByID = function (ids) {
25539 var idSet = {}; // poor man's Set
25540 _.each(ids, function (id) {
25541 idSet[id] = true;
25542 });
25543
25544 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
25545 if (!this.usePersistence) {
25546 return PromisePolyfill.resolve(true);
25547 } else {
25548 var removeFromStorage = _.bind(function () {
25549 return this.ensureInit()
25550 .then(_.bind(function () {
25551 return this.readFromStorage();
25552 }, this))
25553 .then(_.bind(function (storedQueue) {
25554 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
25555 return this.saveToStorage(storedQueue);
25556 }, this))
25557 .then(_.bind(function () {
25558 return this.readFromStorage();
25559 }, this))
25560 .then(_.bind(function (storedQueue) {
25561 // an extra check: did storage report success but somehow
25562 // the items are still there?
25563 for (var i = 0; i < storedQueue.length; i++) {
25564 var item = storedQueue[i];
25565 if (item['id'] && !!idSet[item['id']]) {
25566 throw new Error('Item not removed from storage');
25567 }
25568 }
25569 return true;
25570 }, this))
25571 .catch(_.bind(function (err) {
25572 this.reportError('Error removing items', err, ids);
25573 return false;
25574 }, this));
25575 }, this);
25576
25577 return this.lock
25578 .withLock(removeFromStorage, this.pid)
25579 .catch(_.bind(function (err) {
25580 this.reportError('Error acquiring storage lock', err);
25581 if (!localStorageSupported(this.lock.storage, true)) {
25582 // Looks like localStorage writes have stopped working sometime after
25583 // initialization (probably full), and so nobody can acquire locks
25584 // anymore. Consider it temporarily safe to remove items without the
25585 // lock, since nobody's writing successfully anyway.
25586 return removeFromStorage()
25587 .then(_.bind(function (success) {
25588 if (!success) {
25589 // OK, we couldn't even write out the smaller queue. Try clearing it
25590 // entirely.
25591 return this.queueStorage.removeItem(this.storageKey).then(function () {
25592 return success;
25593 });
25594 }
25595 return success;
25596 }, this))
25597 .catch(_.bind(function (err) {
25598 this.reportError('Error clearing queue', err);
25599 return false;
25600 }, this));
25601 } else {
25602 return false;
25603 }
25604 }, this));
25605 }
25606 };
25607
25608 // internal helper for RequestQueue.updatePayloads
25609 var updatePayloads = function (existingItems, itemsToUpdate) {
25610 var newItems = [];
25611 _.each(existingItems, function (item) {
25612 var id = item['id'];
25613 if (id in itemsToUpdate) {
25614 var newPayload = itemsToUpdate[id];
25615 if (newPayload !== null) {
25616 item['payload'] = newPayload;
25617 newItems.push(item);
25618 }
25619 } else {
25620 // no update
25621 newItems.push(item);
25622 }
25623 });
25624 return newItems;
25625 };
25626
25627 /**
25628 * Update payloads of given items in both in-memory queue and
25629 * persisted queue. Items set to null are removed from queues.
25630 */
25631 RequestQueue.prototype.updatePayloads = function (itemsToUpdate) {
25632 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
25633 if (!this.usePersistence) {
25634 return PromisePolyfill.resolve(true);
25635 } else {
25636 return this.lock
25637 .withLock(_.bind(function lockAcquired() {
25638 return this.ensureInit()
25639 .then(_.bind(function () {
25640 return this.readFromStorage();
25641 }, this))
25642 .then(_.bind(function (storedQueue) {
25643 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
25644 return this.saveToStorage(storedQueue);
25645 }, this))
25646 .catch(_.bind(function (err) {
25647 this.reportError('Error updating items', itemsToUpdate, err);
25648 return false;
25649 }, this));
25650 }, this), this.pid)
25651 .catch(_.bind(function (err) {
25652 this.reportError('Error acquiring storage lock', err);
25653 return false;
25654 }, this));
25655 }
25656 };
25657
25658 /**
25659 * Read and parse items array from localStorage entry, handling
25660 * malformed/missing data if necessary.
25661 */
25662 RequestQueue.prototype.readFromStorage = function () {
25663 return this.ensureInit()
25664 .then(_.bind(function () {
25665 return this.queueStorage.getItem(this.storageKey);
25666 }, this))
25667 .then(_.bind(function (storageEntry) {
25668 if (storageEntry) {
25669 if (!_.isArray(storageEntry)) {
25670 this.reportError('Invalid storage entry:', storageEntry);
25671 storageEntry = null;
25672 }
25673 }
25674 return storageEntry || [];
25675 }, this))
25676 .catch(_.bind(function (err) {
25677 this.reportError('Error retrieving queue', err);
25678 return [];
25679 }, this));
25680 };
25681
25682 /**
25683 * Serialize the given items array to localStorage.
25684 */
25685 RequestQueue.prototype.saveToStorage = function (queue) {
25686 return this.ensureInit()
25687 .then(_.bind(function () {
25688 return this.queueStorage.setItem(this.storageKey, queue);
25689 }, this))
25690 .then(function () {
25691 return true;
25692 })
25693 .catch(_.bind(function (err) {
25694 this.reportError('Error saving queue', err);
25695 return false;
25696 }, this));
25697 };
25698
25699 /**
25700 * Clear out queues (memory and localStorage).
25701 */
25702 RequestQueue.prototype.clear = function () {
25703 this.memQueue = [];
25704
25705 if (this.usePersistence) {
25706 return this.ensureInit()
25707 .then(_.bind(function () {
25708 return this.queueStorage.removeItem(this.storageKey);
25709 }, this));
25710 } else {
25711 return PromisePolyfill.resolve();
25712 }
25713 };
25714
25715 // maximum interval between request retries after exponential backoff
25716 var MAX_RETRY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
25717
25718 var logger$4 = console_with_prefix('batch');
25719
25720 /**
25721 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
25722 * type (events, people, groups).
25723 * Uses RequestQueue to manage the backing store.
25724 * @constructor
25725 */
25726 var RequestBatcher = function(storageKey, options) {
25727 this.errorReporter = options.errorReporter;
25728 this.queue = new RequestQueue(storageKey, {
25729 errorReporter: _.bind(this.reportError, this),
25730 queueStorage: options.queueStorage,
25731 sharedLockStorage: options.sharedLockStorage,
25732 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
25733 usePersistence: options.usePersistence,
25734 enqueueThrottleMs: options.enqueueThrottleMs
25735 });
25736
25737 this.libConfig = options.libConfig;
25738 this.sendRequest = options.sendRequestFunc;
25739 this.beforeSendHook = options.beforeSendHook;
25740 this.stopAllBatching = options.stopAllBatchingFunc;
25741
25742 // seed variable batch size + flush interval with configured values
25743 this.batchSize = this.libConfig['batch_size'];
25744 this.flushInterval = this.libConfig['batch_flush_interval_ms'];
25745
25746 this.stopped = !this.libConfig['batch_autostart'];
25747 this.consecutiveRemovalFailures = 0;
25748
25749 // extra client-side dedupe
25750 this.itemIdsSentSuccessfully = {};
25751
25752 // Make the flush occur at the interval specified by flushIntervalMs, default behavior will attempt consecutive flushes
25753 // as long as the queue is not empty. This is useful for high-frequency events like Session Replay where we might end up
25754 // in a request loop and get ratelimited by the server.
25755 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
25756
25757 this._flushPromise = null;
25758 };
25759
25760 /**
25761 * Add one item to queue.
25762 */
25763 RequestBatcher.prototype.enqueue = function(item) {
25764 return this.queue.enqueue(item, this.flushInterval);
25765 };
25766
25767 /**
25768 * Start flushing batches at the configured time interval. Must call
25769 * this method upon SDK init in order to send anything over the network.
25770 */
25771 RequestBatcher.prototype.start = function() {
25772 this.stopped = false;
25773 this.consecutiveRemovalFailures = 0;
25774 return this.flush();
25775 };
25776
25777 /**
25778 * Stop flushing batches. Can be restarted by calling start().
25779 */
25780 RequestBatcher.prototype.stop = function() {
25781 this.stopped = true;
25782 if (this.timeoutID) {
25783 clearTimeout(this.timeoutID);
25784 this.timeoutID = null;
25785 }
25786 };
25787
25788 /**
25789 * Clear out queue.
25790 */
25791 RequestBatcher.prototype.clear = function() {
25792 return this.queue.clear();
25793 };
25794
25795 /**
25796 * Restore batch size configuration to whatever is set in the main SDK.
25797 */
25798 RequestBatcher.prototype.resetBatchSize = function() {
25799 this.batchSize = this.libConfig['batch_size'];
25800 };
25801
25802 /**
25803 * Restore flush interval time configuration to whatever is set in the main SDK.
25804 */
25805 RequestBatcher.prototype.resetFlush = function() {
25806 this.scheduleFlush(this.libConfig['batch_flush_interval_ms']);
25807 };
25808
25809 /**
25810 * Schedule the next flush in the given number of milliseconds.
25811 */
25812 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
25813 this.flushInterval = flushMS;
25814 if (!this.stopped) { // don't schedule anymore if batching has been stopped
25815 this.timeoutID = setTimeout(_.bind(function() {
25816 if (!this.stopped) {
25817 this._flushPromise = this.flush();
25818 }
25819 }, this), this.flushInterval);
25820 }
25821 };
25822
25823 /**
25824 * Send a request using the sendRequest callback, but promisified.
25825 * TODO: sendRequest should be promisified in the first place.
25826 */
25827 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
25828 return new PromisePolyfill(_.bind(function(resolve) {
25829 this.sendRequest(data, options, resolve);
25830 }, this));
25831 };
25832
25833
25834 /**
25835 * Flush one batch to network. Depending on success/failure modes, it will either
25836 * remove the batch from the queue or leave it in for retry, and schedule the next
25837 * flush. In cases of most network or API failures, it will back off exponentially
25838 * when retrying.
25839 * @param {Object} [options]
25840 * @param {boolean} [options.sendBeacon] - whether to send batch with
25841 * navigator.sendBeacon (only useful for sending batches before page unloads, as
25842 * sendBeacon offers no callbacks or status indications)
25843 */
25844 RequestBatcher.prototype.flush = function(options) {
25845 if (this.requestInProgress) {
25846 logger$4.log('Flush: Request already in progress');
25847 return PromisePolyfill.resolve();
25848 }
25849
25850 this.requestInProgress = true;
25851
25852 options = options || {};
25853 var timeoutMS = this.libConfig['batch_request_timeout_ms'];
25854 var startTime = new Date().getTime();
25855 var currentBatchSize = this.batchSize;
25856
25857 return this.queue.fillBatch(currentBatchSize)
25858 .then(_.bind(function(batch) {
25859
25860 // if there's more items in the queue than the batch size, attempt
25861 // to flush again after the current batch is done.
25862 var attemptSecondaryFlush = batch.length === currentBatchSize;
25863 var dataForRequest = [];
25864 var transformedItems = {};
25865 _.each(batch, function(item) {
25866 var payload = item['payload'];
25867 if (this.beforeSendHook && !item.orphaned) {
25868 payload = this.beforeSendHook(payload);
25869 }
25870 if (payload) {
25871 // mp_sent_by_lib_version prop captures which lib version actually
25872 // sends each event (regardless of which version originally queued
25873 // it for sending)
25874 if (payload['event'] && payload['properties']) {
25875 payload['properties'] = _.extend(
25876 {},
25877 payload['properties'],
25878 {'mp_sent_by_lib_version': Config.LIB_VERSION}
25879 );
25880 }
25881 var addPayload = true;
25882 var itemId = item['id'];
25883 if (itemId) {
25884 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
25885 this.reportError('[dupe] item ID sent too many times, not sending', {
25886 item: item,
25887 batchSize: batch.length,
25888 timesSent: this.itemIdsSentSuccessfully[itemId]
25889 });
25890 addPayload = false;
25891 }
25892 } else {
25893 this.reportError('[dupe] found item with no ID', {item: item});
25894 }
25895
25896 if (addPayload) {
25897 dataForRequest.push(payload);
25898 }
25899 }
25900 transformedItems[item['id']] = payload;
25901 }, this);
25902
25903 if (dataForRequest.length < 1) {
25904 this.requestInProgress = false;
25905 this.resetFlush();
25906 return PromisePolyfill.resolve(); // nothing to do
25907 }
25908
25909 var removeItemsFromQueue = _.bind(function () {
25910 return this.queue
25911 .removeItemsByID(
25912 _.map(batch, function (item) {
25913 return item['id'];
25914 })
25915 )
25916 .then(_.bind(function (succeeded) {
25917 // client-side dedupe
25918 _.each(batch, _.bind(function(item) {
25919 var itemId = item['id'];
25920 if (itemId) {
25921 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
25922 this.itemIdsSentSuccessfully[itemId]++;
25923 if (this.itemIdsSentSuccessfully[itemId] > 5) {
25924 this.reportError('[dupe] item ID sent too many times', {
25925 item: item,
25926 batchSize: batch.length,
25927 timesSent: this.itemIdsSentSuccessfully[itemId]
25928 });
25929 }
25930 } else {
25931 this.reportError('[dupe] found item with no ID while removing', {item: item});
25932 }
25933 }, this));
25934
25935 if (succeeded) {
25936 this.consecutiveRemovalFailures = 0;
25937 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
25938 this.resetFlush(); // schedule next batch with a delay
25939 return PromisePolyfill.resolve();
25940 } else {
25941 return this.flush(); // handle next batch if the queue isn't empty
25942 }
25943 } else {
25944 if (++this.consecutiveRemovalFailures > 5) {
25945 this.reportError('Too many queue failures; disabling batching system.');
25946 this.stopAllBatching();
25947 } else {
25948 this.resetFlush();
25949 }
25950 return PromisePolyfill.resolve();
25951 }
25952 }, this));
25953 }, this);
25954
25955 var batchSendCallback = _.bind(function(res) {
25956 this.requestInProgress = false;
25957
25958 try {
25959
25960 // handle API response in a try-catch to make sure we can reset the
25961 // flush operation if something goes wrong
25962
25963 if (options.unloading) {
25964 // update persisted data to include hook transformations
25965 return this.queue.updatePayloads(transformedItems);
25966 } else if (
25967 _.isObject(res) &&
25968 res.error === 'timeout' &&
25969 new Date().getTime() - startTime >= timeoutMS
25970 ) {
25971 this.reportError('Network timeout; retrying');
25972 return this.flush();
25973 } else if (
25974 _.isObject(res) &&
25975 (
25976 res.httpStatusCode >= 500
25977 || res.httpStatusCode === 429
25978 || (res.httpStatusCode <= 0 && !isOnline())
25979 || res.error === 'timeout'
25980 )
25981 ) {
25982 // network or API error, or 429 Too Many Requests, retry
25983 var retryMS = this.flushInterval * 2;
25984 if (res.retryAfter) {
25985 retryMS = (parseInt(res.retryAfter, 10) * 1000) || retryMS;
25986 }
25987 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
25988 this.reportError('Error; retry in ' + retryMS + ' ms');
25989 this.scheduleFlush(retryMS);
25990 return PromisePolyfill.resolve();
25991 } else if (_.isObject(res) && res.httpStatusCode === 413) {
25992 // 413 Payload Too Large
25993 if (batch.length > 1) {
25994 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
25995 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
25996 this.reportError('413 response; reducing batch size to ' + this.batchSize);
25997 this.resetFlush();
25998 return PromisePolyfill.resolve();
25999 } else {
26000 this.reportError('Single-event request too large; dropping', batch);
26001 this.resetBatchSize();
26002 return removeItemsFromQueue();
26003 }
26004 } else {
26005 // successful network request+response; remove each item in batch from queue
26006 // (even if it was e.g. a 400, in which case retrying won't help)
26007 return removeItemsFromQueue();
26008 }
26009 } catch(err) {
26010 this.reportError('Error handling API response', err);
26011 this.resetFlush();
26012 }
26013 }, this);
26014 var requestOptions = {
26015 method: 'POST',
26016 verbose: true,
26017 ignore_json_errors: true, // eslint-disable-line camelcase
26018 timeout_ms: timeoutMS // eslint-disable-line camelcase
26019 };
26020 if (options.unloading) {
26021 requestOptions.transport = 'sendBeacon';
26022 }
26023 logger$4.log('MIXPANEL REQUEST:', dataForRequest);
26024 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
26025 }, this))
26026 .catch(_.bind(function(err) {
26027 this.reportError('Error flushing request queue', err);
26028 this.resetFlush();
26029 }, this));
26030 };
26031
26032 /**
26033 * Log error to global logger and optional user-defined logger.
26034 */
26035 RequestBatcher.prototype.reportError = function(msg, err) {
26036 logger$4.error.apply(logger$4.error, arguments);
26037 if (this.errorReporter) {
26038 try {
26039 if (!(err instanceof Error)) {
26040 err = new Error(msg);
26041 }
26042 this.errorReporter(msg, err);
26043 } catch(err) {
26044 logger$4.error(err);
26045 }
26046 }
26047 };
26048
26049 /**
26050 * @param {import('./session-recording').SerializedRecording} serializedRecording
26051 * @returns {boolean}
26052 */
26053 var isRecordingExpired = function(serializedRecording) {
26054 var now = Date.now();
26055 return !serializedRecording || now > serializedRecording['maxExpires'] || now > serializedRecording['idleExpires'];
26056 };
26057
26058 var RECORD_ENQUEUE_THROTTLE_MS = 250;
26059
26060 var logger$3 = console_with_prefix('recorder');
26061 var CompressionStream = win['CompressionStream'];
26062
26063 var RECORDER_BATCHER_LIB_CONFIG = {
26064 'batch_size': 1000,
26065 'batch_flush_interval_ms': 10 * 1000,
26066 'batch_request_timeout_ms': 90 * 1000,
26067 'batch_autostart': true
26068 };
26069
26070 var ACTIVE_SOURCES = new Set([
26071 IncrementalSource.MouseMove,
26072 IncrementalSource.MouseInteraction,
26073 IncrementalSource.Scroll,
26074 IncrementalSource.ViewportResize,
26075 IncrementalSource.Input,
26076 IncrementalSource.TouchMove,
26077 IncrementalSource.MediaInteraction,
26078 IncrementalSource.Drag,
26079 IncrementalSource.Selection,
26080 ]);
26081
26082 function isUserEvent(ev) {
26083 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
26084 }
26085
26086 /**
26087 * @typedef {Object} SerializedRecording
26088 * @property {number} idleExpires
26089 * @property {number} maxExpires
26090 * @property {number} replayStartTime
26091 * @property {number} seqNo
26092 * @property {string} batchStartUrl
26093 * @property {string} replayId
26094 * @property {string} tabId
26095 * @property {string} replayStartUrl
26096 */
26097
26098 /**
26099 * @typedef {Object} SessionRecordingOptions
26100 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
26101 * @property {String} [options.replayId] - unique uuid for a single replay
26102 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
26103 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
26104 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
26105 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
26106 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
26107 * optional properties for deserialization:
26108 * @property {number} idleExpires
26109 * @property {number} maxExpires
26110 * @property {number} replayStartTime
26111 * @property {number} seqNo
26112 * @property {string} batchStartUrl
26113 * @property {string} replayStartUrl
26114 */
26115
26116 /**
26117 * @typedef {Object} UserIdInfo
26118 * @property {string} distinct_id
26119 * @property {string} user_id
26120 * @property {string} device_id
26121 */
26122
26123
26124 /**
26125 * This class encapsulates a single session recording and its lifecycle.
26126 * @param {SessionRecordingOptions} options
26127 */
26128 var SessionRecording = function(options) {
26129 this._mixpanel = options.mixpanelInstance;
26130 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
26131 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
26132 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
26133 this._rrwebRecord = options.rrwebRecord || null;
26134
26135 // internal rrweb stopRecording function
26136 this._stopRecording = null;
26137 this.replayId = options.replayId;
26138
26139 this.batchStartUrl = options.batchStartUrl || null;
26140 this.replayStartUrl = options.replayStartUrl || null;
26141 this.idleExpires = options.idleExpires || null;
26142 this.maxExpires = options.maxExpires || null;
26143 this.replayStartTime = options.replayStartTime || null;
26144 this.seqNo = options.seqNo || 0;
26145
26146 this.idleTimeoutId = null;
26147 this.maxTimeoutId = null;
26148
26149 this.recordMaxMs = MAX_RECORDING_MS;
26150 this.recordMinMs = 0;
26151
26152 // disable persistence if localStorage is not supported
26153 // request-queue will automatically disable persistence if indexedDB fails to initialize
26154 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig('disable_persistence');
26155
26156 // each replay has its own batcher key to avoid conflicts between rrweb events of different recordings
26157 this.batcherKey = '__mprec_' + this.getConfig('name') + '_' + this.getConfig('token') + '_' + this.replayId;
26158 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
26159 this.batcher = new RequestBatcher(this.batcherKey, {
26160 errorReporter: this.reportError.bind(this),
26161 flushOnlyOnInterval: true,
26162 libConfig: RECORDER_BATCHER_LIB_CONFIG,
26163 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
26164 queueStorage: this.queueStorage,
26165 sharedLockStorage: options.sharedLockStorage,
26166 usePersistence: usePersistence,
26167 stopAllBatchingFunc: this.stopRecording.bind(this),
26168
26169 // increased throttle and shared lock timeout because recording events are very high frequency.
26170 // this will minimize the amount of lock contention between enqueued events.
26171 // for session recordings there is a lock for each tab anyway, so there's no risk of deadlock between tabs.
26172 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
26173 sharedLockTimeoutMS: 10 * 1000,
26174 });
26175 };
26176
26177 /**
26178 * @returns {UserIdInfo}
26179 */
26180 SessionRecording.prototype.getUserIdInfo = function () {
26181 if (this.finalFlushUserIdInfo) {
26182 return this.finalFlushUserIdInfo;
26183 }
26184
26185 var userIdInfo = {
26186 'distinct_id': String(this._mixpanel.get_distinct_id()),
26187 };
26188
26189 // send ID management props if they exist
26190 var deviceId = this._mixpanel.get_property('$device_id');
26191 if (deviceId) {
26192 userIdInfo['$device_id'] = deviceId;
26193 }
26194 var userId = this._mixpanel.get_property('$user_id');
26195 if (userId) {
26196 userIdInfo['$user_id'] = userId;
26197 }
26198 return userIdInfo;
26199 };
26200
26201 SessionRecording.prototype.unloadPersistedData = function () {
26202 this.batcher.stop();
26203 return this.batcher.flush()
26204 .then(function () {
26205 return this.queueStorage.removeItem(this.batcherKey);
26206 }.bind(this));
26207 };
26208
26209 SessionRecording.prototype.getConfig = function(configVar) {
26210 return this._mixpanel.get_config(configVar);
26211 };
26212
26213 // Alias for getConfig, used by the common addOptOutCheckMixpanelLib function which
26214 // reaches into this class instance and expects the snake case version of the function.
26215 // eslint-disable-next-line camelcase
26216 SessionRecording.prototype.get_config = function(configVar) {
26217 return this.getConfig(configVar);
26218 };
26219
26220 SessionRecording.prototype.startRecording = function (shouldStopBatcher) {
26221 if (this._rrwebRecord === null) {
26222 this.reportError('rrweb record function not provided. ');
26223 return;
26224 }
26225
26226 if (this._stopRecording !== null) {
26227 logger$3.log('Recording already in progress, skipping startRecording.');
26228 return;
26229 }
26230
26231 this.recordMaxMs = this.getConfig('record_max_ms');
26232 if (this.recordMaxMs > MAX_RECORDING_MS) {
26233 this.recordMaxMs = MAX_RECORDING_MS;
26234 logger$3.critical('record_max_ms cannot be greater than ' + MAX_RECORDING_MS + 'ms. Capping value.');
26235 }
26236
26237 if (!this.maxExpires) {
26238 this.maxExpires = new Date().getTime() + this.recordMaxMs;
26239 }
26240
26241 this.recordMinMs = this.getConfig('record_min_ms');
26242 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
26243 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
26244 logger$3.critical('record_min_ms cannot be greater than ' + MAX_VALUE_FOR_MIN_RECORDING_MS + 'ms. Capping value.');
26245 }
26246
26247 if (!this.replayStartTime) {
26248 this.replayStartTime = new Date().getTime();
26249 this.batchStartUrl = _.info.currentUrl();
26250 this.replayStartUrl = _.info.currentUrl();
26251 }
26252
26253 if (shouldStopBatcher || this.recordMinMs > 0) {
26254 // the primary case for shouldStopBatcher is when we're starting recording after a reset
26255 // and don't want to send anything over the network until there's
26256 // actual user activity
26257 // this also applies if the minimum recording length has not been hit yet
26258 // so that we don't send data until we know the recording will be long enough
26259 this.batcher.stop();
26260 } else {
26261 this.batcher.start();
26262 }
26263
26264 var resetIdleTimeout = function () {
26265 clearTimeout(this.idleTimeoutId);
26266 var idleTimeoutMs = this.getConfig('record_idle_timeout_ms');
26267 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
26268 this.idleExpires = new Date().getTime() + idleTimeoutMs;
26269 }.bind(this);
26270 resetIdleTimeout();
26271
26272 var blockSelector = this.getConfig('record_block_selector');
26273 if (blockSelector === '' || blockSelector === null) {
26274 blockSelector = undefined;
26275 }
26276
26277 try {
26278 this._stopRecording = this._rrwebRecord({
26279 'emit': function (ev) {
26280 if (this.idleExpires && this.idleExpires < ev.timestamp) {
26281 this._onIdleTimeout();
26282 return;
26283 }
26284 if (isUserEvent(ev)) {
26285 if (this.batcher.stopped && new Date().getTime() - this.replayStartTime >= this.recordMinMs) {
26286 // start flushing again after user activity
26287 this.batcher.start();
26288 }
26289 resetIdleTimeout();
26290 }
26291 // promise only used to await during tests
26292 this.__enqueuePromise = this.batcher.enqueue(ev);
26293 }.bind(this),
26294 'blockClass': this.getConfig('record_block_class'),
26295 'blockSelector': blockSelector,
26296 'collectFonts': this.getConfig('record_collect_fonts'),
26297 'dataURLOptions': { // canvas image options (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
26298 'type': 'image/webp',
26299 'quality': 0.6
26300 },
26301 'maskAllInputs': true,
26302 'maskTextClass': this.getConfig('record_mask_text_class'),
26303 'maskTextSelector': this.getConfig('record_mask_text_selector'),
26304 'recordCanvas': this.getConfig('record_canvas'),
26305 'sampling': {
26306 'canvas': 15
26307 }
26308 });
26309 } catch (err) {
26310 this.reportError('Unexpected error when starting rrweb recording.', err);
26311 }
26312
26313 if (typeof this._stopRecording !== 'function') {
26314 this.reportError('rrweb failed to start, skipping this recording.');
26315 this._stopRecording = null;
26316 this.stopRecording(); // stop batcher looping and any timeouts
26317 return;
26318 }
26319
26320 var maxTimeoutMs = this.maxExpires - new Date().getTime();
26321 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
26322 };
26323
26324 SessionRecording.prototype.stopRecording = function (skipFlush) {
26325 // store the user ID info in case this is getting called in mixpanel.reset()
26326 this.finalFlushUserIdInfo = this.getUserIdInfo();
26327
26328 if (!this.isRrwebStopped()) {
26329 try {
26330 this._stopRecording();
26331 } catch (err) {
26332 this.reportError('Error with rrweb stopRecording', err);
26333 }
26334 this._stopRecording = null;
26335 }
26336
26337 var flushPromise;
26338 if (this.batcher.stopped) {
26339 // never got user activity to flush after reset, so just clear the batcher
26340 flushPromise = this.batcher.clear();
26341 } else if (!skipFlush) {
26342 // flush any remaining events from running batcher
26343 flushPromise = this.batcher.flush();
26344 }
26345 this.batcher.stop();
26346
26347 clearTimeout(this.idleTimeoutId);
26348 clearTimeout(this.maxTimeoutId);
26349 return flushPromise;
26350 };
26351
26352 SessionRecording.prototype.isRrwebStopped = function () {
26353 return this._stopRecording === null;
26354 };
26355
26356
26357 /**
26358 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
26359 * we stop recording and dump any queued events if the user has opted out.
26360 */
26361 SessionRecording.prototype.flushEventsWithOptOut = function (data, options, cb) {
26362 var onOptOut = function (code) {
26363 // addOptOutCheckMixpanelLib invokes this function with code=0 when the user has opted out
26364 if (code === 0) {
26365 this.stopRecording();
26366 cb({error: 'Tracking has been opted out, stopping recording.'});
26367 }
26368 }.bind(this);
26369
26370 this._flushEvents(data, options, cb, onOptOut);
26371 };
26372
26373 /**
26374 * @returns {SerializedRecording}
26375 */
26376 SessionRecording.prototype.serialize = function () {
26377 // don't break if mixpanel instance was destroyed at some point
26378 var tabId;
26379 try {
26380 tabId = this._mixpanel.get_tab_id();
26381 } catch (e) {
26382 this.reportError('Error getting tab ID for serialization ', e);
26383 tabId = null;
26384 }
26385
26386 return {
26387 'replayId': this.replayId,
26388 'seqNo': this.seqNo,
26389 'replayStartTime': this.replayStartTime,
26390 'batchStartUrl': this.batchStartUrl,
26391 'replayStartUrl': this.replayStartUrl,
26392 'idleExpires': this.idleExpires,
26393 'maxExpires': this.maxExpires,
26394 'tabId': tabId,
26395 };
26396 };
26397
26398
26399 /**
26400 * @static
26401 * @param {SerializedRecording} serializedRecording
26402 * @param {SessionRecordingOptions} options
26403 * @returns {SessionRecording}
26404 */
26405 SessionRecording.deserialize = function (serializedRecording, options) {
26406 var recording = new SessionRecording(_.extend({}, options, {
26407 replayId: serializedRecording['replayId'],
26408 batchStartUrl: serializedRecording['batchStartUrl'],
26409 replayStartUrl: serializedRecording['replayStartUrl'],
26410 idleExpires: serializedRecording['idleExpires'],
26411 maxExpires: serializedRecording['maxExpires'],
26412 replayStartTime: serializedRecording['replayStartTime'],
26413 seqNo: serializedRecording['seqNo'],
26414 sharedLockStorage: options.sharedLockStorage,
26415 }));
26416
26417 return recording;
26418 };
26419
26420 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
26421 var onSuccess = function (response, responseBody) {
26422 // Update batch specific props only if the request was successful to guarantee ordering.
26423 // RequestBatcher will always flush the next batch after the previous one succeeds.
26424 // extra check to see if the replay ID has changed so that we don't increment the seqNo on the wrong replay
26425 if (response.status === 200 && this.replayId === currentReplayId) {
26426 this.seqNo++;
26427 this.batchStartUrl = _.info.currentUrl();
26428 }
26429
26430 this._onBatchSent();
26431 callback({
26432 status: 0,
26433 httpStatusCode: response.status,
26434 responseBody: responseBody,
26435 retryAfter: response.headers.get('Retry-After')
26436 });
26437 }.bind(this);
26438 var apiHost = (this._mixpanel.get_api_host && this._mixpanel.get_api_host('record')) || this.getConfig('api_host');
26439 win['fetch'](apiHost + '/' + this.getConfig('api_routes')['record'] + '?' + new URLSearchParams(reqParams), {
26440 'method': 'POST',
26441 'headers': {
26442 'Authorization': 'Basic ' + btoa(this.getConfig('token') + ':'),
26443 'Content-Type': 'application/octet-stream'
26444 },
26445 'body': reqBody,
26446 }).then(function (response) {
26447 response.json().then(function (responseBody) {
26448 onSuccess(response, responseBody);
26449 }).catch(function (error) {
26450 callback({error: error});
26451 });
26452 }).catch(function (error) {
26453 callback({error: error, httpStatusCode: 0});
26454 });
26455 };
26456
26457 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function (data, options, callback) {
26458 var numEvents = data.length;
26459
26460 if (numEvents > 0) {
26461 var replayId = this.replayId;
26462
26463 // each rrweb event has a timestamp - leverage those to get time properties
26464 var batchStartTime = Infinity;
26465 var batchEndTime = -Infinity;
26466 var hasFullSnapshot = false;
26467 for (var i = 0; i < numEvents; i++) {
26468 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
26469 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
26470 if (data[i].type === EventType.FullSnapshot) {
26471 hasFullSnapshot = true;
26472 }
26473 }
26474
26475 if (this.seqNo === 0) {
26476 if (!hasFullSnapshot) {
26477 callback({error: 'First batch does not contain a full snapshot. Aborting recording.'});
26478 this.stopRecording(true);
26479 return;
26480 }
26481 this.replayStartTime = batchStartTime;
26482 } else if (!this.replayStartTime) {
26483 this.reportError('Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.');
26484 this.replayStartTime = batchStartTime;
26485 }
26486
26487 var replayLengthMs = batchEndTime - this.replayStartTime;
26488
26489 var reqParams = {
26490 '$current_url': this.batchStartUrl,
26491 '$lib_version': Config.LIB_VERSION,
26492 'batch_start_time': batchStartTime / 1000,
26493 'mp_lib': 'web',
26494 'replay_id': replayId,
26495 'replay_length_ms': replayLengthMs,
26496 'replay_start_time': this.replayStartTime / 1000,
26497 'replay_start_url': this.replayStartUrl,
26498 'seq': this.seqNo
26499 };
26500 var eventsJson = JSON.stringify(data);
26501 Object.assign(reqParams, this.getUserIdInfo());
26502
26503 if (CompressionStream) {
26504 var jsonStream = new Blob([eventsJson], {type: 'application/json'}).stream();
26505 var gzipStream = jsonStream.pipeThrough(new CompressionStream('gzip'));
26506 new Response(gzipStream)
26507 .blob()
26508 .then(function(compressedBlob) {
26509 reqParams['format'] = 'gzip';
26510 this._sendRequest(replayId, reqParams, compressedBlob, callback);
26511 }.bind(this));
26512 } else {
26513 reqParams['format'] = 'body';
26514 this._sendRequest(replayId, reqParams, eventsJson, callback);
26515 }
26516 }
26517 });
26518
26519
26520 SessionRecording.prototype.reportError = function(msg, err) {
26521 logger$3.error.apply(logger$3.error, arguments);
26522 try {
26523 if (!err && !(msg instanceof Error)) {
26524 msg = new Error(msg);
26525 }
26526 this.getConfig('error_reporter')(msg, err);
26527 } catch(err) {
26528 logger$3.error(err);
26529 }
26530 };
26531
26532 /**
26533 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
26534 * Makes sure that only one tab can be recording at a time.
26535 */
26536 var RecordingRegistry = function (options) {
26537 /** @type {IDBStorageWrapper} */
26538 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
26539 this.errorReporter = options.errorReporter;
26540 this.mixpanelInstance = options.mixpanelInstance;
26541 this.sharedLockStorage = options.sharedLockStorage;
26542 };
26543
26544 RecordingRegistry.prototype.isPersistenceEnabled = function() {
26545 return !this.mixpanelInstance.get_config('disable_persistence');
26546 };
26547
26548 RecordingRegistry.prototype.handleError = function (err) {
26549 this.errorReporter('IndexedDB error: ', err);
26550 };
26551
26552 /**
26553 * @param {import('./session-recording').SerializedRecording} serializedRecording
26554 */
26555 RecordingRegistry.prototype.setActiveRecording = function (serializedRecording) {
26556 if (!this.isPersistenceEnabled()) {
26557 return PromisePolyfill.resolve();
26558 }
26559
26560 var tabId = serializedRecording['tabId'];
26561 if (!tabId) {
26562 console.warn('No tab ID is set, cannot persist recording metadata.');
26563 return PromisePolyfill.resolve();
26564 }
26565
26566 return this.idb.init()
26567 .then(function () {
26568 return this.idb.setItem(tabId, serializedRecording);
26569 }.bind(this))
26570 .catch(this.handleError.bind(this));
26571 };
26572
26573 /**
26574 * @returns {Promise<import('./session-recording').SerializedRecording>}
26575 */
26576 RecordingRegistry.prototype.getActiveRecording = function () {
26577 if (!this.isPersistenceEnabled()) {
26578 return PromisePolyfill.resolve(null);
26579 }
26580
26581 return this.idb.init()
26582 .then(function () {
26583 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
26584 }.bind(this))
26585 .then(function (serializedRecording) {
26586 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
26587 }.bind(this))
26588 .catch(this.handleError.bind(this));
26589 };
26590
26591 RecordingRegistry.prototype.clearActiveRecording = function () {
26592 if (this.isPersistenceEnabled()) {
26593 // mark recording as expired instead of deleting it in case the page unloads mid-flush and doesn't make it to ingestion.
26594 // this will ensure the next pageload will flush the remaining events, but not try to continue the recording.
26595 return this.markActiveRecordingExpired();
26596 } else {
26597 return this.deleteActiveRecording();
26598 }
26599 };
26600
26601 RecordingRegistry.prototype.markActiveRecordingExpired = function () {
26602 return this.getActiveRecording()
26603 .then(function (serializedRecording) {
26604 if (serializedRecording) {
26605 serializedRecording['maxExpires'] = 0;
26606 return this.setActiveRecording(serializedRecording);
26607 }
26608 }.bind(this))
26609 .catch(this.handleError.bind(this));
26610 };
26611
26612 RecordingRegistry.prototype.deleteActiveRecording = function () {
26613 // avoid initializing IDB if this registry instance hasn't already written a recording
26614 if (this.idb.isInitialized()) {
26615 return this.idb.removeItem(this.mixpanelInstance.get_tab_id())
26616 .catch(this.handleError.bind(this));
26617 } else {
26618 return PromisePolyfill.resolve();
26619 }
26620 };
26621
26622 /**
26623 * Flush any inactive recordings from the registry to minimize data loss.
26624 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
26625 */
26626 RecordingRegistry.prototype.flushInactiveRecordings = function () {
26627 if (!this.isPersistenceEnabled()) {
26628 return PromisePolyfill.resolve([]);
26629 }
26630
26631 return this.idb.init()
26632 .then(function() {
26633 return this.idb.getAll();
26634 }.bind(this))
26635 .then(function (serializedRecordings) {
26636 // clean up any expired recordings from the registry, non-expired ones may be active in other tabs
26637 var unloadPromises = serializedRecordings
26638 .filter(function (serializedRecording) {
26639 return isRecordingExpired(serializedRecording);
26640 })
26641 .map(function (serializedRecording) {
26642 var sessionRecording = SessionRecording.deserialize(serializedRecording, {
26643 mixpanelInstance: this.mixpanelInstance,
26644 sharedLockStorage: this.sharedLockStorage
26645 });
26646 return sessionRecording.unloadPersistedData()
26647 .then(function () {
26648 // expired recording was successfully flushed, we can clean it up from the registry
26649 return this.idb.removeItem(serializedRecording['tabId']);
26650 }.bind(this))
26651 .catch(this.handleError.bind(this));
26652 }.bind(this));
26653
26654 return PromisePolyfill.all(unloadPromises);
26655 }.bind(this))
26656 .catch(this.handleError.bind(this));
26657 };
26658
26659 var logger$2 = console_with_prefix('recorder');
26660
26661 /**
26662 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
26663 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
26664 */
26665 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
26666 this.mixpanelInstance = mixpanelInstance;
26667 this.rrwebRecord = rrwebRecord || record;
26668 this.sharedLockStorage = sharedLockStorage;
26669
26670 /**
26671 * @member {import('./registry').RecordingRegistry}
26672 */
26673 this.recordingRegistry = new RecordingRegistry({
26674 mixpanelInstance: this.mixpanelInstance,
26675 errorReporter: logger$2.error,
26676 sharedLockStorage: sharedLockStorage
26677 });
26678 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
26679
26680 this.activeRecording = null;
26681 this.stopRecordingInProgress = false;
26682 };
26683
26684 MixpanelRecorder.prototype.startRecording = function(options) {
26685 options = options || {};
26686 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
26687 logger$2.log('Recording already in progress, skipping startRecording.');
26688 return;
26689 }
26690
26691 var onIdleTimeout = function () {
26692 logger$2.log('Idle timeout reached, restarting recording.');
26693 this.resetRecording();
26694 }.bind(this);
26695
26696 var onMaxLengthReached = function () {
26697 logger$2.log('Max recording length reached, stopping recording.');
26698 this.resetRecording();
26699 }.bind(this);
26700
26701 var onBatchSent = function () {
26702 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
26703 this['__flushPromise'] = this.activeRecording.batcher._flushPromise;
26704 }.bind(this);
26705
26706 /**
26707 * @type {import('./session-recording').SessionRecordingOptions}
26708 */
26709 var sessionRecordingOptions = {
26710 mixpanelInstance: this.mixpanelInstance,
26711 onBatchSent: onBatchSent,
26712 onIdleTimeout: onIdleTimeout,
26713 onMaxLengthReached: onMaxLengthReached,
26714 replayId: _.UUID(),
26715 rrwebRecord: this.rrwebRecord,
26716 sharedLockStorage: this.sharedLockStorage
26717 };
26718
26719 if (options.activeSerializedRecording) {
26720 this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
26721 } else {
26722 this.activeRecording = new SessionRecording(sessionRecordingOptions);
26723 }
26724
26725 this.activeRecording.startRecording(options.shouldStopBatcher);
26726 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
26727 };
26728
26729 MixpanelRecorder.prototype.stopRecording = function() {
26730 // Prevents activeSerializedRecording from being reused when stopping the recording.
26731 this.stopRecordingInProgress = true;
26732 return this._stopCurrentRecording(false, true).then(function() {
26733 return this.recordingRegistry.clearActiveRecording();
26734 }.bind(this)).then(function() {
26735 this.stopRecordingInProgress = false;
26736 }.bind(this));
26737 };
26738
26739 MixpanelRecorder.prototype.pauseRecording = function() {
26740 return this._stopCurrentRecording(false);
26741 };
26742
26743 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
26744 if (this.activeRecording) {
26745 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
26746 if (disableActiveRecording) {
26747 this.activeRecording = null;
26748 }
26749 return stopRecordingPromise;
26750 }
26751 return PromisePolyfill.resolve();
26752 };
26753
26754 MixpanelRecorder.prototype.resumeRecording = function (startNewIfInactive) {
26755 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
26756 this.activeRecording.startRecording(false);
26757 return PromisePolyfill.resolve(null);
26758 }
26759
26760 return this.recordingRegistry.getActiveRecording()
26761 .then(function (activeSerializedRecording) {
26762 if (activeSerializedRecording && !this.stopRecordingInProgress) {
26763 return this.startRecording({activeSerializedRecording: activeSerializedRecording});
26764 } else if (startNewIfInactive) {
26765 return this.startRecording({shouldStopBatcher: false});
26766 } else {
26767 logger$2.log('No resumable recording found.');
26768 return null;
26769 }
26770 }.bind(this));
26771 };
26772
26773
26774 MixpanelRecorder.prototype.resetRecording = function () {
26775 this.stopRecording();
26776 this.startRecording({shouldStopBatcher: true});
26777 };
26778
26779 MixpanelRecorder.prototype.getActiveReplayId = function () {
26780 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
26781 return this.activeRecording.replayId;
26782 } else {
26783 return null;
26784 }
26785 };
26786
26787 // getter so that older mixpanel-core versions can still retrieve the replay ID
26788 // when pulling the latest recorder bundle from the CDN
26789 Object.defineProperty(MixpanelRecorder.prototype, 'replayId', {
26790 get: function () {
26791 return this.getActiveReplayId();
26792 }
26793 });
26794
26795 win['__mp_recorder'] = MixpanelRecorder;
26796
26797 // stateless utils
26798 // mostly from https://github.com/mixpanel/mixpanel-js/blob/989ada50f518edab47b9c4fd9535f9fbd5ec5fc0/src/autotrack-utils.js
26799
26800
26801 var EV_CHANGE = 'change';
26802 var EV_CLICK = 'click';
26803 var EV_HASHCHANGE = 'hashchange';
26804 var EV_INPUT = 'input';
26805 var EV_LOAD = 'load';
26806 var EV_MP_LOCATION_CHANGE = 'mp_locationchange';
26807 var EV_POPSTATE = 'popstate';
26808 // TODO scrollend isn't available in Safari: document or polyfill?
26809 var EV_SCROLLEND = 'scrollend';
26810 var EV_SCROLL = 'scroll';
26811 var EV_SELECT = 'select';
26812 var EV_SUBMIT = 'submit';
26813 var EV_TOGGLE = 'toggle';
26814 var EV_VISIBILITYCHANGE = 'visibilitychange';
26815
26816 var CLICK_EVENT_PROPS = [
26817 'clientX', 'clientY',
26818 'offsetX', 'offsetY',
26819 'pageX', 'pageY',
26820 'screenX', 'screenY',
26821 'x', 'y'
26822 ];
26823 var OPT_IN_CLASSES = ['mp-include'];
26824 var OPT_OUT_CLASSES = ['mp-no-track'];
26825 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(['mp-sensitive']);
26826 var TRACKED_ATTRS = [
26827 'aria-label', 'aria-labelledby', 'aria-describedby',
26828 'href', 'name', 'role', 'title', 'type'
26829 ];
26830
26831 var INTERACTIVE_ARIA_ROLES = {
26832 'button': true,
26833 'checkbox': true,
26834 'combobox': true,
26835 'grid': true,
26836 'link': true,
26837 'listbox': true,
26838 'menu': true,
26839 'menubar': true,
26840 'menuitem': true,
26841 'menuitemcheckbox': true,
26842 'menuitemradio': true,
26843 'navigation': true,
26844 'option': true,
26845 'radio': true,
26846 'radiogroup': true,
26847 'searchbox': true,
26848 'slider': true,
26849 'spinbutton': true,
26850 'switch': true,
26851 'tab': true,
26852 'tablist': true,
26853 'textbox': true,
26854 'tree': true,
26855 'treegrid': true,
26856 'treeitem': true
26857 };
26858
26859 var ALWAYS_NON_INTERACTIVE_TAGS = {
26860 // Document metadata
26861 'base': true,
26862 'head': true,
26863 'html': true,
26864 'link': true,
26865 'meta': true,
26866 'script': true,
26867 'style': true,
26868 'title': true,
26869 // Text formatting
26870 'br': true,
26871 'hr': true,
26872 'wbr': true,
26873 // Other
26874 'noscript': true,
26875 'picture': true,
26876 'source': true,
26877 'template': true,
26878 'track': true
26879 };
26880
26881 // Common container tags that need additional checks
26882 var TEXT_CONTAINER_TAGS = {
26883 'article': true,
26884 'div': true,
26885 'h1': true,
26886 'h2': true,
26887 'h3': true,
26888 'h4': true,
26889 'h5': true,
26890 'h6': true,
26891 'p': true,
26892 'section': true,
26893 'span': true
26894 };
26895
26896 var EVENT_HANDLER_ATTRIBUTES = [
26897 'onclick', 'onmousedown', 'onmouseup', 'onpointerdown', 'onpointerup', 'ontouchend', 'ontouchstart'
26898 ];
26899
26900 var MAX_DEPTH = 5;
26901
26902 var logger$1 = console_with_prefix('autocapture');
26903
26904
26905 function getClasses(el) {
26906 var classes = {};
26907 var classList = getClassName(el).split(' ');
26908 for (var i = 0; i < classList.length; i++) {
26909 var cls = classList[i];
26910 if (cls) {
26911 classes[cls] = true;
26912 }
26913 }
26914 return classes;
26915 }
26916
26917 /*
26918 * Get the className of an element, accounting for edge cases where element.className is an object
26919 * @param {Element} el - element to get the className of
26920 * @returns {string} the element's class
26921 */
26922 function getClassName(el) {
26923 switch(typeof el.className) {
26924 case 'string':
26925 return el.className;
26926 case 'object': // handle cases where className might be SVGAnimatedString or some other type
26927 return el.className.baseVal || el.getAttribute('class') || '';
26928 default: // future proof
26929 return '';
26930 }
26931 }
26932
26933 function getPreviousElementSibling(el) {
26934 if (el.previousElementSibling) {
26935 return el.previousElementSibling;
26936 } else {
26937 do {
26938 el = el.previousSibling;
26939 } while (el && !isElementNode(el));
26940 return el;
26941 }
26942 }
26943
26944 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
26945 var props = {
26946 '$classes': getClassName(el).split(' '),
26947 '$tag_name': el.tagName.toLowerCase()
26948 };
26949 var elId = el.id;
26950 if (elId) {
26951 props['$id'] = elId;
26952 }
26953
26954 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) {
26955 _.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
26956 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
26957 var attrVal = el.getAttribute(attr);
26958 if (shouldTrackValue(attrVal)) {
26959 props['$attr-' + attr] = attrVal;
26960 }
26961 }
26962 });
26963 }
26964
26965 var nthChild = 1;
26966 var nthOfType = 1;
26967 var currentElem = el;
26968 while (currentElem = getPreviousElementSibling(currentElem)) { // eslint-disable-line no-cond-assign
26969 nthChild++;
26970 if (currentElem.tagName === el.tagName) {
26971 nthOfType++;
26972 }
26973 }
26974 props['$nth_child'] = nthChild;
26975 props['$nth_of_type'] = nthOfType;
26976
26977 return props;
26978 }
26979
26980 function getPropsForDOMEvent(ev, config) {
26981 var allowElementCallback = config.allowElementCallback;
26982 var allowSelectors = config.allowSelectors || [];
26983 var blockAttrs = config.blockAttrs || [];
26984 var blockElementCallback = config.blockElementCallback;
26985 var blockSelectors = config.blockSelectors || [];
26986 var captureTextContent = config.captureTextContent || false;
26987 var captureExtraAttrs = config.captureExtraAttrs || [];
26988 var capturedForHeatMap = config.capturedForHeatMap || false;
26989
26990 // convert array to set every time, as the config may have changed
26991 var blockAttrsSet = {};
26992 _.each(blockAttrs, function(attr) {
26993 blockAttrsSet[attr] = true;
26994 });
26995
26996 var props = null;
26997
26998 var target = typeof ev.target === 'undefined' ? ev.srcElement : ev.target;
26999 if (isTextNode(target)) { // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
27000 target = target.parentNode;
27001 }
27002
27003 if (
27004 shouldTrackDomEvent(target, ev) &&
27005 isElementAllowed(target, ev, allowElementCallback, allowSelectors) &&
27006 !isElementBlocked(target, ev, blockElementCallback, blockSelectors)
27007 ) {
27008 var targetElementList = [target];
27009 var curEl = target;
27010 while (curEl.parentNode && !isTag(curEl, 'body')) {
27011 targetElementList.push(curEl.parentNode);
27012 curEl = curEl.parentNode;
27013 }
27014
27015 var elementsJson = [];
27016 var href, explicitNoTrack = false;
27017 _.each(targetElementList, function(el) {
27018 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
27019
27020 // if the element or a parent element is an anchor tag
27021 // include the href as a property
27022 if (!blockAttrsSet['href'] && el.tagName.toLowerCase() === 'a') {
27023 href = el.getAttribute('href');
27024 href = shouldTrackDetails && shouldTrackValue(href) && href;
27025 }
27026
27027 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) {
27028 explicitNoTrack = true;
27029 }
27030
27031 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
27032 }, this);
27033
27034 if (!explicitNoTrack) {
27035 var docElement = document$1['documentElement'];
27036 props = {
27037 '$event_type': ev.type,
27038 '$host': win.location.host,
27039 '$pathname': win.location.pathname,
27040 '$elements': elementsJson,
27041 '$el_attr__href': href,
27042 '$viewportHeight': Math.max(docElement['clientHeight'], win['innerHeight'] || 0),
27043 '$viewportWidth': Math.max(docElement['clientWidth'], win['innerWidth'] || 0),
27044 '$pageHeight': document$1['body']['offsetHeight'] || 0,
27045 '$pageWidth': document$1['body']['offsetWidth'] || 0,
27046 };
27047 _.each(captureExtraAttrs, function(attr) {
27048 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
27049 var attrVal = target.getAttribute(attr);
27050 if (shouldTrackValue(attrVal)) {
27051 props['$el_attr__' + attr] = attrVal;
27052 }
27053 }
27054 });
27055
27056 if (captureTextContent) {
27057 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
27058 if (elementText && elementText.length) {
27059 props['$el_text'] = elementText;
27060 }
27061 }
27062
27063 if (ev.type === EV_CLICK) {
27064 _.each(CLICK_EVENT_PROPS, function(prop) {
27065 if (prop in ev) {
27066 props['$' + prop] = ev[prop];
27067 }
27068 });
27069 if (capturedForHeatMap) {
27070 props['$captured_for_heatmap'] = true;
27071 }
27072 target = guessRealClickTarget(ev);
27073 }
27074 // prioritize text content from "real" click target if different from original target
27075 if (captureTextContent) {
27076 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
27077 if (elementText && elementText.length) {
27078 props['$el_text'] = elementText;
27079 }
27080 }
27081
27082 if (target) {
27083 // target may have been recalculated; check allowlists and blocklists again
27084 if (
27085 !isElementAllowed(target, ev, allowElementCallback, allowSelectors) ||
27086 isElementBlocked(target, ev, blockElementCallback, blockSelectors)
27087 ) {
27088 return null;
27089 }
27090
27091 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
27092 props['$target'] = targetProps;
27093 // pull up more props onto main event props
27094 props['$el_classes'] = targetProps['$classes'];
27095 _.extend(props, _.strip_empty_properties({
27096 '$el_id': targetProps['$id'],
27097 '$el_tag_name': targetProps['$tag_name']
27098 }));
27099 }
27100 }
27101 }
27102
27103 return props;
27104 }
27105
27106
27107 /**
27108 * Get the direct text content of an element, protecting against sensitive data collection.
27109 * Concats textContent of each of the element's text node children; this avoids potential
27110 * collection of sensitive data that could happen if we used element.textContent and the
27111 * element had sensitive child elements, since element.textContent includes child content.
27112 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
27113 * @param {Element} el - element to get the text of
27114 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
27115 * @returns {string} the element's direct text content
27116 */
27117 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
27118 var elText = '';
27119
27120 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) {
27121 _.each(el.childNodes, function(child) {
27122 if (isTextNode(child) && child.textContent) {
27123 elText += _.trim(child.textContent)
27124 // scrub potentially sensitive values
27125 .split(/(\s+)/).filter(shouldTrackValue).join('')
27126 // normalize whitespace
27127 .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
27128 // truncate
27129 .substring(0, 255);
27130 }
27131 });
27132 }
27133
27134 return _.trim(elText);
27135 }
27136
27137 function guessRealClickTarget(ev) {
27138 var target = ev.target;
27139 var composedPath = ev['composedPath']();
27140 for (var i = 0; i < composedPath.length; i++) {
27141 var node = composedPath[i];
27142 if (
27143 isTag(node, 'a') ||
27144 isTag(node, 'button') ||
27145 isTag(node, 'input') ||
27146 isTag(node, 'select') ||
27147 (node.getAttribute && node.getAttribute('role') === 'button')
27148 ) {
27149 target = node;
27150 break;
27151 }
27152 if (node === target) {
27153 break;
27154 }
27155 }
27156 return target;
27157 }
27158
27159 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
27160 if (allowElementCallback) {
27161 try {
27162 if (!allowElementCallback(el, ev)) {
27163 return false;
27164 }
27165 } catch (err) {
27166 logger$1.critical('Error while checking element in allowElementCallback', err);
27167 return false;
27168 }
27169 }
27170
27171 if (!allowSelectors.length) {
27172 // no allowlist; all elements are fair game
27173 return true;
27174 }
27175
27176 for (var i = 0; i < allowSelectors.length; i++) {
27177 var sel = allowSelectors[i];
27178 try {
27179 if (el['matches'](sel)) {
27180 return true;
27181 }
27182 } catch (err) {
27183 logger$1.critical('Error while checking selector: ' + sel, err);
27184 }
27185 }
27186 return false;
27187 }
27188
27189 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
27190 var i;
27191
27192 if (blockElementCallback) {
27193 try {
27194 if (blockElementCallback(el, ev)) {
27195 return true;
27196 }
27197 } catch (err) {
27198 logger$1.critical('Error while checking element in blockElementCallback', err);
27199 return true;
27200 }
27201 }
27202
27203 if (blockSelectors && blockSelectors.length) {
27204 // programmatically prevent tracking of elements that match CSS selectors
27205 for (i = 0; i < blockSelectors.length; i++) {
27206 var sel = blockSelectors[i];
27207 try {
27208 if (el['matches'](sel)) {
27209 return true;
27210 }
27211 } catch (err) {
27212 logger$1.critical('Error while checking selector: ' + sel, err);
27213 }
27214 }
27215 }
27216
27217 // allow users to programmatically prevent tracking of elements by adding default classes such as 'mp-no-track'
27218 var classes = getClasses(el);
27219 for (i = 0; i < OPT_OUT_CLASSES.length; i++) {
27220 if (classes[OPT_OUT_CLASSES[i]]) {
27221 return true;
27222 }
27223 }
27224
27225 return false;
27226 }
27227
27228 /*
27229 * Check whether a DOM node has nodeType Node.ELEMENT_NODE
27230 * @param {Node} node - node to check
27231 * @returns {boolean} whether node is of the correct nodeType
27232 */
27233 function isElementNode(node) {
27234 return node && node.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
27235 }
27236
27237 /*
27238 * Check whether an element is of a given tag type.
27239 * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
27240 * we want to match tagNames instead of specific references because something like
27241 * element === document.body won't always work because element might not be a native
27242 * element.
27243 * @param {Element} el - element to check
27244 * @param {string} tag - tag name (e.g., "div")
27245 * @returns {boolean} whether el is of the given tag type
27246 */
27247 function isTag(el, tag) {
27248 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
27249 }
27250
27251 /*
27252 * Check whether a DOM node is a TEXT_NODE
27253 * @param {Node} node - node to check
27254 * @returns {boolean} whether node is of type Node.TEXT_NODE
27255 */
27256 function isTextNode(node) {
27257 return node && node.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
27258 }
27259
27260 function minDOMApisSupported() {
27261 try {
27262 var testEl = document$1.createElement('div');
27263 return !!testEl['matches'];
27264 } catch (err) {
27265 return false;
27266 }
27267 }
27268
27269 function weakSetSupported() {
27270 return typeof WeakSet !== 'undefined';
27271 }
27272
27273 /*
27274 * Check whether a DOM event should be "tracked" or if it may contain sensitive data
27275 * using a variety of heuristics.
27276 * @param {Element} el - element to check
27277 * @param {Event} ev - event to check
27278 * @returns {boolean} whether the event should be tracked
27279 */
27280 function shouldTrackDomEvent(el, ev) {
27281 if (!el || isTag(el, 'html') || !isElementNode(el)) {
27282 return false;
27283 }
27284 var tag = el.tagName.toLowerCase();
27285 switch (tag) {
27286 case 'form':
27287 return ev.type === EV_SUBMIT;
27288 case 'input':
27289 if (['button', 'submit'].indexOf(el.getAttribute('type')) === -1) {
27290 return ev.type === EV_CHANGE;
27291 } else {
27292 return ev.type === EV_CLICK;
27293 }
27294 case 'select':
27295 case 'textarea':
27296 return ev.type === EV_CHANGE;
27297 default:
27298 return ev.type === EV_CLICK;
27299 }
27300 }
27301
27302 /*
27303 * Check whether a DOM element should be "tracked" or if it may contain sensitive data
27304 * using a variety of heuristics.
27305 * @param {Element} el - element to check
27306 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
27307 * @returns {boolean} whether the element should be tracked
27308 */
27309 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
27310 var i;
27311
27312 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) {
27313 return false;
27314 }
27315
27316 for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
27317 var classes = getClasses(curEl);
27318 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) {
27319 if (classes[SENSITIVE_DATA_CLASSES[i]]) {
27320 return false;
27321 }
27322 }
27323 }
27324
27325 var elClasses = getClasses(el);
27326 for (i = 0; i < OPT_IN_CLASSES.length; i++) {
27327 if (elClasses[OPT_IN_CLASSES[i]]) {
27328 return true;
27329 }
27330 }
27331
27332 // don't send data from inputs or similar elements since there will always be
27333 // a risk of clientside javascript placing sensitive data in attributes
27334 if (
27335 isTag(el, 'input') ||
27336 isTag(el, 'select') ||
27337 isTag(el, 'textarea') ||
27338 el.getAttribute('contenteditable') === 'true'
27339 ) {
27340 return false;
27341 }
27342
27343 // don't include hidden or password fields
27344 var type = el.type || '';
27345 if (typeof type === 'string') { // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
27346 switch(type.toLowerCase()) {
27347 case 'hidden':
27348 return false;
27349 case 'password':
27350 return false;
27351 }
27352 }
27353
27354 // filter out data from fields that look like sensitive fields
27355 var name = el.name || el.id || '';
27356 if (typeof name === 'string') { // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name="name"]
27357 var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
27358 if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
27359 return false;
27360 }
27361 }
27362
27363 return true;
27364 }
27365
27366
27367 /*
27368 * Check whether a string value should be "tracked" or if it may contain sensitive data
27369 * using a variety of heuristics.
27370 * @param {string} value - string value to check
27371 * @returns {boolean} whether the element should be tracked
27372 */
27373 function shouldTrackValue(value) {
27374 if (value === null || _.isUndefined(value)) {
27375 return false;
27376 }
27377
27378 if (typeof value === 'string') {
27379 value = _.trim(value);
27380
27381 // check to see if input value looks like a credit card number
27382 // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
27383 var ccRegex = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;
27384 if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
27385 return false;
27386 }
27387
27388 // check to see if input value looks like a social security number
27389 var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
27390 if (ssnRegex.test(value)) {
27391 return false;
27392 }
27393 }
27394
27395 return true;
27396 }
27397
27398 /**
27399 * Creates a cross-browser compatible scroll end function with appropriate event listener.
27400 * For browsers that support scrollend, returns the original function with scrollend event.
27401 * For browsers without scrollend support, returns a debounced function that triggers
27402 * 100ms after the last scroll event to simulate scrollend behavior.
27403 * @param {Function} originalFunction - The function to call when scrolling ends
27404 * @returns {Object} Object containing listener function and eventType string
27405 * @returns {Function} returns.listener - The wrapped function to use as event listener
27406 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
27407 */
27408 function getPolyfillScrollEndFunction(originalFunction) {
27409 var supportsScrollEnd = 'onscrollend' in win;
27410 var polyfillFunction = safewrap(originalFunction);
27411 var polyfillEvent = EV_SCROLLEND;
27412 if (!supportsScrollEnd) {
27413 // Polyfill for browsers without scrollend support: wait 100ms after the last scroll event
27414 // https://developer.chrome.com/blog/scrollend-a-new-javascript-event
27415 var scrollTimer = null;
27416 var scrollDelayMs = 100;
27417
27418 polyfillFunction = safewrap(function() {
27419 clearTimeout(scrollTimer);
27420 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
27421 });
27422
27423 polyfillEvent = EV_SCROLL;
27424 }
27425
27426 return {
27427 listener: polyfillFunction,
27428 eventType: polyfillEvent
27429 };
27430 }
27431
27432 function hasInlineEventHandlers(element) {
27433 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) {
27434 if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) {
27435 return true;
27436 }
27437 }
27438 return false;
27439 }
27440
27441 function hasInteractiveAriaRole(element) {
27442 var role = element.getAttribute('role');
27443 if (!role) return false;
27444
27445 // Handle invalid markup where multiple roles might be specified
27446 // Only the first token is recognized per ARIA spec
27447 var primaryRole = role.trim().split(/\s+/)[0].toLowerCase();
27448
27449 return INTERACTIVE_ARIA_ROLES[primaryRole];
27450 }
27451
27452 function hasAnyInteractivityIndicators(element) {
27453 var tagName = element.tagName.toLowerCase();
27454
27455 // Check for interactive HTML elements
27456 if (tagName === 'button' ||
27457 tagName === 'input' ||
27458 tagName === 'select' ||
27459 tagName === 'textarea' ||
27460 tagName === 'details' ||
27461 tagName === 'dialog') {
27462 return true;
27463 }
27464
27465 if (element.isContentEditable) {
27466 return true;
27467 }
27468
27469 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) {
27470 return true;
27471 }
27472
27473 if (hasInlineEventHandlers(element)) {
27474 return true;
27475 }
27476
27477 if (hasInteractiveAriaRole(element)) {
27478 return true;
27479 }
27480
27481 if (tagName === 'a' && element.hasAttribute('href')) {
27482 return true;
27483 }
27484
27485 if (element.hasAttribute('tabindex')) {
27486 return true;
27487 }
27488
27489 return false;
27490 }
27491
27492
27493 function isDefinitelyNonInteractive(element) {
27494 if (!element || !element.tagName) {
27495 return true;
27496 }
27497
27498 var tagName = element.tagName.toLowerCase();
27499
27500 // These tags are definitely non-interactive
27501 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) {
27502 return true;
27503 }
27504
27505 // For all other elements, we can only be certain they're non-interactive if they lack ALL indicators of interactivity
27506 // Check for any signs of interactivity
27507 if (hasAnyInteractivityIndicators(element)) {
27508 return false;
27509 }
27510
27511 // Check parent chain for interactive context
27512 var parent = element.parentElement;
27513 var depth = 0;
27514
27515 while (parent && depth < MAX_DEPTH) {
27516 if (hasAnyInteractivityIndicators(parent)) {
27517 return false; // Element is inside an interactive parent
27518 }
27519
27520 if (parent.getRootNode && parent.getRootNode() !== document$1) {
27521 var root = parent.getRootNode();
27522 if (root.host && hasAnyInteractivityIndicators(root.host)) {
27523 return false; // Inside an interactive shadow host
27524 }
27525 }
27526
27527 parent = parent.parentElement;
27528 depth++;
27529 }
27530
27531 // Pure text containers without any interactive context
27532 if (TEXT_CONTAINER_TAGS[tagName]) {
27533 // These are non-interactive ONLY if they have no interactive indicators (already checked as part of hasAnyInteractivityIndicators)
27534 return true;
27535 }
27536
27537 // Default: we can't be certain it's non-interactive
27538 return false;
27539 }
27540
27541 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
27542 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1000;
27543 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
27544
27545 function RageClickTracker() {
27546 this.clicks = [];
27547 }
27548
27549 RageClickTracker.prototype.isRageClick = function(x, y, options) {
27550 options = options || {};
27551 var thresholdPx = options['threshold_px'] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
27552 var timeoutMs = options['timeout_ms'] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
27553 var clickCount = options['click_count'] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
27554 var timestamp = Date.now();
27555
27556 var lastClick = this.clicks[this.clicks.length - 1];
27557 if (
27558 lastClick &&
27559 timestamp - lastClick.timestamp < timeoutMs &&
27560 Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx
27561 ) {
27562 this.clicks.push({ x: x, y: y, timestamp: timestamp });
27563 if (this.clicks.length >= clickCount) {
27564 this.clicks = [];
27565 return true;
27566 }
27567 } else {
27568 this.clicks = [{ x: x, y: y, timestamp: timestamp }];
27569 }
27570 return false;
27571 };
27572
27573 function ShadowDOMObserver(changeCallback, observerConfig) {
27574 this.changeCallback = changeCallback || function() {};
27575 this.observerConfig = observerConfig;
27576
27577 this.observedShadowRoots = null;
27578 this.shadowObservers = [];
27579 }
27580
27581 ShadowDOMObserver.prototype.getEventTarget = function(event) {
27582 if (!this.observedShadowRoots) {
27583 return;
27584 }
27585 var path = this.getComposedPath(event);
27586 if (path && path.length) {
27587 return path[0];
27588 }
27589
27590 return event['target'] || event['srcElement'];
27591 };
27592
27593
27594 ShadowDOMObserver.prototype.getComposedPath = function(event) {
27595 if ('composedPath' in event) {
27596 return event['composedPath']();
27597 }
27598
27599 return [];
27600 };
27601 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
27602 if (!this.observedShadowRoots) {
27603 return;
27604 }
27605
27606 var path = this.getComposedPath(event);
27607
27608 // Check each element in path for shadow roots
27609 for (var i = 0; i < path.length; i++) {
27610 var element = path[i];
27611
27612 if (element && element.shadowRoot) {
27613 this.observeShadowRoot(element.shadowRoot);
27614 }
27615 }
27616 };
27617
27618
27619 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
27620 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) {
27621 return;
27622 }
27623
27624 var self = this;
27625
27626 try {
27627 this.observedShadowRoots.add(shadowRoot);
27628
27629 var observer = new window.MutationObserver(function() {
27630 self.changeCallback();
27631 });
27632
27633 observer.observe(shadowRoot, this.observerConfig);
27634 this.shadowObservers.push(observer);
27635 } catch (e) {
27636 logger$1.critical('Error while observing shadow root', e);
27637 }
27638 };
27639
27640
27641 ShadowDOMObserver.prototype.start = function() {
27642 if (this.observedShadowRoots) {
27643 return;
27644 }
27645
27646 if (!weakSetSupported()) {
27647 logger$1.critical('Shadow DOM observation unavailable: WeakSet not supported');
27648 return;
27649 }
27650
27651 this.observedShadowRoots = new WeakSet();
27652 };
27653
27654 ShadowDOMObserver.prototype.stop = function() {
27655 if (!this.observedShadowRoots) {
27656 return;
27657 }
27658
27659 for (var i = 0; i < this.shadowObservers.length; i++) {
27660 try {
27661 this.shadowObservers[i].disconnect();
27662 } catch (e) {
27663 logger$1.critical('Error while disconnecting shadow DOM observer', e);
27664 }
27665 }
27666 this.shadowObservers = [];
27667 this.observedShadowRoots = null;
27668 };
27669
27670 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
27671 /** @const */ var INTERACTION_EVENTS = [EV_CHANGE, EV_INPUT, EV_SUBMIT, EV_SELECT, EV_TOGGLE];
27672 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
27673 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
27674 /** @const */ var MUTATION_OBSERVER_CONFIG = {
27675 characterData: true,
27676 childList: true,
27677 subtree: true,
27678 attributes: true,
27679 attributeFilter: ['style', 'class', 'hidden', 'checked', 'selected', 'value', 'display', 'visibility']
27680 };
27681
27682
27683 function DeadClickTracker(onDeadClickCallback) {
27684 this.eventListeners = [];
27685 this.mutationObserver = null;
27686 this.shadowDOMObserver = null;
27687
27688 this.isTracking = false;
27689 this.lastChangeEventTimestamp = 0;
27690 this.pendingClicks = [];
27691 this.onDeadClickCallback = onDeadClickCallback;
27692 this.processingActive = false;
27693 this.processingTimeout = null;
27694 }
27695
27696
27697 DeadClickTracker.prototype.addClick = function(event) {
27698 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
27699
27700 if (!element) {
27701 element = event['target'] || event['srcElement'];
27702 }
27703
27704 if (!element || isDefinitelyNonInteractive(element)) {
27705 return false;
27706 }
27707
27708 if (this.shadowDOMObserver) {
27709 this.shadowDOMObserver.observeFromEvent(event);
27710 }
27711 this.pendingClicks.push({
27712 element: element,
27713 event: event,
27714 timestamp: Date.now()
27715 });
27716 return true;
27717 };
27718
27719 DeadClickTracker.prototype.trackClick = function(event, config) {
27720 if (!this.isTracking) {
27721 return false;
27722 }
27723
27724 var added = this.addClick(event);
27725 if (added) {
27726 this.triggerProcessing(config);
27727 }
27728 return added;
27729 };
27730
27731 DeadClickTracker.prototype.getDeadClicks = function(config) {
27732 if (this.pendingClicks.length === 0) {
27733 return [];
27734 }
27735
27736 var timeoutMs = config['timeout_ms'];
27737 var now = Date.now();
27738 var clicksToEvaluate = this.pendingClicks.slice(); // Copy array
27739 this.pendingClicks = []; // Clear original
27740
27741 var deadClicks = [];
27742
27743 for (var i = 0; i < clicksToEvaluate.length; i++) {
27744 var click = clicksToEvaluate[i];
27745
27746 if (now - click.timestamp >= timeoutMs) {
27747 // Click has exceeded timeout, check if it's dead by looking for changes after this specific click
27748 if (!this.hasChangesAfter(click.timestamp)) {
27749 deadClicks.push(click);
27750 }
27751 } else {
27752 // Still pending - add back
27753 this.pendingClicks.push(click);
27754 }
27755 }
27756
27757 return deadClicks;
27758 };
27759
27760 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
27761 // 100ms tolerance for race condition between when we record the click and the change event
27762 return this.lastChangeEventTimestamp >= (timestamp - 100);
27763 };
27764
27765 DeadClickTracker.prototype.recordChangeEvent = function() {
27766 this.lastChangeEventTimestamp = Date.now();
27767 };
27768
27769 DeadClickTracker.prototype.triggerProcessing = function(config) {
27770 // Prevent multiple concurrent processing chains
27771 if (this.processingActive) {
27772 return;
27773 }
27774 this.processingActive = true;
27775 this.processRecursively(config);
27776 };
27777
27778 DeadClickTracker.prototype.processRecursively = function(config) {
27779 if (!this.isTracking || !this.onDeadClickCallback) {
27780 this.processingActive = false;
27781 return;
27782 }
27783
27784 var timeoutMs = config['timeout_ms'];
27785 var self = this;
27786
27787 this.processingTimeout = setTimeout(function() {
27788 if (!self.processingActive) {
27789 return;
27790 }
27791
27792 var deadClicks = self.getDeadClicks(config);
27793
27794 for (var i = 0; i < deadClicks.length; i++) {
27795 self.onDeadClickCallback(deadClicks[i].event);
27796 }
27797
27798 if (self.pendingClicks.length > 0) {
27799 self.processRecursively(config);
27800 } else {
27801 self.processingActive = false;
27802 }
27803 }, timeoutMs);
27804 };
27805
27806 DeadClickTracker.prototype.startTracking = function() {
27807 if (this.isTracking) {
27808 return;
27809 }
27810
27811 this.isTracking = true;
27812
27813 var self = this;
27814
27815 INTERACTION_EVENTS.forEach(function(event) {
27816 var handler = function() {
27817 self.recordChangeEvent();
27818 };
27819 document.addEventListener(event, handler, { capture: true, passive: true });
27820 self.eventListeners.push({ target: document, event: event, handler: handler, options: { capture: true, passive: true } });
27821 });
27822 NAVIGATION_EVENTS.forEach(function(event) {
27823 var handler = function() {
27824 self.recordChangeEvent();
27825 };
27826 window.addEventListener(event, handler);
27827 self.eventListeners.push({ target: window, event: event, handler: handler });
27828 });
27829 LAYOUT_EVENTS.forEach(function(event) {
27830 var handler = function() {
27831 self.recordChangeEvent();
27832 };
27833 window.addEventListener(event, handler, { passive: true });
27834 self.eventListeners.push({ target: window, event: event, handler: handler, options: { passive: true } });
27835 });
27836 var selectionHandler = function() {
27837 self.recordChangeEvent();
27838 };
27839 document.addEventListener('selectionchange', selectionHandler);
27840 self.eventListeners.push({ target: document, event: 'selectionchange', handler: selectionHandler });
27841
27842 // Set up MutationObserver
27843 if (window.MutationObserver) {
27844 try {
27845 this.mutationObserver = new window.MutationObserver(function() {
27846 self.recordChangeEvent();
27847 });
27848
27849 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
27850 } catch (e) {
27851 logger$1.critical('Error while setting up mutation observer', e);
27852 }
27853 }
27854
27855 // Set up Shadow DOM observer
27856 if (window.customElements) {
27857 try {
27858 this.shadowDOMObserver = new ShadowDOMObserver(
27859 function() {
27860 self.recordChangeEvent();
27861 },
27862 MUTATION_OBSERVER_CONFIG
27863 );
27864 this.shadowDOMObserver.start();
27865 } catch (e) {
27866 logger$1.critical('Error while setting up shadow DOM observer', e);
27867 this.shadowDOMObserver = null;
27868 }
27869 }
27870 };
27871
27872 DeadClickTracker.prototype.stopTracking = function() {
27873 if (!this.isTracking) {
27874 return;
27875 }
27876
27877 this.isTracking = false;
27878 this.pendingClicks = [];
27879 this.lastChangeEventTimestamp = 0;
27880 this.processingActive = false;
27881
27882 if (this.processingTimeout) {
27883 clearTimeout(this.processingTimeout);
27884 this.processingTimeout = null;
27885 }
27886
27887 // Remove all event listeners
27888 for (var i = 0; i < this.eventListeners.length; i++) {
27889 var listener = this.eventListeners[i];
27890 try {
27891 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
27892 } catch (e) {
27893 logger$1.critical('Error while removing event listener', e);
27894 }
27895 }
27896 this.eventListeners = [];
27897
27898 if (this.mutationObserver) {
27899 try {
27900 this.mutationObserver.disconnect();
27901 } catch (e) {
27902 logger$1.critical('Error while disconnecting mutation observer', e);
27903 }
27904 this.mutationObserver = null;
27905 }
27906
27907 if (this.shadowDOMObserver) {
27908 try {
27909 this.shadowDOMObserver.stop();
27910 } catch (e) {
27911 logger$1.critical('Error while stopping shadow DOM observer', e);
27912 }
27913 this.shadowDOMObserver = null;
27914 }
27915 };
27916
27917 var AUTOCAPTURE_CONFIG_KEY = 'autocapture';
27918 var LEGACY_PAGEVIEW_CONFIG_KEY = 'track_pageview';
27919
27920 var PAGEVIEW_OPTION_FULL_URL = 'full-url';
27921 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = 'url-with-path-and-query-string';
27922 var PAGEVIEW_OPTION_URL_WITH_PATH = 'url-with-path';
27923
27924 var CONFIG_ALLOW_ELEMENT_CALLBACK = 'allow_element_callback';
27925 var CONFIG_ALLOW_SELECTORS = 'allow_selectors';
27926 var CONFIG_ALLOW_URL_REGEXES = 'allow_url_regexes';
27927 var CONFIG_BLOCK_ATTRS = 'block_attrs';
27928 var CONFIG_BLOCK_ELEMENT_CALLBACK = 'block_element_callback';
27929 var CONFIG_BLOCK_SELECTORS = 'block_selectors';
27930 var CONFIG_BLOCK_URL_REGEXES = 'block_url_regexes';
27931 var CONFIG_CAPTURE_EXTRA_ATTRS = 'capture_extra_attrs';
27932 var CONFIG_CAPTURE_TEXT_CONTENT = 'capture_text_content';
27933 var CONFIG_SCROLL_CAPTURE_ALL = 'scroll_capture_all';
27934 var CONFIG_SCROLL_CHECKPOINTS = 'scroll_depth_percent_checkpoints';
27935 var CONFIG_TRACK_CLICK = 'click';
27936 var CONFIG_TRACK_DEAD_CLICK = 'dead_click';
27937 var CONFIG_TRACK_INPUT = 'input';
27938 var CONFIG_TRACK_PAGEVIEW = 'pageview';
27939 var CONFIG_TRACK_RAGE_CLICK = 'rage_click';
27940 var CONFIG_TRACK_SCROLL = 'scroll';
27941 var CONFIG_TRACK_PAGE_LEAVE = 'page_leave';
27942 var CONFIG_TRACK_SUBMIT = 'submit';
27943
27944 var CONFIG_DEFAULTS$1 = {};
27945 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
27946 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
27947 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
27948 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
27949 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
27950 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
27951 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
27952 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
27953 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
27954 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [25, 50, 75, 100];
27955 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
27956 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
27957 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
27958 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
27959 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
27960 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
27961 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
27962 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
27963
27964 var DEFAULT_PROPS = {
27965 '$mp_autocapture': true
27966 };
27967
27968 var MP_EV_CLICK = '$mp_click';
27969 var MP_EV_DEAD_CLICK = '$mp_dead_click';
27970 var MP_EV_INPUT = '$mp_input_change';
27971 var MP_EV_RAGE_CLICK = '$mp_rage_click';
27972 var MP_EV_SCROLL = '$mp_scroll';
27973 var MP_EV_SUBMIT = '$mp_submit';
27974 var MP_EV_PAGE_LEAVE = '$mp_page_leave';
27975
27976 /**
27977 * Autocapture: manages automatic event tracking
27978 * @constructor
27979 */
27980 var Autocapture = function(mp) {
27981 this.mp = mp;
27982 this.maxScrollViewDepth = 0;
27983 this.hasTrackedScrollSession = false;
27984 this.previousScrollHeight = 0;
27985 };
27986
27987 Autocapture.prototype.init = function() {
27988 if (!minDOMApisSupported()) {
27989 logger$1.critical('Autocapture unavailable: missing required DOM APIs');
27990 return;
27991 }
27992 this.initPageListeners();
27993 this.initPageviewTracking();
27994 this.initClickTracking();
27995 this.initDeadClickTracking();
27996 this.initInputTracking();
27997 this.initScrollTracking();
27998 this.initSubmitTracking();
27999 this.initRageClickTracking();
28000 this.initPageLeaveTracking();
28001 };
28002
28003 Autocapture.prototype.getFullConfig = function() {
28004 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
28005 if (!autocaptureConfig) {
28006 // Autocapture is completely off
28007 return {};
28008 } else if (_.isObject(autocaptureConfig)) {
28009 return _.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
28010 } else {
28011 // Autocapture config is non-object truthy value, return default
28012 return CONFIG_DEFAULTS$1;
28013 }
28014 };
28015
28016 Autocapture.prototype.getConfig = function(key) {
28017 return this.getFullConfig()[key];
28018 };
28019
28020 Autocapture.prototype.currentUrlBlocked = function() {
28021 var i;
28022 var currentUrl = _.info.currentUrl();
28023
28024 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
28025 if (allowUrlRegexes.length) {
28026 // we're using an allowlist, only track if current URL matches
28027 var allowed = false;
28028 for (i = 0; i < allowUrlRegexes.length; i++) {
28029 var allowRegex = allowUrlRegexes[i];
28030 try {
28031 if (currentUrl.match(allowRegex)) {
28032 allowed = true;
28033 break;
28034 }
28035 } catch (err) {
28036 logger$1.critical('Error while checking block URL regex: ' + allowRegex, err);
28037 return true;
28038 }
28039 }
28040 if (!allowed) {
28041 // wasn't allowed by any regex
28042 return true;
28043 }
28044 }
28045
28046 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
28047 if (!blockUrlRegexes || !blockUrlRegexes.length) {
28048 return false;
28049 }
28050
28051 for (i = 0; i < blockUrlRegexes.length; i++) {
28052 try {
28053 if (currentUrl.match(blockUrlRegexes[i])) {
28054 return true;
28055 }
28056 } catch (err) {
28057 logger$1.critical('Error while checking block URL regex: ' + blockUrlRegexes[i], err);
28058 return true;
28059 }
28060 }
28061 return false;
28062 };
28063
28064 Autocapture.prototype.pageviewTrackingConfig = function() {
28065 // supports both autocapture config and old track_pageview config
28066 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) {
28067 return this.getConfig(CONFIG_TRACK_PAGEVIEW);
28068 } else {
28069 return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
28070 }
28071 };
28072
28073 // helper for event handlers
28074 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
28075 if (this.currentUrlBlocked()) {
28076 return;
28077 }
28078
28079 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (
28080 (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK)) ||
28081 (mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK)) ||
28082 (mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK))
28083 );
28084
28085 var props = getPropsForDOMEvent(ev, {
28086 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
28087 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
28088 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
28089 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
28090 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
28091 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
28092 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
28093 capturedForHeatMap: isCapturedForHeatMap,
28094 });
28095 if (props) {
28096 _.extend(props, DEFAULT_PROPS);
28097 this.mp.track(mpEventName, props);
28098 }
28099 };
28100
28101 Autocapture.prototype.initPageListeners = function() {
28102 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
28103 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
28104
28105 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
28106 // These are all the configs that use these listeners
28107 return;
28108 }
28109
28110 this.listenerPopstate = function() {
28111 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28112 };
28113 this.listenerHashchange = function() {
28114 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28115 };
28116
28117 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
28118 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
28119 var nativePushState = win.history.pushState;
28120 if (typeof nativePushState === 'function') {
28121 win.history.pushState = function(state, unused, url) {
28122 nativePushState.call(win.history, state, unused, url);
28123 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28124 };
28125 }
28126 var nativeReplaceState = win.history.replaceState;
28127 if (typeof nativeReplaceState === 'function') {
28128 win.history.replaceState = function(state, unused, url) {
28129 nativeReplaceState.call(win.history, state, unused, url);
28130 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28131 };
28132 }
28133 };
28134
28135 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
28136 var config = this.getConfig(configKey);
28137
28138 if (!config) {
28139 return null; // click tracking disabled
28140 }
28141
28142 if (config === true) {
28143 return {}; // use defaults
28144 }
28145
28146 if (typeof config === 'object') {
28147 return config; // use custom configuration
28148 }
28149
28150 return {}; // fallback to defaults for any other truthy value
28151 };
28152
28153 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
28154 if (this.hasTrackedScrollSession) {
28155 // User has navigated away already ending their impression.
28156 return;
28157 }
28158
28159 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) {
28160 return;
28161 }
28162
28163 this.hasTrackedScrollSession = true;
28164 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28165 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
28166 var foldLinePercentage = Math.round((viewportHeight / currentScrollHeight) * 100);
28167 if (currentScrollHeight <= viewportHeight) {
28168 // If the content fits within the viewport, consider it fully scrolled
28169 scrollPercentage = 100;
28170 foldLinePercentage = 100;
28171 }
28172
28173 var props = _.extend({
28174 '$max_scroll_view_depth': this.maxScrollViewDepth,
28175 '$max_scroll_percentage': scrollPercentage,
28176 '$fold_line_percentage': foldLinePercentage,
28177 '$scroll_height': currentScrollHeight,
28178 '$event_type': ev.type,
28179 '$current_url': currentUrl || _.info.currentUrl(),
28180 '$viewportHeight': viewportHeight, // This is the fold line
28181 '$viewportWidth': Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
28182 '$captured_for_heatmap': this.mp.is_recording_heatmap_data()
28183 }, DEFAULT_PROPS);
28184
28185 // Send with beacon transport to ensure event is sent before unload
28186 this.mp.track(MP_EV_PAGE_LEAVE, props, {transport: 'sendBeacon'});
28187 };
28188
28189 Autocapture.prototype._initScrollDepthTracking = function() {
28190 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
28191 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
28192
28193 if (!this.mp.get_config('record_heatmap_data')) {
28194 return;
28195 }
28196
28197 logger$1.log('Initializing scroll depth tracking');
28198
28199 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28200
28201 var updateScrollDepth = function() {
28202 if (this.currentUrlBlocked()) {
28203 return;
28204 }
28205 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
28206 if (scrollViewHeight > this.maxScrollViewDepth) {
28207 this.maxScrollViewDepth = scrollViewHeight;
28208 }
28209 this.previousScrollHeight = document$1.body.scrollHeight;
28210 }.bind(this);
28211
28212 var scrollEndPolyfill = getPolyfillScrollEndFunction(updateScrollDepth);
28213 this.listenerScrollDepth = scrollEndPolyfill.listener;
28214 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
28215 };
28216
28217 Autocapture.prototype.initClickTracking = function() {
28218 win.removeEventListener(EV_CLICK, this.listenerClick);
28219
28220 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config('record_heatmap_data')) {
28221 return;
28222 }
28223 logger$1.log('Initializing click tracking');
28224
28225 this.listenerClick = function(ev) {
28226 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) {
28227 return;
28228 }
28229 this.trackDomEvent(ev, MP_EV_CLICK);
28230 }.bind(this);
28231 win.addEventListener(EV_CLICK, this.listenerClick);
28232 };
28233
28234 Autocapture.prototype.initDeadClickTracking = function() {
28235 var deadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
28236
28237 if (!deadClickConfig && !this.mp.get_config('record_heatmap_data')) {
28238 this.stopDeadClickTracking();
28239 return;
28240 }
28241
28242 logger$1.log('Initializing dead click tracking');
28243 if (!this._deadClickTracker) {
28244 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
28245 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
28246 }.bind(this));
28247 this._deadClickTracker.startTracking();
28248 }
28249
28250 if (!this.listenerDeadClick) {
28251 this.listenerDeadClick = function(ev) {
28252 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
28253 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) {
28254 return;
28255 }
28256 if (this.currentUrlBlocked()) {
28257 return;
28258 }
28259 // Normalize config to ensure timeout_ms is always set
28260 var normalizedConfig = currentDeadClickConfig || {};
28261 if (!normalizedConfig['timeout_ms']) {
28262 normalizedConfig['timeout_ms'] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
28263 }
28264 this._deadClickTracker.trackClick(ev, normalizedConfig);
28265 }.bind(this);
28266 win.addEventListener(EV_CLICK, this.listenerDeadClick);
28267 }
28268 };
28269
28270 Autocapture.prototype.initInputTracking = function() {
28271 win.removeEventListener(EV_CHANGE, this.listenerChange);
28272
28273 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
28274 return;
28275 }
28276 logger$1.log('Initializing input tracking');
28277
28278 this.listenerChange = function(ev) {
28279 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
28280 return;
28281 }
28282 this.trackDomEvent(ev, MP_EV_INPUT);
28283 }.bind(this);
28284 win.addEventListener(EV_CHANGE, this.listenerChange);
28285 };
28286
28287 Autocapture.prototype.initPageviewTracking = function() {
28288 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
28289
28290 if (!this.pageviewTrackingConfig()) {
28291 return;
28292 }
28293 logger$1.log('Initializing pageview tracking');
28294
28295 var previousTrackedUrl = '';
28296 var tracked = false;
28297 if (!this.currentUrlBlocked()) {
28298 tracked = this.mp.track_pageview(DEFAULT_PROPS);
28299 }
28300 if (tracked) {
28301 previousTrackedUrl = _.info.currentUrl();
28302 }
28303
28304 this.listenerLocationchange = safewrap(function() {
28305 if (this.currentUrlBlocked()) {
28306 return;
28307 }
28308
28309 var currentUrl = _.info.currentUrl();
28310 var shouldTrack = false;
28311 var didPathChange = currentUrl.split('#')[0].split('?')[0] !== previousTrackedUrl.split('#')[0].split('?')[0];
28312 var trackPageviewOption = this.pageviewTrackingConfig();
28313 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) {
28314 shouldTrack = currentUrl !== previousTrackedUrl;
28315 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) {
28316 shouldTrack = currentUrl.split('#')[0] !== previousTrackedUrl.split('#')[0];
28317 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) {
28318 shouldTrack = didPathChange;
28319 }
28320
28321 if (shouldTrack) {
28322 var tracked = this.mp.track_pageview(DEFAULT_PROPS);
28323 if (tracked) {
28324 previousTrackedUrl = currentUrl;
28325 }
28326 if (didPathChange) {
28327 this.lastScrollCheckpoint = 0;
28328 logger$1.log('Path change: re-initializing scroll depth checkpoints');
28329 }
28330 }
28331 }.bind(this));
28332 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
28333 };
28334
28335 Autocapture.prototype.initRageClickTracking = function() {
28336 win.removeEventListener(EV_CLICK, this.listenerRageClick);
28337
28338 var rageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
28339 if (!rageClickConfig && !this.mp.get_config('record_heatmap_data')) {
28340 return;
28341 }
28342
28343 logger$1.log('Initializing rage click tracking');
28344 if (!this._rageClickTracker) {
28345 this._rageClickTracker = new RageClickTracker();
28346 }
28347
28348 this.listenerRageClick = function(ev) {
28349 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
28350 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) {
28351 return;
28352 }
28353
28354 if (this.currentUrlBlocked()) {
28355 return;
28356 }
28357
28358 if (this._rageClickTracker.isRageClick(ev['pageX'], ev['pageY'], currentRageClickConfig)) {
28359 this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
28360 }
28361 }.bind(this);
28362 win.addEventListener(EV_CLICK, this.listenerRageClick);
28363 };
28364
28365 Autocapture.prototype.initScrollTracking = function() {
28366 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
28367 win.removeEventListener(EV_SCROLL, this.listenerScroll);
28368
28369
28370 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
28371 return;
28372 }
28373 logger$1.log('Initializing scroll tracking');
28374 this.lastScrollCheckpoint = 0;
28375
28376 var scrollTrackFunction = function() {
28377 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
28378 return;
28379 }
28380 if (this.currentUrlBlocked()) {
28381 return;
28382 }
28383
28384 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
28385 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || [])
28386 .slice()
28387 .sort(function(a, b) { return a - b; });
28388
28389 var scrollTop = win.scrollY;
28390 var props = _.extend({'$scroll_top': scrollTop}, DEFAULT_PROPS);
28391 try {
28392 var scrollHeight = document$1.body.scrollHeight;
28393 var scrollPercentage = Math.round((scrollTop / (scrollHeight - win.innerHeight)) * 100);
28394 props['$scroll_height'] = scrollHeight;
28395 props['$scroll_percentage'] = scrollPercentage;
28396 if (scrollPercentage > this.lastScrollCheckpoint) {
28397 for (var i = 0; i < scrollCheckpoints.length; i++) {
28398 var checkpoint = scrollCheckpoints[i];
28399 if (
28400 scrollPercentage >= checkpoint &&
28401 this.lastScrollCheckpoint < checkpoint
28402 ) {
28403 props['$scroll_checkpoint'] = checkpoint;
28404 this.lastScrollCheckpoint = checkpoint;
28405 shouldTrack = true;
28406 }
28407 }
28408 }
28409 } catch (err) {
28410 logger$1.critical('Error while calculating scroll percentage', err);
28411 }
28412 if (shouldTrack) {
28413 this.mp.track(MP_EV_SCROLL, props);
28414 }
28415 }.bind(this);
28416
28417 var scrollEndPolyfill = getPolyfillScrollEndFunction(scrollTrackFunction);
28418 this.listenerScroll = scrollEndPolyfill.listener;
28419 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
28420 };
28421
28422 Autocapture.prototype.initSubmitTracking = function() {
28423 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
28424
28425 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
28426 return;
28427 }
28428 logger$1.log('Initializing submit tracking');
28429
28430 this.listenerSubmit = function(ev) {
28431 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
28432 return;
28433 }
28434 this.trackDomEvent(ev, MP_EV_SUBMIT);
28435 }.bind(this);
28436 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
28437 };
28438
28439 Autocapture.prototype.initPageLeaveTracking = function() {
28440 // Capture page_leave both when the user navigates away from the page (visibilitychange) as well
28441 // as when they navigate to a different page within the SPA (popstate/pushstate/hashchange).
28442 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
28443 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
28444 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
28445
28446 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
28447 return;
28448 }
28449
28450 logger$1.log('Initializing page visibility tracking.');
28451 this._initScrollDepthTracking();
28452 var previousTrackedUrl = _.info.currentUrl();
28453
28454 // Initialize previousScrollHeight on `load` which handles async loading
28455 // https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
28456 this.listenerPageLoad = function() {
28457 this.previousScrollHeight = document$1.body.scrollHeight;
28458 }.bind(this);
28459 win.addEventListener(EV_LOAD, this.listenerPageLoad);
28460
28461 // Track page navigation events similar to how initPageviewTracking does it
28462 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
28463 if (this.currentUrlBlocked()) {
28464 return;
28465 }
28466
28467 var currentUrl = _.info.currentUrl();
28468 // Track all URL changes including query string or fragment changes as separate scroll sessions
28469 var shouldTrack = currentUrl !== previousTrackedUrl;
28470
28471 if (shouldTrack) {
28472 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
28473 previousTrackedUrl = currentUrl;
28474 // Fragment navigation should call scroll(end) and trigger listener, don't add window.scrollY here.
28475 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28476 this.previousScrollHeight = document$1.body.scrollHeight;
28477 this.hasTrackedScrollSession = false;
28478 }
28479 }.bind(this));
28480 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
28481
28482 this.listenerPageLeaveVisibilitychange = function(ev) {
28483 if (document$1.hidden) {
28484 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
28485 }
28486 }.bind(this);
28487 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
28488 };
28489
28490 Autocapture.prototype.stopDeadClickTracking = function() {
28491 if (this.listenerDeadClick) {
28492 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
28493 this.listenerDeadClick = null;
28494 }
28495
28496 if (this._deadClickTracker) {
28497 this._deadClickTracker.stopTracking();
28498 this._deadClickTracker = null;
28499 }
28500 };
28501
28502 // TODO integrate error_reporter from mixpanel instance
28503 safewrapClass(Autocapture);
28504
28505 var logger = console_with_prefix('flags');
28506
28507 var FLAGS_CONFIG_KEY = 'flags';
28508
28509 var CONFIG_CONTEXT = 'context';
28510 var CONFIG_DEFAULTS = {};
28511 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
28512
28513 /**
28514 * FeatureFlagManager: support for Mixpanel's feature flagging product
28515 * @constructor
28516 */
28517 var FeatureFlagManager = function(initOptions) {
28518 this.fetch = win['fetch'];
28519 this.getFullApiRoute = initOptions.getFullApiRoute;
28520 this.getMpConfig = initOptions.getConfigFunc;
28521 this.setMpConfig = initOptions.setConfigFunc;
28522 this.getMpProperty = initOptions.getPropertyFunc;
28523 this.track = initOptions.trackingFunc;
28524 };
28525
28526 FeatureFlagManager.prototype.init = function() {
28527 if (!this.minApisSupported()) {
28528 logger.critical('Feature Flags unavailable: missing minimum required APIs');
28529 return;
28530 }
28531
28532 this.flags = null;
28533 this.fetchFlags();
28534
28535 this.trackedFeatures = new Set();
28536 };
28537
28538 FeatureFlagManager.prototype.getFullConfig = function() {
28539 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
28540 if (!ffConfig) {
28541 // flags are completely off
28542 return {};
28543 } else if (_.isObject(ffConfig)) {
28544 return _.extend({}, CONFIG_DEFAULTS, ffConfig);
28545 } else {
28546 // config is non-object truthy value, return default
28547 return CONFIG_DEFAULTS;
28548 }
28549 };
28550
28551 FeatureFlagManager.prototype.getConfig = function(key) {
28552 return this.getFullConfig()[key];
28553 };
28554
28555 FeatureFlagManager.prototype.isSystemEnabled = function() {
28556 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
28557 };
28558
28559 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
28560 if (!this.isSystemEnabled()) {
28561 logger.critical('Feature Flags not enabled, cannot update context');
28562 return Promise.resolve();
28563 }
28564
28565 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
28566 if (!_.isObject(ffConfig)) {
28567 ffConfig = {};
28568 }
28569 var oldContext = (options && options['replace']) ? {} : this.getConfig(CONFIG_CONTEXT);
28570 ffConfig[CONFIG_CONTEXT] = _.extend({}, oldContext, newContext);
28571
28572 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
28573 return this.fetchFlags();
28574 };
28575
28576 FeatureFlagManager.prototype.areFlagsReady = function() {
28577 if (!this.isSystemEnabled()) {
28578 logger.error('Feature Flags not enabled');
28579 }
28580 return !!this.flags;
28581 };
28582
28583 FeatureFlagManager.prototype.fetchFlags = function() {
28584 if (!this.isSystemEnabled()) {
28585 return Promise.resolve();
28586 }
28587
28588 var distinctId = this.getMpProperty('distinct_id');
28589 var deviceId = this.getMpProperty('$device_id');
28590 var traceparent = generateTraceparent();
28591 logger.log('Fetching flags for distinct ID: ' + distinctId);
28592
28593 var context = _.extend({'distinct_id': distinctId, 'device_id': deviceId}, this.getConfig(CONFIG_CONTEXT));
28594 var searchParams = new URLSearchParams();
28595 searchParams.set('context', JSON.stringify(context));
28596 searchParams.set('token', this.getMpConfig('token'));
28597 searchParams.set('mp_lib', 'web');
28598 searchParams.set('$lib_version', Config.LIB_VERSION);
28599 var url = this.getFullApiRoute() + '?' + searchParams.toString();
28600
28601 this._fetchInProgressStartTime = Date.now();
28602 this.fetchPromise = this.fetch.call(win, url, {
28603 'method': 'GET',
28604 'headers': {
28605 'Authorization': 'Basic ' + btoa(this.getMpConfig('token') + ':'),
28606 'traceparent': traceparent
28607 }
28608 }).then(function(response) {
28609 this.markFetchComplete();
28610 return response.json().then(function(responseBody) {
28611 var responseFlags = responseBody['flags'];
28612 if (!responseFlags) {
28613 throw new Error('No flags in API response');
28614 }
28615 var flags = new Map();
28616 _.each(responseFlags, function(data, key) {
28617 flags.set(key, {
28618 'key': data['variant_key'],
28619 'value': data['variant_value'],
28620 'experiment_id': data['experiment_id'],
28621 'is_experiment_active': data['is_experiment_active'],
28622 'is_qa_tester': data['is_qa_tester']
28623 });
28624 });
28625 this.flags = flags;
28626 this._traceparent = traceparent;
28627 }.bind(this)).catch(function(error) {
28628 this.markFetchComplete();
28629 logger.error(error);
28630 }.bind(this));
28631 }.bind(this)).catch(function(error) {
28632 this.markFetchComplete();
28633 logger.error(error);
28634 }.bind(this));
28635
28636 return this.fetchPromise;
28637 };
28638
28639 FeatureFlagManager.prototype.markFetchComplete = function() {
28640 if (!this._fetchInProgressStartTime) {
28641 logger.error('Fetch in progress started time not set, cannot mark fetch complete');
28642 return;
28643 }
28644 this._fetchStartTime = this._fetchInProgressStartTime;
28645 this._fetchCompleteTime = Date.now();
28646 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
28647 this._fetchInProgressStartTime = null;
28648 };
28649
28650 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
28651 if (!this.fetchPromise) {
28652 return new Promise(function(resolve) {
28653 logger.critical('Feature Flags not initialized');
28654 resolve(fallback);
28655 });
28656 }
28657
28658 return this.fetchPromise.then(function() {
28659 return this.getVariantSync(featureName, fallback);
28660 }.bind(this)).catch(function(error) {
28661 logger.error(error);
28662 return fallback;
28663 });
28664 };
28665
28666 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
28667 if (!this.areFlagsReady()) {
28668 logger.log('Flags not loaded yet');
28669 return fallback;
28670 }
28671 var feature = this.flags.get(featureName);
28672 if (!feature) {
28673 logger.log('No flag found: "' + featureName + '"');
28674 return fallback;
28675 }
28676 this.trackFeatureCheck(featureName, feature);
28677 return feature;
28678 };
28679
28680 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
28681 return this.getVariant(featureName, {'value': fallbackValue}).then(function(feature) {
28682 return feature['value'];
28683 }).catch(function(error) {
28684 logger.error(error);
28685 return fallbackValue;
28686 });
28687 };
28688
28689 // TODO remove deprecated method
28690 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
28691 logger.critical('mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.');
28692 return this.getVariantValue(featureName, fallbackValue);
28693 };
28694
28695 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
28696 return this.getVariantSync(featureName, {'value': fallbackValue})['value'];
28697 };
28698
28699 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
28700 return this.getVariantValue(featureName).then(function() {
28701 return this.isEnabledSync(featureName, fallbackValue);
28702 }.bind(this)).catch(function(error) {
28703 logger.error(error);
28704 return fallbackValue;
28705 });
28706 };
28707
28708 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
28709 fallbackValue = fallbackValue || false;
28710 var val = this.getVariantValueSync(featureName, fallbackValue);
28711 if (val !== true && val !== false) {
28712 logger.error('Feature flag "' + featureName + '" value: ' + val + ' is not a boolean; returning fallback value: ' + fallbackValue);
28713 val = fallbackValue;
28714 }
28715 return val;
28716 };
28717
28718 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
28719 if (this.trackedFeatures.has(featureName)) {
28720 return;
28721 }
28722 this.trackedFeatures.add(featureName);
28723
28724 var trackingProperties = {
28725 'Experiment name': featureName,
28726 'Variant name': feature['key'],
28727 '$experiment_type': 'feature_flag',
28728 'Variant fetch start time': new Date(this._fetchStartTime).toISOString(),
28729 'Variant fetch complete time': new Date(this._fetchCompleteTime).toISOString(),
28730 'Variant fetch latency (ms)': this._fetchLatency,
28731 'Variant fetch traceparent': this._traceparent,
28732 };
28733
28734 if (feature['experiment_id'] !== 'undefined') {
28735 trackingProperties['$experiment_id'] = feature['experiment_id'];
28736 }
28737 if (feature['is_experiment_active'] !== 'undefined') {
28738 trackingProperties['$is_experiment_active'] = feature['is_experiment_active'];
28739 }
28740 if (feature['is_qa_tester'] !== 'undefined') {
28741 trackingProperties['$is_qa_tester'] = feature['is_qa_tester'];
28742 }
28743
28744 this.track('$experiment_started', trackingProperties);
28745 };
28746
28747 FeatureFlagManager.prototype.minApisSupported = function() {
28748 return !!this.fetch &&
28749 typeof Promise !== 'undefined' &&
28750 typeof Map !== 'undefined' &&
28751 typeof Set !== 'undefined';
28752 };
28753
28754 safewrapClass(FeatureFlagManager);
28755
28756 FeatureFlagManager.prototype['are_flags_ready'] = FeatureFlagManager.prototype.areFlagsReady;
28757 FeatureFlagManager.prototype['get_variant'] = FeatureFlagManager.prototype.getVariant;
28758 FeatureFlagManager.prototype['get_variant_sync'] = FeatureFlagManager.prototype.getVariantSync;
28759 FeatureFlagManager.prototype['get_variant_value'] = FeatureFlagManager.prototype.getVariantValue;
28760 FeatureFlagManager.prototype['get_variant_value_sync'] = FeatureFlagManager.prototype.getVariantValueSync;
28761 FeatureFlagManager.prototype['is_enabled'] = FeatureFlagManager.prototype.isEnabled;
28762 FeatureFlagManager.prototype['is_enabled_sync'] = FeatureFlagManager.prototype.isEnabledSync;
28763 FeatureFlagManager.prototype['update_context'] = FeatureFlagManager.prototype.updateContext;
28764
28765 // Deprecated method
28766 FeatureFlagManager.prototype['get_feature_data'] = FeatureFlagManager.prototype.getFeatureData;
28767
28768 /* eslint camelcase: "off" */
28769
28770
28771 /**
28772 * DomTracker Object
28773 * @constructor
28774 */
28775 var DomTracker = function() {};
28776
28777
28778 // interface
28779 DomTracker.prototype.create_properties = function() {};
28780 DomTracker.prototype.event_handler = function() {};
28781 DomTracker.prototype.after_track_handler = function() {};
28782
28783 DomTracker.prototype.init = function(mixpanel_instance) {
28784 this.mp = mixpanel_instance;
28785 return this;
28786 };
28787
28788 /**
28789 * @param {Object|string} query
28790 * @param {string} event_name
28791 * @param {Object=} properties
28792 * @param {function=} user_callback
28793 */
28794 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
28795 var that = this;
28796 var elements = _.dom_query(query);
28797
28798 if (elements.length === 0) {
28799 console$1.error('The DOM query (' + query + ') returned 0 elements');
28800 return;
28801 }
28802
28803 _.each(elements, function(element) {
28804 _.register_event(element, this.override_event, function(e) {
28805 var options = {};
28806 var props = that.create_properties(properties, this);
28807 var timeout = that.mp.get_config('track_links_timeout');
28808
28809 that.event_handler(e, this, options);
28810
28811 // in case the mixpanel servers don't get back to us in time
28812 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
28813
28814 // fire the tracking event
28815 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
28816 });
28817 }, this);
28818
28819 return true;
28820 };
28821
28822 /**
28823 * @param {function} user_callback
28824 * @param {Object} props
28825 * @param {boolean=} timeout_occured
28826 */
28827 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
28828 timeout_occured = timeout_occured || false;
28829 var that = this;
28830
28831 return function() {
28832 // options is referenced from both callbacks, so we can have
28833 // a 'lock' of sorts to ensure only one fires
28834 if (options.callback_fired) { return; }
28835 options.callback_fired = true;
28836
28837 if (user_callback && user_callback(timeout_occured, props) === false) {
28838 // user can prevent the default functionality by
28839 // returning false from their callback
28840 return;
28841 }
28842
28843 that.after_track_handler(props, options, timeout_occured);
28844 };
28845 };
28846
28847 DomTracker.prototype.create_properties = function(properties, element) {
28848 var props;
28849
28850 if (typeof(properties) === 'function') {
28851 props = properties(element);
28852 } else {
28853 props = _.extend({}, properties);
28854 }
28855
28856 return props;
28857 };
28858
28859 /**
28860 * LinkTracker Object
28861 * @constructor
28862 * @extends DomTracker
28863 */
28864 var LinkTracker = function() {
28865 this.override_event = 'click';
28866 };
28867 _.inherit(LinkTracker, DomTracker);
28868
28869 LinkTracker.prototype.create_properties = function(properties, element) {
28870 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
28871
28872 if (element.href) { props['url'] = element.href; }
28873
28874 return props;
28875 };
28876
28877 LinkTracker.prototype.event_handler = function(evt, element, options) {
28878 options.new_tab = (
28879 evt.which === 2 ||
28880 evt.metaKey ||
28881 evt.ctrlKey ||
28882 element.target === '_blank'
28883 );
28884 options.href = element.href;
28885
28886 if (!options.new_tab) {
28887 evt.preventDefault();
28888 }
28889 };
28890
28891 LinkTracker.prototype.after_track_handler = function(props, options) {
28892 if (options.new_tab) { return; }
28893
28894 setTimeout(function() {
28895 window.location = options.href;
28896 }, 0);
28897 };
28898
28899 /**
28900 * FormTracker Object
28901 * @constructor
28902 * @extends DomTracker
28903 */
28904 var FormTracker = function() {
28905 this.override_event = 'submit';
28906 };
28907 _.inherit(FormTracker, DomTracker);
28908
28909 FormTracker.prototype.event_handler = function(evt, element, options) {
28910 options.element = element;
28911 evt.preventDefault();
28912 };
28913
28914 FormTracker.prototype.after_track_handler = function(props, options) {
28915 setTimeout(function() {
28916 options.element.submit();
28917 }, 0);
28918 };
28919
28920 /* eslint camelcase: "off" */
28921
28922
28923 /** @const */ var SET_ACTION = '$set';
28924 /** @const */ var SET_ONCE_ACTION = '$set_once';
28925 /** @const */ var UNSET_ACTION = '$unset';
28926 /** @const */ var ADD_ACTION = '$add';
28927 /** @const */ var APPEND_ACTION = '$append';
28928 /** @const */ var UNION_ACTION = '$union';
28929 /** @const */ var REMOVE_ACTION = '$remove';
28930 /** @const */ var DELETE_ACTION = '$delete';
28931
28932 // Common internal methods for mixpanel.people and mixpanel.group APIs.
28933 // These methods shouldn't involve network I/O.
28934 var apiActions = {
28935 set_action: function(prop, to) {
28936 var data = {};
28937 var $set = {};
28938 if (_.isObject(prop)) {
28939 _.each(prop, function(v, k) {
28940 if (!this._is_reserved_property(k)) {
28941 $set[k] = v;
28942 }
28943 }, this);
28944 } else {
28945 $set[prop] = to;
28946 }
28947
28948 data[SET_ACTION] = $set;
28949 return data;
28950 },
28951
28952 unset_action: function(prop) {
28953 var data = {};
28954 var $unset = [];
28955 if (!_.isArray(prop)) {
28956 prop = [prop];
28957 }
28958
28959 _.each(prop, function(k) {
28960 if (!this._is_reserved_property(k)) {
28961 $unset.push(k);
28962 }
28963 }, this);
28964
28965 data[UNSET_ACTION] = $unset;
28966 return data;
28967 },
28968
28969 set_once_action: function(prop, to) {
28970 var data = {};
28971 var $set_once = {};
28972 if (_.isObject(prop)) {
28973 _.each(prop, function(v, k) {
28974 if (!this._is_reserved_property(k)) {
28975 $set_once[k] = v;
28976 }
28977 }, this);
28978 } else {
28979 $set_once[prop] = to;
28980 }
28981 data[SET_ONCE_ACTION] = $set_once;
28982 return data;
28983 },
28984
28985 union_action: function(list_name, values) {
28986 var data = {};
28987 var $union = {};
28988 if (_.isObject(list_name)) {
28989 _.each(list_name, function(v, k) {
28990 if (!this._is_reserved_property(k)) {
28991 $union[k] = _.isArray(v) ? v : [v];
28992 }
28993 }, this);
28994 } else {
28995 $union[list_name] = _.isArray(values) ? values : [values];
28996 }
28997 data[UNION_ACTION] = $union;
28998 return data;
28999 },
29000
29001 append_action: function(list_name, value) {
29002 var data = {};
29003 var $append = {};
29004 if (_.isObject(list_name)) {
29005 _.each(list_name, function(v, k) {
29006 if (!this._is_reserved_property(k)) {
29007 $append[k] = v;
29008 }
29009 }, this);
29010 } else {
29011 $append[list_name] = value;
29012 }
29013 data[APPEND_ACTION] = $append;
29014 return data;
29015 },
29016
29017 remove_action: function(list_name, value) {
29018 var data = {};
29019 var $remove = {};
29020 if (_.isObject(list_name)) {
29021 _.each(list_name, function(v, k) {
29022 if (!this._is_reserved_property(k)) {
29023 $remove[k] = v;
29024 }
29025 }, this);
29026 } else {
29027 $remove[list_name] = value;
29028 }
29029 data[REMOVE_ACTION] = $remove;
29030 return data;
29031 },
29032
29033 delete_action: function() {
29034 var data = {};
29035 data[DELETE_ACTION] = '';
29036 return data;
29037 }
29038 };
29039
29040 /* eslint camelcase: "off" */
29041
29042 /**
29043 * Mixpanel Group Object
29044 * @constructor
29045 */
29046 var MixpanelGroup = function() {};
29047
29048 _.extend(MixpanelGroup.prototype, apiActions);
29049
29050 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
29051 this._mixpanel = mixpanel_instance;
29052 this._group_key = group_key;
29053 this._group_id = group_id;
29054 };
29055
29056 /**
29057 * Set properties on a group.
29058 *
29059 * ### Usage:
29060 *
29061 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
29062 *
29063 * // or set multiple properties at once
29064 * mixpanel.get_group('company', 'mixpanel').set({
29065 * 'Location': '405 Howard',
29066 * 'Founded' : 2009,
29067 * });
29068 * // properties can be strings, integers, dates, or lists
29069 *
29070 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
29071 * @param {*} [to] A value to set on the given property name
29072 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29073 */
29074 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
29075 var data = this.set_action(prop, to);
29076 if (_.isObject(prop)) {
29077 callback = to;
29078 }
29079 return this._send_request(data, callback);
29080 });
29081
29082 /**
29083 * Set properties on a group, only if they do not yet exist.
29084 * This will not overwrite previous group property values, unlike
29085 * group.set().
29086 *
29087 * ### Usage:
29088 *
29089 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
29090 *
29091 * // or set multiple properties at once
29092 * mixpanel.get_group('company', 'mixpanel').set_once({
29093 * 'Location': '405 Howard',
29094 * 'Founded' : 2009,
29095 * });
29096 * // properties can be strings, integers, lists or dates
29097 *
29098 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
29099 * @param {*} [to] A value to set on the given property name
29100 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29101 */
29102 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
29103 var data = this.set_once_action(prop, to);
29104 if (_.isObject(prop)) {
29105 callback = to;
29106 }
29107 return this._send_request(data, callback);
29108 });
29109
29110 /**
29111 * Unset properties on a group permanently.
29112 *
29113 * ### Usage:
29114 *
29115 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
29116 *
29117 * @param {String} prop The name of the property.
29118 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29119 */
29120 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
29121 var data = this.unset_action(prop);
29122 return this._send_request(data, callback);
29123 });
29124
29125 /**
29126 * Merge a given list with a list-valued group property, excluding duplicate values.
29127 *
29128 * ### Usage:
29129 *
29130 * // merge a value to a list, creating it if needed
29131 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
29132 *
29133 * @param {String} list_name Name of the property.
29134 * @param {Array} values Values to merge with the given property
29135 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29136 */
29137 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
29138 if (_.isObject(list_name)) {
29139 callback = values;
29140 }
29141 var data = this.union_action(list_name, values);
29142 return this._send_request(data, callback);
29143 });
29144
29145 /**
29146 * Permanently delete a group.
29147 *
29148 * ### Usage:
29149 *
29150 * mixpanel.get_group('company', 'mixpanel').delete();
29151 *
29152 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29153 */
29154 MixpanelGroup.prototype['delete'] = addOptOutCheckMixpanelGroup(function(callback) {
29155 // bracket notation above prevents a minification error related to reserved words
29156 var data = this.delete_action();
29157 return this._send_request(data, callback);
29158 });
29159
29160 /**
29161 * Remove a property from a group. The value will be ignored if doesn't exist.
29162 *
29163 * ### Usage:
29164 *
29165 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
29166 *
29167 * @param {String} list_name Name of the property.
29168 * @param {Object} value Value to remove from the given group property
29169 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29170 */
29171 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
29172 var data = this.remove_action(list_name, value);
29173 return this._send_request(data, callback);
29174 });
29175
29176 MixpanelGroup.prototype._send_request = function(data, callback) {
29177 data['$group_key'] = this._group_key;
29178 data['$group_id'] = this._group_id;
29179 data['$token'] = this._get_config('token');
29180
29181 var date_encoded_data = _.encodeDates(data);
29182 return this._mixpanel._track_or_batch({
29183 type: 'groups',
29184 data: date_encoded_data,
29185 endpoint: this._mixpanel.get_api_host('groups') + '/' + this._get_config('api_routes')['groups'],
29186 batcher: this._mixpanel.request_batchers.groups
29187 }, callback);
29188 };
29189
29190 MixpanelGroup.prototype._is_reserved_property = function(prop) {
29191 return prop === '$group_key' || prop === '$group_id';
29192 };
29193
29194 MixpanelGroup.prototype._get_config = function(conf) {
29195 return this._mixpanel.get_config(conf);
29196 };
29197
29198 MixpanelGroup.prototype.toString = function() {
29199 return this._mixpanel.toString() + '.group.' + this._group_key + '.' + this._group_id;
29200 };
29201
29202 // MixpanelGroup Exports
29203 MixpanelGroup.prototype['remove'] = MixpanelGroup.prototype.remove;
29204 MixpanelGroup.prototype['set'] = MixpanelGroup.prototype.set;
29205 MixpanelGroup.prototype['set_once'] = MixpanelGroup.prototype.set_once;
29206 MixpanelGroup.prototype['union'] = MixpanelGroup.prototype.union;
29207 MixpanelGroup.prototype['unset'] = MixpanelGroup.prototype.unset;
29208 MixpanelGroup.prototype['toString'] = MixpanelGroup.prototype.toString;
29209
29210 /* eslint camelcase: "off" */
29211
29212 /**
29213 * Mixpanel People Object
29214 * @constructor
29215 */
29216 var MixpanelPeople = function() {};
29217
29218 _.extend(MixpanelPeople.prototype, apiActions);
29219
29220 MixpanelPeople.prototype._init = function(mixpanel_instance) {
29221 this._mixpanel = mixpanel_instance;
29222 };
29223
29224 /*
29225 * Set properties on a user record.
29226 *
29227 * ### Usage:
29228 *
29229 * mixpanel.people.set('gender', 'm');
29230 *
29231 * // or set multiple properties at once
29232 * mixpanel.people.set({
29233 * 'Company': 'Acme',
29234 * 'Plan': 'Premium',
29235 * 'Upgrade date': new Date()
29236 * });
29237 * // properties can be strings, integers, dates, or lists
29238 *
29239 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
29240 * @param {*} [to] A value to set on the given property name
29241 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29242 */
29243 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
29244 var data = this.set_action(prop, to);
29245 if (_.isObject(prop)) {
29246 callback = to;
29247 }
29248 // make sure that the referrer info has been updated and saved
29249 if (this._get_config('save_referrer')) {
29250 this._mixpanel['persistence'].update_referrer_info(document.referrer);
29251 }
29252
29253 // update $set object with default people properties
29254 data[SET_ACTION] = _.extend(
29255 {},
29256 _.info.people_properties(),
29257 data[SET_ACTION]
29258 );
29259 return this._send_request(data, callback);
29260 });
29261
29262 /*
29263 * Set properties on a user record, only if they do not yet exist.
29264 * This will not overwrite previous people property values, unlike
29265 * people.set().
29266 *
29267 * ### Usage:
29268 *
29269 * mixpanel.people.set_once('First Login Date', new Date());
29270 *
29271 * // or set multiple properties at once
29272 * mixpanel.people.set_once({
29273 * 'First Login Date': new Date(),
29274 * 'Starting Plan': 'Premium'
29275 * });
29276 *
29277 * // properties can be strings, integers or dates
29278 *
29279 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and values.
29280 * @param {*} [to] A value to set on the given property name
29281 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29282 */
29283 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
29284 var data = this.set_once_action(prop, to);
29285 if (_.isObject(prop)) {
29286 callback = to;
29287 }
29288 return this._send_request(data, callback);
29289 });
29290
29291 /*
29292 * Unset properties on a user record (permanently removes the properties and their values from a profile).
29293 *
29294 * ### Usage:
29295 *
29296 * mixpanel.people.unset('gender');
29297 *
29298 * // or unset multiple properties at once
29299 * mixpanel.people.unset(['gender', 'Company']);
29300 *
29301 * @param {Array|String} prop If a string, this is the name of the property. If an array, this is a list of property names.
29302 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29303 */
29304 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
29305 var data = this.unset_action(prop);
29306 return this._send_request(data, callback);
29307 });
29308
29309 /*
29310 * Increment/decrement numeric people analytics properties.
29311 *
29312 * ### Usage:
29313 *
29314 * mixpanel.people.increment('page_views', 1);
29315 *
29316 * // or, for convenience, if you're just incrementing a counter by
29317 * // 1, you can simply do
29318 * mixpanel.people.increment('page_views');
29319 *
29320 * // to decrement a counter, pass a negative number
29321 * mixpanel.people.increment('credits_left', -1);
29322 *
29323 * // like mixpanel.people.set(), you can increment multiple
29324 * // properties at once:
29325 * mixpanel.people.increment({
29326 * counter1: 1,
29327 * counter2: 6
29328 * });
29329 *
29330 * @param {Object|String} prop If a string, this is the name of the property. If an object, this is an associative array of names and numeric values.
29331 * @param {Number} [by] An amount to increment the given property
29332 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29333 */
29334 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
29335 var data = {};
29336 var $add = {};
29337 if (_.isObject(prop)) {
29338 _.each(prop, function(v, k) {
29339 if (!this._is_reserved_property(k)) {
29340 if (isNaN(parseFloat(v))) {
29341 console$1.error('Invalid increment value passed to mixpanel.people.increment - must be a number');
29342 return;
29343 } else {
29344 $add[k] = v;
29345 }
29346 }
29347 }, this);
29348 callback = by;
29349 } else {
29350 // convenience: mixpanel.people.increment('property'); will
29351 // increment 'property' by 1
29352 if (_.isUndefined(by)) {
29353 by = 1;
29354 }
29355 $add[prop] = by;
29356 }
29357 data[ADD_ACTION] = $add;
29358
29359 return this._send_request(data, callback);
29360 });
29361
29362 /*
29363 * Append a value to a list-valued people analytics property.
29364 *
29365 * ### Usage:
29366 *
29367 * // append a value to a list, creating it if needed
29368 * mixpanel.people.append('pages_visited', 'homepage');
29369 *
29370 * // like mixpanel.people.set(), you can append multiple
29371 * // properties at once:
29372 * mixpanel.people.append({
29373 * list1: 'bob',
29374 * list2: 123
29375 * });
29376 *
29377 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
29378 * @param {*} [value] value An item to append to the list
29379 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29380 */
29381 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
29382 if (_.isObject(list_name)) {
29383 callback = value;
29384 }
29385 var data = this.append_action(list_name, value);
29386 return this._send_request(data, callback);
29387 });
29388
29389 /*
29390 * Remove a value from a list-valued people analytics property.
29391 *
29392 * ### Usage:
29393 *
29394 * mixpanel.people.remove('School', 'UCB');
29395 *
29396 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
29397 * @param {*} [value] value Item to remove from the list
29398 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29399 */
29400 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
29401 if (_.isObject(list_name)) {
29402 callback = value;
29403 }
29404 var data = this.remove_action(list_name, value);
29405 return this._send_request(data, callback);
29406 });
29407
29408 /*
29409 * Merge a given list with a list-valued people analytics property,
29410 * excluding duplicate values.
29411 *
29412 * ### Usage:
29413 *
29414 * // merge a value to a list, creating it if needed
29415 * mixpanel.people.union('pages_visited', 'homepage');
29416 *
29417 * // like mixpanel.people.set(), you can append multiple
29418 * // properties at once:
29419 * mixpanel.people.union({
29420 * list1: 'bob',
29421 * list2: 123
29422 * });
29423 *
29424 * // like mixpanel.people.append(), you can append multiple
29425 * // values to the same list:
29426 * mixpanel.people.union({
29427 * list1: ['bob', 'billy']
29428 * });
29429 *
29430 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
29431 * @param {*} [value] Value / values to merge with the given property
29432 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29433 */
29434 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
29435 if (_.isObject(list_name)) {
29436 callback = values;
29437 }
29438 var data = this.union_action(list_name, values);
29439 return this._send_request(data, callback);
29440 });
29441
29442 /*
29443 * Record that you have charged the current user a certain amount
29444 * of money. Charges recorded with track_charge() will appear in the
29445 * Mixpanel revenue report.
29446 *
29447 * ### Usage:
29448 *
29449 * // charge a user $50
29450 * mixpanel.people.track_charge(50);
29451 *
29452 * // charge a user $30.50 on the 2nd of january
29453 * mixpanel.people.track_charge(30.50, {
29454 * '$time': new Date('jan 1 2012')
29455 * });
29456 *
29457 * @param {Number} amount The amount of money charged to the current user
29458 * @param {Object} [properties] An associative array of properties associated with the charge
29459 * @param {Function} [callback] If provided, the callback will be called when the server responds
29460 * @deprecated
29461 */
29462 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
29463 console$1.error('mixpanel.people.track_charge() is deprecated and no longer has any effect.');
29464 });
29465
29466 /*
29467 * Permanently clear all revenue report transactions from the
29468 * current user's people analytics profile.
29469 *
29470 * ### Usage:
29471 *
29472 * mixpanel.people.clear_charges();
29473 *
29474 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29475 * @deprecated
29476 */
29477 MixpanelPeople.prototype.clear_charges = function(callback) {
29478 return this.set('$transactions', [], callback);
29479 };
29480
29481 /*
29482 * Permanently deletes the current people analytics profile from
29483 * Mixpanel (using the current distinct_id).
29484 *
29485 * ### Usage:
29486 *
29487 * // remove the all data you have stored about the current user
29488 * mixpanel.people.delete_user();
29489 *
29490 */
29491 MixpanelPeople.prototype.delete_user = function() {
29492 if (!this._identify_called()) {
29493 console$1.error('mixpanel.people.delete_user() requires you to call identify() first');
29494 return;
29495 }
29496 var data = {'$delete': this._mixpanel.get_distinct_id()};
29497 return this._send_request(data);
29498 };
29499
29500 MixpanelPeople.prototype.toString = function() {
29501 return this._mixpanel.toString() + '.people';
29502 };
29503
29504 MixpanelPeople.prototype._send_request = function(data, callback) {
29505 data['$token'] = this._get_config('token');
29506 data['$distinct_id'] = this._mixpanel.get_distinct_id();
29507 var device_id = this._mixpanel.get_property('$device_id');
29508 var user_id = this._mixpanel.get_property('$user_id');
29509 var had_persisted_distinct_id = this._mixpanel.get_property('$had_persisted_distinct_id');
29510 if (device_id) {
29511 data['$device_id'] = device_id;
29512 }
29513 if (user_id) {
29514 data['$user_id'] = user_id;
29515 }
29516 if (had_persisted_distinct_id) {
29517 data['$had_persisted_distinct_id'] = had_persisted_distinct_id;
29518 }
29519
29520 var date_encoded_data = _.encodeDates(data);
29521
29522 if (!this._identify_called()) {
29523 this._enqueue(data);
29524 if (!_.isUndefined(callback)) {
29525 if (this._get_config('verbose')) {
29526 callback({status: -1, error: null});
29527 } else {
29528 callback(-1);
29529 }
29530 }
29531 return _.truncate(date_encoded_data, 255);
29532 }
29533
29534 return this._mixpanel._track_or_batch({
29535 type: 'people',
29536 data: date_encoded_data,
29537 endpoint: this._mixpanel.get_api_host('people') + '/' + this._get_config('api_routes')['engage'],
29538 batcher: this._mixpanel.request_batchers.people
29539 }, callback);
29540 };
29541
29542 MixpanelPeople.prototype._get_config = function(conf_var) {
29543 return this._mixpanel.get_config(conf_var);
29544 };
29545
29546 MixpanelPeople.prototype._identify_called = function() {
29547 return this._mixpanel._flags.identify_called === true;
29548 };
29549
29550 // Queue up engage operations if identify hasn't been called yet.
29551 MixpanelPeople.prototype._enqueue = function(data) {
29552 if (SET_ACTION in data) {
29553 this._mixpanel['persistence']._add_to_people_queue(SET_ACTION, data);
29554 } else if (SET_ONCE_ACTION in data) {
29555 this._mixpanel['persistence']._add_to_people_queue(SET_ONCE_ACTION, data);
29556 } else if (UNSET_ACTION in data) {
29557 this._mixpanel['persistence']._add_to_people_queue(UNSET_ACTION, data);
29558 } else if (ADD_ACTION in data) {
29559 this._mixpanel['persistence']._add_to_people_queue(ADD_ACTION, data);
29560 } else if (APPEND_ACTION in data) {
29561 this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, data);
29562 } else if (REMOVE_ACTION in data) {
29563 this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, data);
29564 } else if (UNION_ACTION in data) {
29565 this._mixpanel['persistence']._add_to_people_queue(UNION_ACTION, data);
29566 } else {
29567 console$1.error('Invalid call to _enqueue():', data);
29568 }
29569 };
29570
29571 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
29572 var _this = this;
29573 var queued_data = _.extend({}, this._mixpanel['persistence'].load_queue(action));
29574 var action_params = queued_data;
29575
29576 if (!_.isUndefined(queued_data) && _.isObject(queued_data) && !_.isEmptyObject(queued_data)) {
29577 _this._mixpanel['persistence']._pop_from_people_queue(action, queued_data);
29578 _this._mixpanel['persistence'].save();
29579 if (queue_to_params_fn) {
29580 action_params = queue_to_params_fn(queued_data);
29581 }
29582 action_method.call(_this, action_params, function(response, data) {
29583 // on bad response, we want to add it back to the queue
29584 if (response === 0) {
29585 _this._mixpanel['persistence']._add_to_people_queue(action, queued_data);
29586 }
29587 if (!_.isUndefined(callback)) {
29588 callback(response, data);
29589 }
29590 });
29591 }
29592 };
29593
29594 // Flush queued engage operations - order does not matter,
29595 // and there are network level race conditions anyway
29596 MixpanelPeople.prototype._flush = function(
29597 _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
29598 ) {
29599 var _this = this;
29600
29601 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
29602 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
29603 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) { return _.keys(queue); });
29604 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
29605 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
29606
29607 // we have to fire off each $append individually since there is
29608 // no concat method server side
29609 var $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
29610 if (!_.isUndefined($append_queue) && _.isArray($append_queue) && $append_queue.length) {
29611 var $append_item;
29612 var append_callback = function(response, data) {
29613 if (response === 0) {
29614 _this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, $append_item);
29615 }
29616 if (!_.isUndefined(_append_callback)) {
29617 _append_callback(response, data);
29618 }
29619 };
29620 for (var i = $append_queue.length - 1; i >= 0; i--) {
29621 $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
29622 $append_item = $append_queue.pop();
29623 _this._mixpanel['persistence'].save();
29624 if (!_.isEmptyObject($append_item)) {
29625 _this.append($append_item, append_callback);
29626 }
29627 }
29628 }
29629
29630 // same for $remove
29631 var $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
29632 if (!_.isUndefined($remove_queue) && _.isArray($remove_queue) && $remove_queue.length) {
29633 var $remove_item;
29634 var remove_callback = function(response, data) {
29635 if (response === 0) {
29636 _this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, $remove_item);
29637 }
29638 if (!_.isUndefined(_remove_callback)) {
29639 _remove_callback(response, data);
29640 }
29641 };
29642 for (var j = $remove_queue.length - 1; j >= 0; j--) {
29643 $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
29644 $remove_item = $remove_queue.pop();
29645 _this._mixpanel['persistence'].save();
29646 if (!_.isEmptyObject($remove_item)) {
29647 _this.remove($remove_item, remove_callback);
29648 }
29649 }
29650 }
29651 };
29652
29653 MixpanelPeople.prototype._is_reserved_property = function(prop) {
29654 return prop === '$distinct_id' || prop === '$token' || prop === '$device_id' || prop === '$user_id' || prop === '$had_persisted_distinct_id';
29655 };
29656
29657 // MixpanelPeople Exports
29658 MixpanelPeople.prototype['set'] = MixpanelPeople.prototype.set;
29659 MixpanelPeople.prototype['set_once'] = MixpanelPeople.prototype.set_once;
29660 MixpanelPeople.prototype['unset'] = MixpanelPeople.prototype.unset;
29661 MixpanelPeople.prototype['increment'] = MixpanelPeople.prototype.increment;
29662 MixpanelPeople.prototype['append'] = MixpanelPeople.prototype.append;
29663 MixpanelPeople.prototype['remove'] = MixpanelPeople.prototype.remove;
29664 MixpanelPeople.prototype['union'] = MixpanelPeople.prototype.union;
29665 MixpanelPeople.prototype['track_charge'] = MixpanelPeople.prototype.track_charge;
29666 MixpanelPeople.prototype['clear_charges'] = MixpanelPeople.prototype.clear_charges;
29667 MixpanelPeople.prototype['delete_user'] = MixpanelPeople.prototype.delete_user;
29668 MixpanelPeople.prototype['toString'] = MixpanelPeople.prototype.toString;
29669
29670 /* eslint camelcase: "off" */
29671
29672
29673 /*
29674 * Constants
29675 */
29676 /** @const */ var SET_QUEUE_KEY = '__mps';
29677 /** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
29678 /** @const */ var UNSET_QUEUE_KEY = '__mpus';
29679 /** @const */ var ADD_QUEUE_KEY = '__mpa';
29680 /** @const */ var APPEND_QUEUE_KEY = '__mpap';
29681 /** @const */ var REMOVE_QUEUE_KEY = '__mpr';
29682 /** @const */ var UNION_QUEUE_KEY = '__mpu';
29683 // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
29684 /** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
29685 /** @const */ var ALIAS_ID_KEY = '__alias';
29686 /** @const */ var EVENT_TIMERS_KEY = '__timers';
29687 /** @const */ var RESERVED_PROPERTIES = [
29688 SET_QUEUE_KEY,
29689 SET_ONCE_QUEUE_KEY,
29690 UNSET_QUEUE_KEY,
29691 ADD_QUEUE_KEY,
29692 APPEND_QUEUE_KEY,
29693 REMOVE_QUEUE_KEY,
29694 UNION_QUEUE_KEY,
29695 PEOPLE_DISTINCT_ID_KEY,
29696 ALIAS_ID_KEY,
29697 EVENT_TIMERS_KEY
29698 ];
29699
29700 /**
29701 * Mixpanel Persistence Object
29702 * @constructor
29703 */
29704 var MixpanelPersistence = function(config) {
29705 this['props'] = {};
29706 this.campaign_params_saved = false;
29707
29708 if (config['persistence_name']) {
29709 this.name = 'mp_' + config['persistence_name'];
29710 } else {
29711 this.name = 'mp_' + config['token'] + '_mixpanel';
29712 }
29713
29714 var storage_type = config['persistence'];
29715 if (storage_type !== 'cookie' && storage_type !== 'localStorage') {
29716 console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');
29717 storage_type = config['persistence'] = 'cookie';
29718 }
29719
29720 if (storage_type === 'localStorage' && _.localStorage.is_supported()) {
29721 this.storage = _.localStorage;
29722 } else {
29723 this.storage = _.cookie;
29724 }
29725
29726 this.load();
29727 this.update_config(config);
29728 this.upgrade();
29729 this.save();
29730 };
29731
29732 MixpanelPersistence.prototype.properties = function() {
29733 var p = {};
29734
29735 this.load();
29736
29737 // Filter out reserved properties
29738 _.each(this['props'], function(v, k) {
29739 if (!_.include(RESERVED_PROPERTIES, k)) {
29740 p[k] = v;
29741 }
29742 });
29743 return p;
29744 };
29745
29746 MixpanelPersistence.prototype.load = function() {
29747 if (this.disabled) { return; }
29748
29749 var entry = this.storage.parse(this.name);
29750
29751 if (entry) {
29752 this['props'] = _.extend({}, entry);
29753 }
29754 };
29755
29756 MixpanelPersistence.prototype.upgrade = function() {
29757 var old_cookie,
29758 old_localstorage;
29759
29760 // if transferring from cookie to localStorage or vice-versa, copy existing
29761 // super properties over to new storage mode
29762 if (this.storage === _.localStorage) {
29763 old_cookie = _.cookie.parse(this.name);
29764
29765 _.cookie.remove(this.name);
29766 _.cookie.remove(this.name, true);
29767
29768 if (old_cookie) {
29769 this.register_once(old_cookie);
29770 }
29771 } else if (this.storage === _.cookie) {
29772 old_localstorage = _.localStorage.parse(this.name);
29773
29774 _.localStorage.remove(this.name);
29775
29776 if (old_localstorage) {
29777 this.register_once(old_localstorage);
29778 }
29779 }
29780 };
29781
29782 MixpanelPersistence.prototype.save = function() {
29783 if (this.disabled) { return; }
29784
29785 this.storage.set(
29786 this.name,
29787 JSONStringify(this['props']),
29788 this.expire_days,
29789 this.cross_subdomain,
29790 this.secure,
29791 this.cross_site,
29792 this.cookie_domain
29793 );
29794 };
29795
29796 MixpanelPersistence.prototype.load_prop = function(key) {
29797 this.load();
29798 return this['props'][key];
29799 };
29800
29801 MixpanelPersistence.prototype.remove = function() {
29802 // remove both domain and subdomain cookies
29803 this.storage.remove(this.name, false, this.cookie_domain);
29804 this.storage.remove(this.name, true, this.cookie_domain);
29805 };
29806
29807 // removes the storage entry and deletes all loaded data
29808 // forced name for tests
29809 MixpanelPersistence.prototype.clear = function() {
29810 this.remove();
29811 this['props'] = {};
29812 };
29813
29814 /**
29815 * @param {Object} props
29816 * @param {*=} default_value
29817 * @param {number=} days
29818 */
29819 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
29820 if (_.isObject(props)) {
29821 if (typeof(default_value) === 'undefined') { default_value = 'None'; }
29822 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
29823
29824 this.load();
29825
29826 _.each(props, function(val, prop) {
29827 if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {
29828 this['props'][prop] = val;
29829 }
29830 }, this);
29831
29832 this.save();
29833
29834 return true;
29835 }
29836 return false;
29837 };
29838
29839 /**
29840 * @param {Object} props
29841 * @param {number=} days
29842 */
29843 MixpanelPersistence.prototype.register = function(props, days) {
29844 if (_.isObject(props)) {
29845 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
29846
29847 this.load();
29848 _.extend(this['props'], props);
29849 this.save();
29850
29851 return true;
29852 }
29853 return false;
29854 };
29855
29856 MixpanelPersistence.prototype.unregister = function(prop) {
29857 this.load();
29858 if (prop in this['props']) {
29859 delete this['props'][prop];
29860 this.save();
29861 }
29862 };
29863
29864 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
29865 this.register(_.info.searchInfo(referrer));
29866 };
29867
29868 // EXPORTED METHOD, we test this directly.
29869 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
29870 // If referrer doesn't exist, we want to note the fact that it was type-in traffic.
29871 this.register_once({
29872 '$initial_referrer': referrer || '$direct',
29873 '$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'
29874 }, '');
29875 };
29876
29877 MixpanelPersistence.prototype.get_referrer_info = function() {
29878 return _.strip_empty_properties({
29879 '$initial_referrer': this['props']['$initial_referrer'],
29880 '$initial_referring_domain': this['props']['$initial_referring_domain']
29881 });
29882 };
29883
29884 MixpanelPersistence.prototype.update_config = function(config) {
29885 this.default_expiry = this.expire_days = config['cookie_expiration'];
29886 this.set_disabled(config['disable_persistence']);
29887 this.set_cookie_domain(config['cookie_domain']);
29888 this.set_cross_site(config['cross_site_cookie']);
29889 this.set_cross_subdomain(config['cross_subdomain_cookie']);
29890 this.set_secure(config['secure_cookie']);
29891 };
29892
29893 MixpanelPersistence.prototype.set_disabled = function(disabled) {
29894 this.disabled = disabled;
29895 if (this.disabled) {
29896 this.remove();
29897 } else {
29898 this.save();
29899 }
29900 };
29901
29902 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
29903 if (cookie_domain !== this.cookie_domain) {
29904 this.remove();
29905 this.cookie_domain = cookie_domain;
29906 this.save();
29907 }
29908 };
29909
29910 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
29911 if (cross_site !== this.cross_site) {
29912 this.cross_site = cross_site;
29913 this.remove();
29914 this.save();
29915 }
29916 };
29917
29918 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
29919 if (cross_subdomain !== this.cross_subdomain) {
29920 this.cross_subdomain = cross_subdomain;
29921 this.remove();
29922 this.save();
29923 }
29924 };
29925
29926 MixpanelPersistence.prototype.get_cross_subdomain = function() {
29927 return this.cross_subdomain;
29928 };
29929
29930 MixpanelPersistence.prototype.set_secure = function(secure) {
29931 if (secure !== this.secure) {
29932 this.secure = secure ? true : false;
29933 this.remove();
29934 this.save();
29935 }
29936 };
29937
29938 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
29939 var q_key = this._get_queue_key(queue),
29940 q_data = data[queue],
29941 set_q = this._get_or_create_queue(SET_ACTION),
29942 set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),
29943 unset_q = this._get_or_create_queue(UNSET_ACTION),
29944 add_q = this._get_or_create_queue(ADD_ACTION),
29945 union_q = this._get_or_create_queue(UNION_ACTION),
29946 remove_q = this._get_or_create_queue(REMOVE_ACTION, []),
29947 append_q = this._get_or_create_queue(APPEND_ACTION, []);
29948
29949 if (q_key === SET_QUEUE_KEY) {
29950 // Update the set queue - we can override any existing values
29951 _.extend(set_q, q_data);
29952 // if there was a pending increment, override it
29953 // with the set.
29954 this._pop_from_people_queue(ADD_ACTION, q_data);
29955 // if there was a pending union, override it
29956 // with the set.
29957 this._pop_from_people_queue(UNION_ACTION, q_data);
29958 this._pop_from_people_queue(UNSET_ACTION, q_data);
29959 } else if (q_key === SET_ONCE_QUEUE_KEY) {
29960 // only queue the data if there is not already a set_once call for it.
29961 _.each(q_data, function(v, k) {
29962 if (!(k in set_once_q)) {
29963 set_once_q[k] = v;
29964 }
29965 });
29966 this._pop_from_people_queue(UNSET_ACTION, q_data);
29967 } else if (q_key === UNSET_QUEUE_KEY) {
29968 _.each(q_data, function(prop) {
29969
29970 // undo previously-queued actions on this key
29971 _.each([set_q, set_once_q, add_q, union_q], function(enqueued_obj) {
29972 if (prop in enqueued_obj) {
29973 delete enqueued_obj[prop];
29974 }
29975 });
29976 _.each(append_q, function(append_obj) {
29977 if (prop in append_obj) {
29978 delete append_obj[prop];
29979 }
29980 });
29981
29982 unset_q[prop] = true;
29983
29984 });
29985 } else if (q_key === ADD_QUEUE_KEY) {
29986 _.each(q_data, function(v, k) {
29987 // If it exists in the set queue, increment
29988 // the value
29989 if (k in set_q) {
29990 set_q[k] += v;
29991 } else {
29992 // If it doesn't exist, update the add
29993 // queue
29994 if (!(k in add_q)) {
29995 add_q[k] = 0;
29996 }
29997 add_q[k] += v;
29998 }
29999 }, this);
30000 this._pop_from_people_queue(UNSET_ACTION, q_data);
30001 } else if (q_key === UNION_QUEUE_KEY) {
30002 _.each(q_data, function(v, k) {
30003 if (_.isArray(v)) {
30004 if (!(k in union_q)) {
30005 union_q[k] = [];
30006 }
30007 // Prevent duplicate values
30008 _.each(v, function(item) {
30009 if (!_.include(union_q[k], item)) {
30010 union_q[k].push(item);
30011 }
30012 });
30013 }
30014 });
30015 this._pop_from_people_queue(UNSET_ACTION, q_data);
30016 } else if (q_key === REMOVE_QUEUE_KEY) {
30017 remove_q.push(q_data);
30018 this._pop_from_people_queue(APPEND_ACTION, q_data);
30019 } else if (q_key === APPEND_QUEUE_KEY) {
30020 append_q.push(q_data);
30021 this._pop_from_people_queue(UNSET_ACTION, q_data);
30022 }
30023
30024 console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');
30025 console$1.log(data);
30026
30027 this.save();
30028 };
30029
30030 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
30031 var q = this['props'][this._get_queue_key(queue)];
30032 if (!_.isUndefined(q)) {
30033 _.each(data, function(v, k) {
30034 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) {
30035 // list actions: only remove if both k+v match
30036 // e.g. remove should not override append in a case like
30037 // append({foo: 'bar'}); remove({foo: 'qux'})
30038 _.each(q, function(queued_action) {
30039 if (queued_action[k] === v) {
30040 delete queued_action[k];
30041 }
30042 });
30043 } else {
30044 delete q[k];
30045 }
30046 }, this);
30047 }
30048 };
30049
30050 MixpanelPersistence.prototype.load_queue = function(queue) {
30051 return this.load_prop(this._get_queue_key(queue));
30052 };
30053
30054 MixpanelPersistence.prototype._get_queue_key = function(queue) {
30055 if (queue === SET_ACTION) {
30056 return SET_QUEUE_KEY;
30057 } else if (queue === SET_ONCE_ACTION) {
30058 return SET_ONCE_QUEUE_KEY;
30059 } else if (queue === UNSET_ACTION) {
30060 return UNSET_QUEUE_KEY;
30061 } else if (queue === ADD_ACTION) {
30062 return ADD_QUEUE_KEY;
30063 } else if (queue === APPEND_ACTION) {
30064 return APPEND_QUEUE_KEY;
30065 } else if (queue === REMOVE_ACTION) {
30066 return REMOVE_QUEUE_KEY;
30067 } else if (queue === UNION_ACTION) {
30068 return UNION_QUEUE_KEY;
30069 } else {
30070 console$1.error('Invalid queue:', queue);
30071 }
30072 };
30073
30074 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
30075 var key = this._get_queue_key(queue);
30076 default_val = _.isUndefined(default_val) ? {} : default_val;
30077 return this['props'][key] || (this['props'][key] = default_val);
30078 };
30079
30080 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
30081 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
30082 timers[event_name] = timestamp;
30083 this['props'][EVENT_TIMERS_KEY] = timers;
30084 this.save();
30085 };
30086
30087 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
30088 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
30089 var timestamp = timers[event_name];
30090 if (!_.isUndefined(timestamp)) {
30091 delete this['props'][EVENT_TIMERS_KEY][event_name];
30092 this.save();
30093 }
30094 return timestamp;
30095 };
30096
30097 /* eslint camelcase: "off" */
30098
30099 /*
30100 * Mixpanel JS Library
30101 *
30102 * Copyright 2012, Mixpanel, Inc. All Rights Reserved
30103 * http://mixpanel.com/
30104 *
30105 * Includes portions of Underscore.js
30106 * http://documentcloud.github.com/underscore/
30107 * (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
30108 * Released under the MIT License.
30109 */
30110
30111 /*
30112 SIMPLE STYLE GUIDE:
30113
30114 this.x === public function
30115 this._x === internal - only use within this file
30116 this.__x === private - only use within the class
30117
30118 Globals should be all caps
30119 */
30120
30121 var init_type; // MODULE or SNIPPET loader
30122 // allow bundlers to specify how extra code (recorder bundle) should be loaded
30123 // eslint-disable-next-line no-unused-vars
30124 var load_extra_bundle = function(src, _onload) {
30125 throw new Error(src + ' not available in this build.');
30126 };
30127
30128 var mixpanel_master; // main mixpanel instance / object
30129 var INIT_MODULE = 0;
30130 var INIT_SNIPPET = 1;
30131
30132 var IDENTITY_FUNC = function(x) {return x;};
30133
30134 /** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';
30135 /** @const */ var PAYLOAD_TYPE_BASE64 = 'base64';
30136 /** @const */ var PAYLOAD_TYPE_JSON = 'json';
30137 /** @const */ var DEVICE_ID_PREFIX = '$device:';
30138
30139
30140 /*
30141 * Dynamic... constants? Is that an oxymoron?
30142 */
30143 // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
30144 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
30145 var USE_XHR = (win.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
30146
30147 // IE<10 does not support cross-origin XHR's but script tags
30148 // with defer won't block window.onload; ENQUEUE_REQUESTS
30149 // should only be true for Opera<12
30150 var ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);
30151
30152 // save reference to navigator.sendBeacon so it can be minified
30153 var sendBeacon = null;
30154 if (navigator['sendBeacon']) {
30155 sendBeacon = function() {
30156 // late reference to navigator.sendBeacon to allow patching/spying
30157 return navigator['sendBeacon'].apply(navigator, arguments);
30158 };
30159 }
30160
30161 var DEFAULT_API_ROUTES = {
30162 'track': 'track/',
30163 'engage': 'engage/',
30164 'groups': 'groups/',
30165 'record': 'record/',
30166 'flags': 'flags/'
30167 };
30168
30169 /*
30170 * Module-level globals
30171 */
30172 var DEFAULT_CONFIG = {
30173 'api_host': 'https://api-js.mixpanel.com',
30174 'api_hosts': {},
30175 'api_routes': DEFAULT_API_ROUTES,
30176 'api_extra_query_params': {},
30177 'api_method': 'POST',
30178 'api_transport': 'XHR',
30179 'api_payload_format': PAYLOAD_TYPE_BASE64,
30180 'app_host': 'https://mixpanel.com',
30181 'autocapture': false,
30182 'cdn': 'https://cdn.mxpnl.com',
30183 'cross_site_cookie': false,
30184 'cross_subdomain_cookie': true,
30185 'error_reporter': NOOP_FUNC,
30186 'flags': false,
30187 'persistence': 'cookie',
30188 'persistence_name': '',
30189 'cookie_domain': '',
30190 'cookie_name': '',
30191 'loaded': NOOP_FUNC,
30192 'mp_loader': null,
30193 'track_marketing': true,
30194 'track_pageview': false,
30195 'skip_first_touch_marketing': false,
30196 'store_google': true,
30197 'stop_utm_persistence': false,
30198 'save_referrer': true,
30199 'test': false,
30200 'verbose': false,
30201 'img': false,
30202 'debug': false,
30203 'track_links_timeout': 300,
30204 'cookie_expiration': 365,
30205 'upgrade': false,
30206 'disable_persistence': false,
30207 'disable_cookie': false,
30208 'secure_cookie': false,
30209 'ip': true,
30210 'opt_out_tracking_by_default': false,
30211 'opt_out_persistence_by_default': false,
30212 'opt_out_tracking_persistence_type': 'localStorage',
30213 'opt_out_tracking_cookie_prefix': null,
30214 'property_blacklist': [],
30215 'xhr_headers': {}, // { header: value, header2: value }
30216 'ignore_dnt': false,
30217 'batch_requests': true,
30218 'batch_size': 50,
30219 'batch_flush_interval_ms': 5000,
30220 'batch_request_timeout_ms': 90000,
30221 'batch_autostart': true,
30222 'hooks': {},
30223 'record_block_class': new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$'),
30224 'record_block_selector': 'img, video, audio',
30225 'record_canvas': false,
30226 'record_collect_fonts': false,
30227 'record_heatmap_data': false,
30228 'record_idle_timeout_ms': 30 * 60 * 1000, // 30 minutes
30229 'record_mask_text_class': new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$'),
30230 'record_mask_text_selector': '*',
30231 'record_max_ms': MAX_RECORDING_MS,
30232 'record_min_ms': 0,
30233 'record_sessions_percent': 0,
30234 'recorder_src': 'https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js'
30235 };
30236
30237 var DOM_LOADED = false;
30238
30239 /**
30240 * Mixpanel Library Object
30241 * @constructor
30242 */
30243 var MixpanelLib = function() {};
30244
30245
30246 /**
30247 * create_mplib(token:string, config:object, name:string)
30248 *
30249 * This function is used by the init method of MixpanelLib objects
30250 * as well as the main initializer at the end of the JSLib (that
30251 * initializes document.mixpanel as well as any additional instances
30252 * declared before this file has loaded).
30253 */
30254 var create_mplib = function(token, config, name) {
30255 var instance,
30256 target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];
30257
30258 if (target && init_type === INIT_MODULE) {
30259 instance = target;
30260 } else {
30261 if (target && !_.isArray(target)) {
30262 console$1.error('You have already initialized ' + name);
30263 return;
30264 }
30265 instance = new MixpanelLib();
30266 }
30267
30268 instance._cached_groups = {}; // cache groups in a pool
30269
30270 instance._init(token, config, name);
30271
30272 instance['people'] = new MixpanelPeople();
30273 instance['people']._init(instance);
30274
30275 if (!instance.get_config('skip_first_touch_marketing')) {
30276 // We need null UTM params in the object because
30277 // UTM parameters act as a tuple. If any UTM param
30278 // is present, then we set all UTM params including
30279 // empty ones together
30280 var utm_params = _.info.campaignParams(null);
30281 var initial_utm_params = {};
30282 var has_utm = false;
30283 _.each(utm_params, function(utm_value, utm_key) {
30284 initial_utm_params['initial_' + utm_key] = utm_value;
30285 if (utm_value) {
30286 has_utm = true;
30287 }
30288 });
30289 if (has_utm) {
30290 instance['people'].set_once(initial_utm_params);
30291 }
30292 }
30293
30294 // if any instance on the page has debug = true, we set the
30295 // global debug to be true
30296 Config.DEBUG = Config.DEBUG || instance.get_config('debug');
30297
30298 // if target is not defined, we called init after the lib already
30299 // loaded, so there won't be an array of things to execute
30300 if (!_.isUndefined(target) && _.isArray(target)) {
30301 // Crunch through the people queue first - we queue this data up &
30302 // flush on identify, so it's better to do all these operations first
30303 instance._execute_array.call(instance['people'], target['people']);
30304 instance._execute_array(target);
30305 }
30306
30307 return instance;
30308 };
30309
30310 // Initialization methods
30311
30312 /**
30313 * This function initializes a new instance of the Mixpanel tracking object.
30314 * All new instances are added to the main mixpanel object as sub properties (such as
30315 * mixpanel.library_name) and also returned by this function. To define a
30316 * second instance on the page, you would call:
30317 *
30318 * mixpanel.init('new token', { your: 'config' }, 'library_name');
30319 *
30320 * and use it like so:
30321 *
30322 * mixpanel.library_name.track(...);
30323 *
30324 * @param {String} token Your Mixpanel API token
30325 * @param {Object} [config] A dictionary of config options to override. <a href="https://github.com/mixpanel/mixpanel-js/blob/v2.46.0/src/mixpanel-core.js#L88-L127">See a list of default config options</a>.
30326 * @param {String} [name] The name for the new mixpanel instance that you want created
30327 */
30328 MixpanelLib.prototype.init = function (token, config, name) {
30329 if (_.isUndefined(name)) {
30330 this.report_error('You must name your new library: init(token, config, name)');
30331 return;
30332 }
30333 if (name === PRIMARY_INSTANCE_NAME) {
30334 this.report_error('You must initialize the main mixpanel object right after you include the Mixpanel js snippet');
30335 return;
30336 }
30337
30338 var instance = create_mplib(token, config, name);
30339 mixpanel_master[name] = instance;
30340 instance._loaded();
30341
30342 return instance;
30343 };
30344
30345 // mixpanel._init(token:string, config:object, name:string)
30346 //
30347 // This function sets up the current instance of the mixpanel
30348 // library. The difference between this method and the init(...)
30349 // method is this one initializes the actual instance, whereas the
30350 // init(...) method sets up a new library and calls _init on it.
30351 //
30352 MixpanelLib.prototype._init = function(token, config, name) {
30353 config = config || {};
30354
30355 this['__loaded'] = true;
30356 this['config'] = {};
30357
30358 var variable_features = {};
30359
30360 // default to JSON payload for standard mixpanel.com API hosts
30361 if (!('api_payload_format' in config)) {
30362 var api_host = config['api_host'] || DEFAULT_CONFIG['api_host'];
30363 if (api_host.match(/\.mixpanel\.com/)) {
30364 variable_features['api_payload_format'] = PAYLOAD_TYPE_JSON;
30365 }
30366 }
30367
30368 this.set_config(_.extend({}, DEFAULT_CONFIG, variable_features, config, {
30369 'name': name,
30370 'token': token,
30371 'callback_fn': ((name === PRIMARY_INSTANCE_NAME) ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc'
30372 }));
30373
30374 this['_jsc'] = NOOP_FUNC;
30375
30376 this.__dom_loaded_queue = [];
30377 this.__request_queue = [];
30378 this.__disabled_events = [];
30379 this._flags = {
30380 'disable_all_events': false,
30381 'identify_called': false
30382 };
30383
30384 // set up request queueing/batching
30385 this.request_batchers = {};
30386 this._batch_requests = this.get_config('batch_requests');
30387 if (this._batch_requests) {
30388 if (!_.localStorage.is_supported(true) || !USE_XHR) {
30389 this._batch_requests = false;
30390 console$1.log('Turning off Mixpanel request-queueing; needs XHR and localStorage support');
30391 _.each(this.get_batcher_configs(), function(batcher_config) {
30392 console$1.log('Clearing batch queue ' + batcher_config.queue_key);
30393 _.localStorage.remove(batcher_config.queue_key);
30394 });
30395 } else {
30396 this.init_batchers();
30397 if (sendBeacon && win.addEventListener) {
30398 // Before page closes or hides (user tabs away etc), attempt to flush any events
30399 // queued up via navigator.sendBeacon. Since sendBeacon doesn't report success/failure,
30400 // events will not be removed from the persistent store; if the site is loaded again,
30401 // the events will be flushed again on startup and deduplicated on the Mixpanel server
30402 // side.
30403 // There is no reliable way to capture only page close events, so we lean on the
30404 // visibilitychange and pagehide events as recommended at
30405 // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes.
30406 // These events fire when the user clicks away from the current page/tab, so will occur
30407 // more frequently than page unload, but are the only mechanism currently for capturing
30408 // this scenario somewhat reliably.
30409 var flush_on_unload = _.bind(function() {
30410 if (!this.request_batchers.events.stopped) {
30411 this.request_batchers.events.flush({unloading: true});
30412 }
30413 }, this);
30414 win.addEventListener('pagehide', function(ev) {
30415 if (ev['persisted']) {
30416 flush_on_unload();
30417 }
30418 });
30419 win.addEventListener('visibilitychange', function() {
30420 if (document$1['visibilityState'] === 'hidden') {
30421 flush_on_unload();
30422 }
30423 });
30424 }
30425 }
30426 }
30427
30428 this['persistence'] = this['cookie'] = new MixpanelPersistence(this['config']);
30429 this.unpersisted_superprops = {};
30430 this._gdpr_init();
30431
30432 var uuid = _.UUID();
30433 if (!this.get_distinct_id()) {
30434 // There is no need to set the distinct id
30435 // or the device id if something was already stored
30436 // in the persitence
30437 this.register_once({
30438 'distinct_id': DEVICE_ID_PREFIX + uuid,
30439 '$device_id': uuid
30440 }, '');
30441 }
30442
30443 this.flags = new FeatureFlagManager({
30444 getFullApiRoute: _.bind(function() {
30445 return this.get_api_host('flags') + '/' + this.get_config('api_routes')['flags'];
30446 }, this),
30447 getConfigFunc: _.bind(this.get_config, this),
30448 setConfigFunc: _.bind(this.set_config, this),
30449 getPropertyFunc: _.bind(this.get_property, this),
30450 trackingFunc: _.bind(this.track, this)
30451 });
30452 this.flags.init();
30453 this['flags'] = this.flags;
30454
30455 this.autocapture = new Autocapture(this);
30456 this.autocapture.init();
30457
30458 this._init_tab_id();
30459 this._check_and_start_session_recording();
30460 };
30461
30462 /**
30463 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
30464 * This is primarily used for session recording, where data must be isolated to the current tab.
30465 */
30466 MixpanelLib.prototype._init_tab_id = function() {
30467 if (this.get_config('disable_persistence')) {
30468 console$1.log('Tab ID initialization skipped due to disable_persistence config');
30469 } else if (_.sessionStorage.is_supported()) {
30470 try {
30471 var key_suffix = this.get_config('name') + '_' + this.get_config('token');
30472 var tab_id_key = 'mp_tab_id_' + key_suffix;
30473
30474 // A flag is used to determine if sessionStorage is copied over and we need to generate a new tab ID.
30475 // This enforces a unique ID in the cases like duplicated tab, window.open(...)
30476 var should_generate_new_tab_id_key = 'mp_gen_new_tab_id_' + key_suffix;
30477 if (_.sessionStorage.get(should_generate_new_tab_id_key) || !_.sessionStorage.get(tab_id_key)) {
30478 _.sessionStorage.set(tab_id_key, '$tab-' + _.UUID());
30479 }
30480
30481 _.sessionStorage.set(should_generate_new_tab_id_key, '1');
30482 this.tab_id = _.sessionStorage.get(tab_id_key);
30483
30484 // Remove the flag when the tab is unloaded to indicate the stored tab ID can be reused. This event is not reliable to detect all page unloads,
30485 // but reliable in cases where the user remains in the tab e.g. a refresh or href navigation.
30486 // If the flag is absent, this indicates to the next SDK instance that we can reuse the stored tab_id.
30487 win.addEventListener('beforeunload', function () {
30488 _.sessionStorage.remove(should_generate_new_tab_id_key);
30489 });
30490 } catch(err) {
30491 this.report_error('Error initializing tab id', err);
30492 }
30493 } else {
30494 this.report_error('Session storage is not supported, cannot keep track of unique tab ID.');
30495 }
30496 };
30497
30498 MixpanelLib.prototype.get_tab_id = function () {
30499 return this.tab_id || null;
30500 };
30501
30502 MixpanelLib.prototype._should_load_recorder = function () {
30503 if (this.get_config('disable_persistence')) {
30504 console$1.log('Load recorder check skipped due to disable_persistence config');
30505 return Promise.resolve(false);
30506 }
30507
30508 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
30509 var tab_id = this.get_tab_id();
30510 return recording_registry_idb.init()
30511 .then(function () {
30512 return recording_registry_idb.getAll();
30513 })
30514 .then(function (recordings) {
30515 for (var i = 0; i < recordings.length; i++) {
30516 // if there are expired recordings in the registry, we should load the recorder to flush them
30517 // if there's a recording for this tab id, we should load the recorder to continue the recording
30518 if (isRecordingExpired(recordings[i]) || recordings[i]['tabId'] === tab_id) {
30519 return true;
30520 }
30521 }
30522 return false;
30523 })
30524 .catch(_.bind(function (err) {
30525 this.report_error('Error checking recording registry', err);
30526 }, this));
30527 };
30528
30529 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
30530 if (!win['MutationObserver']) {
30531 console$1.critical('Browser does not support MutationObserver; skipping session recording');
30532 return;
30533 }
30534
30535 var loadRecorder = _.bind(function(startNewIfInactive) {
30536 var handleLoadedRecorder = _.bind(function() {
30537 this._recorder = this._recorder || new win['__mp_recorder'](this);
30538 this._recorder['resumeRecording'](startNewIfInactive);
30539 }, this);
30540
30541 if (_.isUndefined(win['__mp_recorder'])) {
30542 load_extra_bundle(this.get_config('recorder_src'), handleLoadedRecorder);
30543 } else {
30544 handleLoadedRecorder();
30545 }
30546 }, this);
30547
30548 /**
30549 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
30550 * Otherwise, if the recording registry has any records then it's likely there's a recording in progress or orphaned data that needs to be flushed.
30551 */
30552 var is_sampled = this.get_config('record_sessions_percent') > 0 && Math.random() * 100 <= this.get_config('record_sessions_percent');
30553 if (force_start || is_sampled) {
30554 loadRecorder(true);
30555 } else {
30556 this._should_load_recorder()
30557 .then(function (shouldLoad) {
30558 if (shouldLoad) {
30559 loadRecorder(false);
30560 }
30561 });
30562 }
30563 });
30564
30565 MixpanelLib.prototype.start_session_recording = function () {
30566 this._check_and_start_session_recording(true);
30567 };
30568
30569 MixpanelLib.prototype.stop_session_recording = function () {
30570 if (this._recorder) {
30571 return this._recorder['stopRecording']();
30572 }
30573 return Promise.resolve();
30574 };
30575
30576 MixpanelLib.prototype.pause_session_recording = function () {
30577 if (this._recorder) {
30578 return this._recorder['pauseRecording']();
30579 }
30580 return Promise.resolve();
30581 };
30582
30583 MixpanelLib.prototype.resume_session_recording = function () {
30584 if (this._recorder) {
30585 return this._recorder['resumeRecording']();
30586 }
30587 return Promise.resolve();
30588 };
30589
30590 MixpanelLib.prototype.is_recording_heatmap_data = function () {
30591 return this._get_session_replay_id() && this.get_config('record_heatmap_data');
30592 };
30593
30594 MixpanelLib.prototype.get_session_recording_properties = function () {
30595 var props = {};
30596 var replay_id = this._get_session_replay_id();
30597 if (replay_id) {
30598 props['$mp_replay_id'] = replay_id;
30599 }
30600 return props;
30601 };
30602
30603 MixpanelLib.prototype.get_session_replay_url = function () {
30604 var replay_url = null;
30605 var replay_id = this._get_session_replay_id();
30606 if (replay_id) {
30607 var query_params = _.HTTPBuildQuery({
30608 'replay_id': replay_id,
30609 'distinct_id': this.get_distinct_id(),
30610 'token': this.get_config('token')
30611 });
30612 replay_url = 'https://mixpanel.com/projects/replay-redirect?' + query_params;
30613 }
30614 return replay_url;
30615 };
30616
30617 MixpanelLib.prototype._get_session_replay_id = function () {
30618 var replay_id = null;
30619 if (this._recorder) {
30620 replay_id = this._recorder['replayId'];
30621 }
30622 return replay_id || null;
30623 };
30624
30625 // "private" public method to reach into the recorder in test cases
30626 MixpanelLib.prototype.__get_recorder = function () {
30627 return this._recorder;
30628 };
30629
30630 // Private methods
30631
30632 MixpanelLib.prototype._loaded = function() {
30633 this.get_config('loaded')(this);
30634 this._set_default_superprops();
30635 this['people'].set_once(this['persistence'].get_referrer_info());
30636
30637 // `store_google` is now deprecated and previously stored UTM parameters are cleared
30638 // from persistence by default.
30639 if (this.get_config('store_google') && this.get_config('stop_utm_persistence')) {
30640 var utm_params = _.info.campaignParams(null);
30641 _.each(utm_params, function(_utm_value, utm_key) {
30642 // We need to unregister persisted UTM parameters so old values
30643 // are not mixed with the new UTM parameters
30644 this.unregister(utm_key);
30645 }.bind(this));
30646 }
30647 };
30648
30649 // update persistence with info on referrer, UTM params, etc
30650 MixpanelLib.prototype._set_default_superprops = function() {
30651 this['persistence'].update_search_keyword(document$1.referrer);
30652 // Registering super properties for UTM persistence by 'store_google' is deprecated.
30653 if (this.get_config('store_google') && !this.get_config('stop_utm_persistence')) {
30654 this.register(_.info.campaignParams());
30655 }
30656 if (this.get_config('save_referrer')) {
30657 this['persistence'].update_referrer_info(document$1.referrer);
30658 }
30659 };
30660
30661 MixpanelLib.prototype._dom_loaded = function() {
30662 _.each(this.__dom_loaded_queue, function(item) {
30663 this._track_dom.apply(this, item);
30664 }, this);
30665
30666 if (!this.has_opted_out_tracking()) {
30667 _.each(this.__request_queue, function(item) {
30668 this._send_request.apply(this, item);
30669 }, this);
30670 }
30671
30672 delete this.__dom_loaded_queue;
30673 delete this.__request_queue;
30674 };
30675
30676 MixpanelLib.prototype._track_dom = function(DomClass, args) {
30677 if (this.get_config('img')) {
30678 this.report_error('You can\'t use DOM tracking functions with img = true.');
30679 return false;
30680 }
30681
30682 if (!DOM_LOADED) {
30683 this.__dom_loaded_queue.push([DomClass, args]);
30684 return false;
30685 }
30686
30687 var dt = new DomClass().init(this);
30688 return dt.track.apply(dt, args);
30689 };
30690
30691 /**
30692 * _prepare_callback() should be called by callers of _send_request for use
30693 * as the callback argument.
30694 *
30695 * If there is no callback, this returns null.
30696 * If we are going to make XHR/XDR requests, this returns a function.
30697 * If we are going to use script tags, this returns a string to use as the
30698 * callback GET param.
30699 */
30700 MixpanelLib.prototype._prepare_callback = function(callback, data) {
30701 if (_.isUndefined(callback)) {
30702 return null;
30703 }
30704
30705 if (USE_XHR) {
30706 var callback_function = function(response) {
30707 callback(response, data);
30708 };
30709 return callback_function;
30710 } else {
30711 // if the user gives us a callback, we store as a random
30712 // property on this instances jsc function and update our
30713 // callback string to reflect that.
30714 var jsc = this['_jsc'];
30715 var randomized_cb = '' + Math.floor(Math.random() * 100000000);
30716 var callback_string = this.get_config('callback_fn') + '[' + randomized_cb + ']';
30717 jsc[randomized_cb] = function(response) {
30718 delete jsc[randomized_cb];
30719 callback(response, data);
30720 };
30721 return callback_string;
30722 }
30723 };
30724
30725 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
30726 var succeeded = true;
30727
30728 if (ENQUEUE_REQUESTS) {
30729 this.__request_queue.push(arguments);
30730 return succeeded;
30731 }
30732
30733 var DEFAULT_OPTIONS = {
30734 method: this.get_config('api_method'),
30735 transport: this.get_config('api_transport'),
30736 verbose: this.get_config('verbose')
30737 };
30738 var body_data = null;
30739
30740 if (!callback && (_.isFunction(options) || typeof options === 'string')) {
30741 callback = options;
30742 options = null;
30743 }
30744 options = _.extend(DEFAULT_OPTIONS, options || {});
30745 if (!USE_XHR) {
30746 options.method = 'GET';
30747 }
30748 var use_post = options.method === 'POST';
30749 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === 'sendbeacon';
30750
30751 // needed to correctly format responses
30752 var verbose_mode = options.verbose;
30753 if (data['verbose']) { verbose_mode = true; }
30754
30755 if (this.get_config('test')) { data['test'] = 1; }
30756 if (verbose_mode) { data['verbose'] = 1; }
30757 if (this.get_config('img')) { data['img'] = 1; }
30758 if (!USE_XHR) {
30759 if (callback) {
30760 data['callback'] = callback;
30761 } else if (verbose_mode || this.get_config('test')) {
30762 // Verbose output (from verbose mode, or an error in test mode) is a json blob,
30763 // which by itself is not valid javascript. Without a callback, this verbose output will
30764 // cause an error when returned via jsonp, so we force a no-op callback param.
30765 // See the ECMA script spec: http://www.ecma-international.org/ecma-262/5.1/#sec-12.4
30766 data['callback'] = '(function(){})';
30767 }
30768 }
30769
30770 data['ip'] = this.get_config('ip')?1:0;
30771 data['_'] = new Date().getTime().toString();
30772
30773 if (use_post) {
30774 body_data = 'data=' + encodeURIComponent(data['data']);
30775 delete data['data'];
30776 }
30777
30778 _.extend(data, this.get_config('api_extra_query_params'));
30779
30780 url += '?' + _.HTTPBuildQuery(data);
30781
30782 var lib = this;
30783 if ('img' in data) {
30784 var img = document$1.createElement('img');
30785 img.src = url;
30786 document$1.body.appendChild(img);
30787 } else if (use_sendBeacon) {
30788 try {
30789 succeeded = sendBeacon(url, body_data);
30790 } catch (e) {
30791 lib.report_error(e);
30792 succeeded = false;
30793 }
30794 try {
30795 if (callback) {
30796 callback(succeeded ? 1 : 0);
30797 }
30798 } catch (e) {
30799 lib.report_error(e);
30800 }
30801 } else if (USE_XHR) {
30802 try {
30803 var req = new XMLHttpRequest();
30804 req.open(options.method, url, true);
30805
30806 var headers = this.get_config('xhr_headers');
30807 if (use_post) {
30808 headers['Content-Type'] = 'application/x-www-form-urlencoded';
30809 }
30810 _.each(headers, function(headerValue, headerName) {
30811 req.setRequestHeader(headerName, headerValue);
30812 });
30813
30814 if (options.timeout_ms && typeof req.timeout !== 'undefined') {
30815 req.timeout = options.timeout_ms;
30816 var start_time = new Date().getTime();
30817 }
30818
30819 // send the mp_optout cookie
30820 // withCredentials cannot be modified until after calling .open on Android and Mobile Safari
30821 req.withCredentials = true;
30822 req.onreadystatechange = function () {
30823 if (req.readyState === 4) { // XMLHttpRequest.DONE == 4, except in safari 4
30824 if (req.status === 200) {
30825 if (callback) {
30826 if (verbose_mode) {
30827 var response;
30828 try {
30829 response = _.JSONDecode(req.responseText);
30830 } catch (e) {
30831 lib.report_error(e);
30832 if (options.ignore_json_errors) {
30833 response = req.responseText;
30834 } else {
30835 return;
30836 }
30837 }
30838 callback(response);
30839 } else {
30840 callback(Number(req.responseText));
30841 }
30842 }
30843 } else {
30844 var error;
30845 if (
30846 req.timeout &&
30847 !req.status &&
30848 new Date().getTime() - start_time >= req.timeout
30849 ) {
30850 error = 'timeout';
30851 } else {
30852 error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
30853 }
30854 lib.report_error(error);
30855 if (callback) {
30856 if (verbose_mode) {
30857 var response_headers = req['responseHeaders'] || {};
30858 callback({status: 0, httpStatusCode: req['status'], error: error, retryAfter: response_headers['Retry-After']});
30859 } else {
30860 callback(0);
30861 }
30862 }
30863 }
30864 }
30865 };
30866 req.send(body_data);
30867 } catch (e) {
30868 lib.report_error(e);
30869 succeeded = false;
30870 }
30871 } else {
30872 var script = document$1.createElement('script');
30873 script.type = 'text/javascript';
30874 script.async = true;
30875 script.defer = true;
30876 script.src = url;
30877 var s = document$1.getElementsByTagName('script')[0];
30878 s.parentNode.insertBefore(script, s);
30879 }
30880
30881 return succeeded;
30882 };
30883
30884 /**
30885 * _execute_array() deals with processing any mixpanel function
30886 * calls that were called before the Mixpanel library were loaded
30887 * (and are thus stored in an array so they can be called later)
30888 *
30889 * Note: we fire off all the mixpanel function calls && user defined
30890 * functions BEFORE we fire off mixpanel tracking calls. This is so
30891 * identify/register/set_config calls can properly modify early
30892 * tracking calls.
30893 *
30894 * @param {Array} array
30895 */
30896 MixpanelLib.prototype._execute_array = function(array) {
30897 var fn_name, alias_calls = [], other_calls = [], tracking_calls = [];
30898 _.each(array, function(item) {
30899 if (item) {
30900 fn_name = item[0];
30901 if (_.isArray(fn_name)) {
30902 tracking_calls.push(item); // chained call e.g. mixpanel.get_group().set()
30903 } else if (typeof(item) === 'function') {
30904 item.call(this);
30905 } else if (_.isArray(item) && fn_name === 'alias') {
30906 alias_calls.push(item);
30907 } else if (_.isArray(item) && fn_name.indexOf('track') !== -1 && typeof(this[fn_name]) === 'function') {
30908 tracking_calls.push(item);
30909 } else {
30910 other_calls.push(item);
30911 }
30912 }
30913 }, this);
30914
30915 var execute = function(calls, context) {
30916 _.each(calls, function(item) {
30917 if (_.isArray(item[0])) {
30918 // chained call
30919 var caller = context;
30920 _.each(item, function(call) {
30921 caller = caller[call[0]].apply(caller, call.slice(1));
30922 });
30923 } else {
30924 this[item[0]].apply(this, item.slice(1));
30925 }
30926 }, context);
30927 };
30928
30929 execute(alias_calls, this);
30930 execute(other_calls, this);
30931 execute(tracking_calls, this);
30932 };
30933
30934 // request queueing utils
30935
30936 MixpanelLib.prototype.are_batchers_initialized = function() {
30937 return !!this.request_batchers.events;
30938 };
30939
30940 MixpanelLib.prototype.get_batcher_configs = function() {
30941 var queue_prefix = '__mpq_' + this.get_config('token');
30942 this._batcher_configs = this._batcher_configs || {
30943 events: {type: 'events', api_name: 'track', queue_key: queue_prefix + '_ev'},
30944 people: {type: 'people', api_name: 'engage', queue_key: queue_prefix + '_pp'},
30945 groups: {type: 'groups', api_name: 'groups', queue_key: queue_prefix + '_gr'}
30946 };
30947 return this._batcher_configs;
30948 };
30949
30950 MixpanelLib.prototype.init_batchers = function() {
30951 if (!this.are_batchers_initialized()) {
30952 var batcher_for = _.bind(function(attrs) {
30953 return new RequestBatcher(
30954 attrs.queue_key,
30955 {
30956 libConfig: this['config'],
30957 errorReporter: this.get_config('error_reporter'),
30958 sendRequestFunc: _.bind(function(data, options, cb) {
30959 var api_routes = this.get_config('api_routes');
30960 this._send_request(
30961 this.get_api_host(attrs.api_name) + '/' + api_routes[attrs.api_name],
30962 this._encode_data_for_request(data),
30963 options,
30964 this._prepare_callback(cb, data)
30965 );
30966 }, this),
30967 beforeSendHook: _.bind(function(item) {
30968 return this._run_hook('before_send_' + attrs.type, item);
30969 }, this),
30970 stopAllBatchingFunc: _.bind(this.stop_batch_senders, this),
30971 usePersistence: true,
30972 }
30973 );
30974 }, this);
30975 var batcher_configs = this.get_batcher_configs();
30976 this.request_batchers = {
30977 events: batcher_for(batcher_configs.events),
30978 people: batcher_for(batcher_configs.people),
30979 groups: batcher_for(batcher_configs.groups)
30980 };
30981 }
30982 if (this.get_config('batch_autostart')) {
30983 this.start_batch_senders();
30984 }
30985 };
30986
30987 MixpanelLib.prototype.start_batch_senders = function() {
30988 this._batchers_were_started = true;
30989 if (this.are_batchers_initialized()) {
30990 this._batch_requests = true;
30991 _.each(this.request_batchers, function(batcher) {
30992 batcher.start();
30993 });
30994 }
30995 };
30996
30997 MixpanelLib.prototype.stop_batch_senders = function() {
30998 this._batch_requests = false;
30999 _.each(this.request_batchers, function(batcher) {
31000 batcher.stop();
31001 batcher.clear();
31002 });
31003 };
31004
31005 /**
31006 * push() keeps the standard async-array-push
31007 * behavior around after the lib is loaded.
31008 * This is only useful for external integrations that
31009 * do not wish to rely on our convenience methods
31010 * (created in the snippet).
31011 *
31012 * ### Usage:
31013 * mixpanel.push(['register', { a: 'b' }]);
31014 *
31015 * @param {Array} item A [function_name, args...] array to be executed
31016 */
31017 MixpanelLib.prototype.push = function(item) {
31018 this._execute_array([item]);
31019 };
31020
31021 /**
31022 * Disable events on the Mixpanel object. If passed no arguments,
31023 * this function disables tracking of any event. If passed an
31024 * array of event names, those events will be disabled, but other
31025 * events will continue to be tracked.
31026 *
31027 * Note: this function does not stop other mixpanel functions from
31028 * firing, such as register() or people.set().
31029 *
31030 * @param {Array} [events] An array of event names to disable
31031 */
31032 MixpanelLib.prototype.disable = function(events) {
31033 if (typeof(events) === 'undefined') {
31034 this._flags.disable_all_events = true;
31035 } else {
31036 this.__disabled_events = this.__disabled_events.concat(events);
31037 }
31038 };
31039
31040 MixpanelLib.prototype._encode_data_for_request = function(data) {
31041 var encoded_data = JSONStringify(data);
31042 if (this.get_config('api_payload_format') === PAYLOAD_TYPE_BASE64) {
31043 encoded_data = _.base64Encode(encoded_data);
31044 }
31045 return {'data': encoded_data};
31046 };
31047
31048 // internal method for handling track vs batch-enqueue logic
31049 MixpanelLib.prototype._track_or_batch = function(options, callback) {
31050 var truncated_data = _.truncate(options.data, 255);
31051 var endpoint = options.endpoint;
31052 var batcher = options.batcher;
31053 var should_send_immediately = options.should_send_immediately;
31054 var send_request_options = options.send_request_options || {};
31055 callback = callback || NOOP_FUNC;
31056
31057 var request_enqueued_or_initiated = true;
31058 var send_request_immediately = _.bind(function() {
31059 if (!send_request_options.skip_hooks) {
31060 truncated_data = this._run_hook('before_send_' + options.type, truncated_data);
31061 }
31062 if (truncated_data) {
31063 console$1.log('MIXPANEL REQUEST:');
31064 console$1.log(truncated_data);
31065 return this._send_request(
31066 endpoint,
31067 this._encode_data_for_request(truncated_data),
31068 send_request_options,
31069 this._prepare_callback(callback, truncated_data)
31070 );
31071 } else {
31072 return null;
31073 }
31074 }, this);
31075
31076 if (this._batch_requests && !should_send_immediately) {
31077 batcher.enqueue(truncated_data).then(function(succeeded) {
31078 if (succeeded) {
31079 callback(1, truncated_data);
31080 } else {
31081 send_request_immediately();
31082 }
31083 });
31084 } else {
31085 request_enqueued_or_initiated = send_request_immediately();
31086 }
31087
31088 return request_enqueued_or_initiated && truncated_data;
31089 };
31090
31091 /**
31092 * Track an event. This is the most important and
31093 * frequently used Mixpanel function.
31094 *
31095 * ### Usage:
31096 *
31097 * // track an event named 'Registered'
31098 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
31099 *
31100 * // track an event using navigator.sendBeacon
31101 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
31102 *
31103 * To track link clicks or form submissions, see track_links() or track_forms().
31104 *
31105 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
31106 * @param {Object} [properties] A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself.
31107 * @param {Object} [options] Optional configuration for this track request.
31108 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
31109 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
31110 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
31111 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
31112 * with the tracking payload sent to the API server is returned; otherwise false.
31113 */
31114 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
31115 if (!callback && typeof options === 'function') {
31116 callback = options;
31117 options = null;
31118 }
31119 options = options || {};
31120 var transport = options['transport']; // external API, don't minify 'transport' prop
31121 if (transport) {
31122 options.transport = transport; // 'transport' prop name can be minified internally
31123 }
31124 var should_send_immediately = options['send_immediately'];
31125 if (typeof callback !== 'function') {
31126 callback = NOOP_FUNC;
31127 }
31128
31129 if (_.isUndefined(event_name)) {
31130 this.report_error('No event name provided to mixpanel.track');
31131 return;
31132 }
31133
31134 if (this._event_is_disabled(event_name)) {
31135 callback(0);
31136 return;
31137 }
31138
31139 // set defaults
31140 properties = _.extend({}, properties);
31141 properties['token'] = this.get_config('token');
31142
31143 // set $duration if time_event was previously called for this event
31144 var start_timestamp = this['persistence'].remove_event_timer(event_name);
31145 if (!_.isUndefined(start_timestamp)) {
31146 var duration_in_ms = new Date().getTime() - start_timestamp;
31147 properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
31148 }
31149
31150 this._set_default_superprops();
31151
31152 var marketing_properties = this.get_config('track_marketing')
31153 ? _.info.marketingParams()
31154 : {};
31155
31156 // note: extend writes to the first object, so lets make sure we
31157 // don't write to the persistence properties object and info
31158 // properties object by passing in a new object
31159
31160 // update properties with pageview info and super-properties
31161 properties = _.extend(
31162 {},
31163 _.info.properties({'mp_loader': this.get_config('mp_loader')}),
31164 marketing_properties,
31165 this['persistence'].properties(),
31166 this.unpersisted_superprops,
31167 this.get_session_recording_properties(),
31168 properties
31169 );
31170
31171 var property_blacklist = this.get_config('property_blacklist');
31172 if (_.isArray(property_blacklist)) {
31173 _.each(property_blacklist, function(blacklisted_prop) {
31174 delete properties[blacklisted_prop];
31175 });
31176 } else {
31177 this.report_error('Invalid value for property_blacklist config: ' + property_blacklist);
31178 }
31179
31180 var data = {
31181 'event': event_name,
31182 'properties': properties
31183 };
31184 var ret = this._track_or_batch({
31185 type: 'events',
31186 data: data,
31187 endpoint: this.get_api_host('events') + '/' + this.get_config('api_routes')['track'],
31188 batcher: this.request_batchers.events,
31189 should_send_immediately: should_send_immediately,
31190 send_request_options: options
31191 }, callback);
31192
31193 return ret;
31194 });
31195
31196 /**
31197 * Register the current user into one/many groups.
31198 *
31199 * ### Usage:
31200 *
31201 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
31202 * mixpanel.set_group('company', 'mixpanel')
31203 * mixpanel.set_group('company', 128746312)
31204 *
31205 * @param {String} group_key Group key
31206 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
31207 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31208 *
31209 */
31210 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
31211 if (!_.isArray(group_ids)) {
31212 group_ids = [group_ids];
31213 }
31214 var prop = {};
31215 prop[group_key] = group_ids;
31216 this.register(prop);
31217 return this['people'].set(group_key, group_ids, callback);
31218 });
31219
31220 /**
31221 * Add a new group for this user.
31222 *
31223 * ### Usage:
31224 *
31225 * mixpanel.add_group('company', 'mixpanel')
31226 *
31227 * @param {String} group_key Group key
31228 * @param {*} group_id A valid Mixpanel property type
31229 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31230 */
31231 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
31232 var old_values = this.get_property(group_key);
31233 var prop = {};
31234 if (old_values === undefined) {
31235 prop[group_key] = [group_id];
31236 this.register(prop);
31237 } else {
31238 if (old_values.indexOf(group_id) === -1) {
31239 old_values.push(group_id);
31240 prop[group_key] = old_values;
31241 this.register(prop);
31242 }
31243 }
31244 return this['people'].union(group_key, group_id, callback);
31245 });
31246
31247 /**
31248 * Remove a group from this user.
31249 *
31250 * ### Usage:
31251 *
31252 * mixpanel.remove_group('company', 'mixpanel')
31253 *
31254 * @param {String} group_key Group key
31255 * @param {*} group_id A valid Mixpanel property type
31256 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31257 */
31258 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
31259 var old_value = this.get_property(group_key);
31260 // if the value doesn't exist, the persistent store is unchanged
31261 if (old_value !== undefined) {
31262 var idx = old_value.indexOf(group_id);
31263 if (idx > -1) {
31264 old_value.splice(idx, 1);
31265 this.register({group_key: old_value});
31266 }
31267 if (old_value.length === 0) {
31268 this.unregister(group_key);
31269 }
31270 }
31271 return this['people'].remove(group_key, group_id, callback);
31272 });
31273
31274 /**
31275 * Track an event with specific groups.
31276 *
31277 * ### Usage:
31278 *
31279 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
31280 *
31281 * @param {String} event_name The name of the event (see `mixpanel.track()`)
31282 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
31283 * @param {Object=} groups An object mapping group name keys to one or more values
31284 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31285 */
31286 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
31287 var tracking_props = _.extend({}, properties || {});
31288 _.each(groups, function(v, k) {
31289 if (v !== null && v !== undefined) {
31290 tracking_props[k] = v;
31291 }
31292 });
31293 return this.track(event_name, tracking_props, callback);
31294 });
31295
31296 MixpanelLib.prototype._create_map_key = function (group_key, group_id) {
31297 return group_key + '_' + JSON.stringify(group_id);
31298 };
31299
31300 MixpanelLib.prototype._remove_group_from_cache = function (group_key, group_id) {
31301 delete this._cached_groups[this._create_map_key(group_key, group_id)];
31302 };
31303
31304 /**
31305 * Look up reference to a Mixpanel group
31306 *
31307 * ### Usage:
31308 *
31309 * mixpanel.get_group(group_key, group_id)
31310 *
31311 * @param {String} group_key Group key
31312 * @param {Object} group_id A valid Mixpanel property type
31313 * @returns {Object} A MixpanelGroup identifier
31314 */
31315 MixpanelLib.prototype.get_group = function (group_key, group_id) {
31316 var map_key = this._create_map_key(group_key, group_id);
31317 var group = this._cached_groups[map_key];
31318 if (group === undefined || group._group_key !== group_key || group._group_id !== group_id) {
31319 group = new MixpanelGroup();
31320 group._init(this, group_key, group_id);
31321 this._cached_groups[map_key] = group;
31322 }
31323 return group;
31324 };
31325
31326 /**
31327 * Track a default Mixpanel page view event, which includes extra default event properties to
31328 * improve page view data.
31329 *
31330 * ### Usage:
31331 *
31332 * // track a default $mp_web_page_view event
31333 * mixpanel.track_pageview();
31334 *
31335 * // track a page view event with additional event properties
31336 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
31337 *
31338 * // example approach to track page views on different page types as event properties
31339 * mixpanel.track_pageview({'page': 'pricing'});
31340 * mixpanel.track_pageview({'page': 'homepage'});
31341 *
31342 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
31343 * // individual pages on the same site or product. Use cases for custom event_name may be page
31344 * // views on different products or internal applications that are considered completely separate
31345 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
31346 *
31347 * ### Notes:
31348 *
31349 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
31350 * may be turned on for tracking page loads automatically.
31351 *
31352 * // track only page loads
31353 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
31354 *
31355 * // track when the URL changes in any manner
31356 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
31357 *
31358 * // track when the URL changes, ignoring any changes in the hash part
31359 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
31360 *
31361 * // track when the path changes, ignoring any query parameter or hash changes
31362 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
31363 *
31364 * @param {Object} [properties] An optional set of additional properties to send with the page view event
31365 * @param {Object} [options] Page view tracking options
31366 * @param {String} [options.event_name] - Alternate name for the tracking event
31367 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
31368 * with the tracking payload sent to the API server is returned; otherwise false.
31369 */
31370 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
31371 if (typeof properties !== 'object') {
31372 properties = {};
31373 }
31374 options = options || {};
31375 var event_name = options['event_name'] || '$mp_web_page_view';
31376
31377 var default_page_properties = _.extend(
31378 _.info.mpPageViewProperties(),
31379 _.info.campaignParams(),
31380 _.info.clickParams()
31381 );
31382
31383 var event_properties = _.extend(
31384 {},
31385 default_page_properties,
31386 properties
31387 );
31388
31389 return this.track(event_name, event_properties);
31390 });
31391
31392 /**
31393 * Track clicks on a set of document elements. Selector must be a
31394 * valid query. Elements must exist on the page at the time track_links is called.
31395 *
31396 * ### Usage:
31397 *
31398 * // track click for link id #nav
31399 * mixpanel.track_links('#nav', 'Clicked Nav Link');
31400 *
31401 * ### Notes:
31402 *
31403 * This function will wait up to 300 ms for the Mixpanel
31404 * servers to respond. If they have not responded by that time
31405 * it will head to the link without ensuring that your event
31406 * has been tracked. To configure this timeout please see the
31407 * set_config() documentation below.
31408 *
31409 * If you pass a function in as the properties argument, the
31410 * function will receive the DOMElement that triggered the
31411 * event as an argument. You are expected to return an object
31412 * from the function; any properties defined on this object
31413 * will be sent to mixpanel as event properties.
31414 *
31415 * @type {Function}
31416 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
31417 * @param {String} event_name The name of the event to track
31418 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
31419 */
31420 MixpanelLib.prototype.track_links = function() {
31421 return this._track_dom.call(this, LinkTracker, arguments);
31422 };
31423
31424 /**
31425 * Track form submissions. Selector must be a valid query.
31426 *
31427 * ### Usage:
31428 *
31429 * // track submission for form id 'register'
31430 * mixpanel.track_forms('#register', 'Created Account');
31431 *
31432 * ### Notes:
31433 *
31434 * This function will wait up to 300 ms for the mixpanel
31435 * servers to respond, if they have not responded by that time
31436 * it will head to the link without ensuring that your event
31437 * has been tracked. To configure this timeout please see the
31438 * set_config() documentation below.
31439 *
31440 * If you pass a function in as the properties argument, the
31441 * function will receive the DOMElement that triggered the
31442 * event as an argument. You are expected to return an object
31443 * from the function; any properties defined on this object
31444 * will be sent to mixpanel as event properties.
31445 *
31446 * @type {Function}
31447 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
31448 * @param {String} event_name The name of the event to track
31449 * @param {Object|Function} [properties] This can be a set of properties, or a function that returns a set of properties after being passed a DOMElement
31450 */
31451 MixpanelLib.prototype.track_forms = function() {
31452 return this._track_dom.call(this, FormTracker, arguments);
31453 };
31454
31455 /**
31456 * Time an event by including the time between this call and a
31457 * later 'track' call for the same event in the properties sent
31458 * with the event.
31459 *
31460 * ### Usage:
31461 *
31462 * // time an event named 'Registered'
31463 * mixpanel.time_event('Registered');
31464 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
31465 *
31466 * When called for a particular event name, the next track call for that event
31467 * name will include the elapsed time between the 'time_event' and 'track'
31468 * calls. This value is stored as seconds in the '$duration' property.
31469 *
31470 * @param {String} event_name The name of the event.
31471 */
31472 MixpanelLib.prototype.time_event = function(event_name) {
31473 if (_.isUndefined(event_name)) {
31474 this.report_error('No event name provided to mixpanel.time_event');
31475 return;
31476 }
31477
31478 if (this._event_is_disabled(event_name)) {
31479 return;
31480 }
31481
31482 this['persistence'].set_event_timer(event_name, new Date().getTime());
31483 };
31484
31485 var REGISTER_DEFAULTS = {
31486 'persistent': true
31487 };
31488 /**
31489 * Helper to parse options param for register methods, maintaining
31490 * legacy support for plain "days" param instead of options object
31491 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
31492 * @returns {Object} options object
31493 */
31494 var options_for_register = function(days_or_options) {
31495 var options;
31496 if (_.isObject(days_or_options)) {
31497 options = days_or_options;
31498 } else if (!_.isUndefined(days_or_options)) {
31499 options = {'days': days_or_options};
31500 } else {
31501 options = {};
31502 }
31503 return _.extend({}, REGISTER_DEFAULTS, options);
31504 };
31505
31506 /**
31507 * Register a set of super properties, which are included with all
31508 * events. This will overwrite previous super property values.
31509 *
31510 * ### Usage:
31511 *
31512 * // register 'Gender' as a super property
31513 * mixpanel.register({'Gender': 'Female'});
31514 *
31515 * // register several super properties when a user signs up
31516 * mixpanel.register({
31517 * 'Email': 'jdoe@example.com',
31518 * 'Account Type': 'Free'
31519 * });
31520 *
31521 * // register only for the current pageload
31522 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
31523 *
31524 * @param {Object} properties An associative array of properties to store about the user
31525 * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)
31526 * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)
31527 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
31528 */
31529 MixpanelLib.prototype.register = function(props, days_or_options) {
31530 var options = options_for_register(days_or_options);
31531 if (options['persistent']) {
31532 this['persistence'].register(props, options['days']);
31533 } else {
31534 _.extend(this.unpersisted_superprops, props);
31535 }
31536 };
31537
31538 /**
31539 * Register a set of super properties only once. This will not
31540 * overwrite previous super property values, unlike register().
31541 *
31542 * ### Usage:
31543 *
31544 * // register a super property for the first time only
31545 * mixpanel.register_once({
31546 * 'First Login Date': new Date().toISOString()
31547 * });
31548 *
31549 * // register once, only for the current pageload
31550 * mixpanel.register_once({
31551 * 'First interaction time': new Date().toISOString()
31552 * }, 'None', {persistent: false});
31553 *
31554 * ### Notes:
31555 *
31556 * If default_value is specified, current super properties
31557 * with that value will be overwritten.
31558 *
31559 * @param {Object} properties An associative array of properties to store about the user
31560 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
31561 * @param {Number|Object} [days_or_options] Options object or number of days since the user's last visit to store the super properties (only valid for persisted props)
31562 * @param {boolean} [days_or_options.days] - number of days since the user's last visit to store the super properties (only valid for persisted props)
31563 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
31564 */
31565 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
31566 var options = options_for_register(days_or_options);
31567 if (options['persistent']) {
31568 this['persistence'].register_once(props, default_value, options['days']);
31569 } else {
31570 if (typeof(default_value) === 'undefined') {
31571 default_value = 'None';
31572 }
31573 _.each(props, function(val, prop) {
31574 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) {
31575 this.unpersisted_superprops[prop] = val;
31576 }
31577 }, this);
31578 }
31579 };
31580
31581 /**
31582 * Delete a super property stored with the current user.
31583 *
31584 * @param {String} property The name of the super property to remove
31585 * @param {Object} [options]
31586 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
31587 */
31588 MixpanelLib.prototype.unregister = function(property, options) {
31589 options = options_for_register(options);
31590 if (options['persistent']) {
31591 this['persistence'].unregister(property);
31592 } else {
31593 delete this.unpersisted_superprops[property];
31594 }
31595 };
31596
31597 MixpanelLib.prototype._register_single = function(prop, value) {
31598 var props = {};
31599 props[prop] = value;
31600 this.register(props);
31601 };
31602
31603 /**
31604 * Identify a user with a unique ID to track user activity across
31605 * devices, tie a user to their events, and create a user profile.
31606 * If you never call this method, unique visitors are tracked using
31607 * a UUID generated the first time they visit the site.
31608 *
31609 * Call identify when you know the identity of the current user,
31610 * typically after login or signup. We recommend against using
31611 * identify for anonymous visitors to your site.
31612 *
31613 * ### Notes:
31614 * If your project has
31615 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
31616 * enabled, the identify method will connect pre- and
31617 * post-authentication events when appropriate.
31618 *
31619 * If your project does not have ID Merge enabled, identify will
31620 * change the user's local distinct_id to the unique ID you pass.
31621 * Events tracked prior to authentication will not be connected
31622 * to the same user identity. If ID Merge is disabled, alias can
31623 * be used to connect pre- and post-registration events.
31624 *
31625 * @param {String} [unique_id] A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used.
31626 */
31627 MixpanelLib.prototype.identify = function(
31628 new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
31629 ) {
31630 // Optional Parameters
31631 // _set_callback:function A callback to be run if and when the People set queue is flushed
31632 // _add_callback:function A callback to be run if and when the People add queue is flushed
31633 // _append_callback:function A callback to be run if and when the People append queue is flushed
31634 // _set_once_callback:function A callback to be run if and when the People set_once queue is flushed
31635 // _union_callback:function A callback to be run if and when the People union queue is flushed
31636 // _unset_callback:function A callback to be run if and when the People unset queue is flushed
31637
31638 var previous_distinct_id = this.get_distinct_id();
31639 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
31640 // we allow the following condition if previous distinct_id is same as new_distinct_id
31641 // so that you can force flush people updates for anonymous profiles.
31642 if (typeof new_distinct_id === 'string' && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
31643 this.report_error('distinct_id cannot have $device: prefix');
31644 return -1;
31645 }
31646 this.register({'$user_id': new_distinct_id});
31647 }
31648
31649 if (!this.get_property('$device_id')) {
31650 // The persisted distinct id might not actually be a device id at all
31651 // it might be a distinct id of the user from before
31652 var device_id = previous_distinct_id;
31653 this.register_once({
31654 '$had_persisted_distinct_id': true,
31655 '$device_id': device_id
31656 }, '');
31657 }
31658
31659 // identify only changes the distinct id if it doesn't match either the existing or the alias;
31660 // if it's new, blow away the alias as well.
31661 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
31662 this.unregister(ALIAS_ID_KEY);
31663 this.register({'distinct_id': new_distinct_id});
31664 }
31665 this._flags.identify_called = true;
31666 // Flush any queued up people requests
31667 this['people']._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
31668
31669 // send an $identify event any time the distinct_id is changing - logic on the server
31670 // will determine whether or not to do anything with it.
31671 if (new_distinct_id !== previous_distinct_id) {
31672 this.track('$identify', {
31673 'distinct_id': new_distinct_id,
31674 '$anon_distinct_id': previous_distinct_id
31675 }, {skip_hooks: true});
31676 }
31677
31678 // check feature flags again if distinct id has changed
31679 if (new_distinct_id !== previous_distinct_id) {
31680 this.flags.fetchFlags();
31681 }
31682 };
31683
31684 /**
31685 * Clears super properties and generates a new random distinct_id for this instance.
31686 * Useful for clearing data when a user logs out.
31687 */
31688 MixpanelLib.prototype.reset = function() {
31689 this.stop_session_recording();
31690 this['persistence'].clear();
31691 this._flags.identify_called = false;
31692 var uuid = _.UUID();
31693 this.register_once({
31694 'distinct_id': DEVICE_ID_PREFIX + uuid,
31695 '$device_id': uuid
31696 }, '');
31697 this._check_and_start_session_recording();
31698 };
31699
31700 /**
31701 * Returns the current distinct id of the user. This is either the id automatically
31702 * generated by the library or the id that has been passed by a call to identify().
31703 *
31704 * ### Notes:
31705 *
31706 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
31707 * init() has a loaded function available to handle this automatically. For example:
31708 *
31709 * // set distinct_id after the mixpanel library has loaded
31710 * mixpanel.init('YOUR PROJECT TOKEN', {
31711 * loaded: function(mixpanel) {
31712 * distinct_id = mixpanel.get_distinct_id();
31713 * }
31714 * });
31715 */
31716 MixpanelLib.prototype.get_distinct_id = function() {
31717 return this.get_property('distinct_id');
31718 };
31719
31720 /**
31721 * The alias method creates an alias which Mixpanel will use to
31722 * remap one id to another. Multiple aliases can point to the
31723 * same identifier.
31724 *
31725 * The following is a valid use of alias:
31726 *
31727 * mixpanel.alias('new_id', 'existing_id');
31728 * // You can add multiple id aliases to the existing ID
31729 * mixpanel.alias('newer_id', 'existing_id');
31730 *
31731 * Aliases can also be chained - the following is a valid example:
31732 *
31733 * mixpanel.alias('new_id', 'existing_id');
31734 * // chain newer_id - new_id - existing_id
31735 * mixpanel.alias('newer_id', 'new_id');
31736 *
31737 * Aliases cannot point to multiple identifiers - the following
31738 * example will not work:
31739 *
31740 * mixpanel.alias('new_id', 'existing_id');
31741 * // this is invalid as 'new_id' already points to 'existing_id'
31742 * mixpanel.alias('new_id', 'newer_id');
31743 *
31744 * ### Notes:
31745 *
31746 * If your project does not have
31747 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
31748 * enabled, the best practice is to call alias once when a unique
31749 * ID is first created for a user (e.g., when a user first registers
31750 * for an account). Do not use alias multiple times for a single
31751 * user without ID Merge enabled.
31752 *
31753 * @param {String} alias A unique identifier that you want to use for this user in the future.
31754 * @param {String} [original] The current identifier being used for this user.
31755 */
31756 MixpanelLib.prototype.alias = function(alias, original) {
31757 // If the $people_distinct_id key exists in persistence, there has been a previous
31758 // mixpanel.people.identify() call made for this user. It is VERY BAD to make an alias with
31759 // this ID, as it will duplicate users.
31760 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
31761 this.report_error('Attempting to create alias for existing People user - aborting.');
31762 return -2;
31763 }
31764
31765 var _this = this;
31766 if (_.isUndefined(original)) {
31767 original = this.get_distinct_id();
31768 }
31769 if (alias !== original) {
31770 this._register_single(ALIAS_ID_KEY, alias);
31771 return this.track('$create_alias', {
31772 'alias': alias,
31773 'distinct_id': original
31774 }, {
31775 skip_hooks: true
31776 }, function() {
31777 // Flush the people queue
31778 _this.identify(alias);
31779 });
31780 } else {
31781 this.report_error('alias matches current distinct_id - skipping api call.');
31782 this.identify(alias);
31783 return -1;
31784 }
31785 };
31786
31787 /**
31788 * Provide a string to recognize the user by. The string passed to
31789 * this method will appear in the Mixpanel Streams product rather
31790 * than an automatically generated name. Name tags do not have to
31791 * be unique.
31792 *
31793 * This value will only be included in Streams data.
31794 *
31795 * @param {String} name_tag A human readable name for the user
31796 * @deprecated
31797 */
31798 MixpanelLib.prototype.name_tag = function(name_tag) {
31799 this._register_single('mp_name_tag', name_tag);
31800 };
31801
31802 /**
31803 * Update the configuration of a mixpanel library instance.
31804 *
31805 * The default config is:
31806 *
31807 * {
31808 * // host for requests (customizable for e.g. a local proxy)
31809 * api_host: 'https://api-js.mixpanel.com',
31810 *
31811 * // endpoints for different types of requests
31812 * api_routes: {
31813 * track: 'track/',
31814 * engage: 'engage/',
31815 * groups: 'groups/',
31816 * }
31817 *
31818 * // HTTP method for tracking requests
31819 * api_method: 'POST'
31820 *
31821 * // transport for sending requests ('XHR' or 'sendBeacon')
31822 * // NB: sendBeacon should only be used for scenarios such as
31823 * // page unload where a "best-effort" attempt to send is
31824 * // acceptable; the sendBeacon API does not support callbacks
31825 * // or any way to know the result of the request. Mixpanel
31826 * // tracking via sendBeacon will not support any event-
31827 * // batching or retry mechanisms.
31828 * api_transport: 'XHR'
31829 *
31830 * // request-batching/queueing/retry
31831 * batch_requests: true,
31832 *
31833 * // maximum number of events/updates to send in a single
31834 * // network request
31835 * batch_size: 50,
31836 *
31837 * // milliseconds to wait between sending batch requests
31838 * batch_flush_interval_ms: 5000,
31839 *
31840 * // milliseconds to wait for network responses to batch requests
31841 * // before they are considered timed-out and retried
31842 * batch_request_timeout_ms: 90000,
31843 *
31844 * // override value for cookie domain, only useful for ensuring
31845 * // correct cross-subdomain cookies on unusual domains like
31846 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
31847 * // set cookies on a different domain than the current origin
31848 * cookie_domain: ''
31849 *
31850 * // super properties cookie expiration (in days)
31851 * cookie_expiration: 365
31852 *
31853 * // if true, cookie will be set with SameSite=None; Secure
31854 * // this is only useful in special situations, like embedded
31855 * // 3rd-party iframes that set up a Mixpanel instance
31856 * cross_site_cookie: false
31857 *
31858 * // super properties span subdomains
31859 * cross_subdomain_cookie: true
31860 *
31861 * // debug mode
31862 * debug: false
31863 *
31864 * // if this is true, the mixpanel cookie or localStorage entry
31865 * // will be deleted, and no user persistence will take place
31866 * disable_persistence: false
31867 *
31868 * // if this is true, Mixpanel will automatically determine
31869 * // City, Region and Country data using the IP address of
31870 * //the client
31871 * ip: true
31872 *
31873 * // opt users out of tracking by this Mixpanel instance by default
31874 * opt_out_tracking_by_default: false
31875 *
31876 * // opt users out of browser data storage by this Mixpanel instance by default
31877 * opt_out_persistence_by_default: false
31878 *
31879 * // persistence mechanism used by opt-in/opt-out methods - cookie
31880 * // or localStorage - falls back to cookie if localStorage is unavailable
31881 * opt_out_tracking_persistence_type: 'localStorage'
31882 *
31883 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
31884 * opt_out_tracking_cookie_prefix: null
31885 *
31886 * // type of persistent store for super properties (cookie/
31887 * // localStorage) if set to 'localStorage', any existing
31888 * // mixpanel cookie value with the same persistence_name
31889 * // will be transferred to localStorage and deleted
31890 * persistence: 'cookie'
31891 *
31892 * // name for super properties persistent store
31893 * persistence_name: ''
31894 *
31895 * // names of properties/superproperties which should never
31896 * // be sent with track() calls
31897 * property_blacklist: []
31898 *
31899 * // if this is true, mixpanel cookies will be marked as
31900 * // secure, meaning they will only be transmitted over https
31901 * secure_cookie: false
31902 *
31903 * // disables enriching user profiles with first touch marketing data
31904 * skip_first_touch_marketing: false
31905 *
31906 * // the amount of time track_links will
31907 * // wait for Mixpanel's servers to respond
31908 * track_links_timeout: 300
31909 *
31910 * // adds any UTM parameters and click IDs present on the page to any events fired
31911 * track_marketing: true
31912 *
31913 * // enables automatic page view tracking using default page view events through
31914 * // the track_pageview() method
31915 * track_pageview: false
31916 *
31917 * // if you set upgrade to be true, the library will check for
31918 * // a cookie from our old js library and import super
31919 * // properties from it, then the old cookie is deleted
31920 * // The upgrade config option only works in the initialization,
31921 * // so make sure you set it when you create the library.
31922 * upgrade: false
31923 *
31924 * // extra HTTP request headers to set for each API request, in
31925 * // the format {'Header-Name': value}
31926 * xhr_headers: {}
31927 *
31928 * // whether to ignore or respect the web browser's Do Not Track setting
31929 * ignore_dnt: false
31930 * }
31931 *
31932 *
31933 * @param {Object} config A dictionary of new configuration values to update
31934 */
31935 MixpanelLib.prototype.set_config = function(config) {
31936 if (_.isObject(config)) {
31937 _.extend(this['config'], config);
31938
31939 var new_batch_size = config['batch_size'];
31940 if (new_batch_size) {
31941 _.each(this.request_batchers, function(batcher) {
31942 batcher.resetBatchSize();
31943 });
31944 }
31945
31946 if (!this.get_config('persistence_name')) {
31947 this['config']['persistence_name'] = this['config']['cookie_name'];
31948 }
31949 if (!this.get_config('disable_persistence')) {
31950 this['config']['disable_persistence'] = this['config']['disable_cookie'];
31951 }
31952
31953 if (this['persistence']) {
31954 this['persistence'].update_config(this['config']);
31955 }
31956 Config.DEBUG = Config.DEBUG || this.get_config('debug');
31957
31958 if (('autocapture' in config || 'record_heatmap_data' in config) && this.autocapture) {
31959 this.autocapture.init();
31960 }
31961 }
31962 };
31963
31964 /**
31965 * returns the current config object for the library.
31966 */
31967 MixpanelLib.prototype.get_config = function(prop_name) {
31968 return this['config'][prop_name];
31969 };
31970
31971 /**
31972 * Fetch a hook function from config, with safe default, and run it
31973 * against the given arguments
31974 * @param {string} hook_name which hook to retrieve
31975 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
31976 */
31977 MixpanelLib.prototype._run_hook = function(hook_name) {
31978 var ret = (this['config']['hooks'][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
31979 if (typeof ret === 'undefined') {
31980 this.report_error(hook_name + ' hook did not return a value');
31981 ret = null;
31982 }
31983 return ret;
31984 };
31985
31986 /**
31987 * Returns the value of the super property named property_name. If no such
31988 * property is set, get_property() will return the undefined value.
31989 *
31990 * ### Notes:
31991 *
31992 * get_property() can only be called after the Mixpanel library has finished loading.
31993 * init() has a loaded function available to handle this automatically. For example:
31994 *
31995 * // grab value for 'user_id' after the mixpanel library has loaded
31996 * mixpanel.init('YOUR PROJECT TOKEN', {
31997 * loaded: function(mixpanel) {
31998 * user_id = mixpanel.get_property('user_id');
31999 * }
32000 * });
32001 *
32002 * @param {String} property_name The name of the super property you want to retrieve
32003 */
32004 MixpanelLib.prototype.get_property = function(property_name) {
32005 return this['persistence'].load_prop([property_name]);
32006 };
32007
32008 /**
32009 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
32010 *
32011 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
32012 * @returns {String} The API host to use for this endpoint
32013 */
32014 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
32015 return this.get_config('api_hosts')[endpoint_type] || this.get_config('api_host');
32016 };
32017
32018 MixpanelLib.prototype.toString = function() {
32019 var name = this.get_config('name');
32020 if (name !== PRIMARY_INSTANCE_NAME) {
32021 name = PRIMARY_INSTANCE_NAME + '.' + name;
32022 }
32023 return name;
32024 };
32025
32026 MixpanelLib.prototype._event_is_disabled = function(event_name) {
32027 return _.isBlockedUA(userAgent) ||
32028 this._flags.disable_all_events ||
32029 _.include(this.__disabled_events, event_name);
32030 };
32031
32032 // perform some housekeeping around GDPR opt-in/out state
32033 MixpanelLib.prototype._gdpr_init = function() {
32034 var is_localStorage_requested = this.get_config('opt_out_tracking_persistence_type') === 'localStorage';
32035
32036 // try to convert opt-in/out cookies to localStorage if possible
32037 if (is_localStorage_requested && _.localStorage.is_supported()) {
32038 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({'persistence_type': 'cookie'})) {
32039 this.opt_in_tracking({'enable_persistence': false});
32040 }
32041 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({'persistence_type': 'cookie'})) {
32042 this.opt_out_tracking({'clear_persistence': false});
32043 }
32044 this.clear_opt_in_out_tracking({
32045 'persistence_type': 'cookie',
32046 'enable_persistence': false
32047 });
32048 }
32049
32050 // check whether the user has already opted out - if so, clear & disable persistence
32051 if (this.has_opted_out_tracking()) {
32052 this._gdpr_update_persistence({'clear_persistence': true});
32053
32054 // check whether we should opt out by default
32055 // note: we don't clear persistence here by default since opt-out default state is often
32056 // used as an initial state while GDPR information is being collected
32057 } else if (!this.has_opted_in_tracking() && (
32058 this.get_config('opt_out_tracking_by_default') || _.cookie.get('mp_optout')
32059 )) {
32060 _.cookie.remove('mp_optout');
32061 this.opt_out_tracking({
32062 'clear_persistence': this.get_config('opt_out_persistence_by_default')
32063 });
32064 }
32065 };
32066
32067 /**
32068 * Enable or disable persistence based on options
32069 * only enable/disable if persistence is not already in this state
32070 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
32071 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
32072 */
32073 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
32074 var disabled;
32075 if (options && options['clear_persistence']) {
32076 disabled = true;
32077 } else if (options && options['enable_persistence']) {
32078 disabled = false;
32079 } else {
32080 return;
32081 }
32082
32083 if (!this.get_config('disable_persistence') && this['persistence'].disabled !== disabled) {
32084 this['persistence'].set_disabled(disabled);
32085 }
32086
32087 if (disabled) {
32088 this.stop_batch_senders();
32089 this.stop_session_recording();
32090 } else {
32091 // only start batchers after opt-in if they have previously been started
32092 // in order to avoid unintentionally starting up batching for the first time
32093 if (this._batchers_were_started) {
32094 this.start_batch_senders();
32095 }
32096 }
32097 };
32098
32099 // call a base gdpr function after constructing the appropriate token and options args
32100 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
32101 options = _.extend({
32102 'track': _.bind(this.track, this),
32103 'persistence_type': this.get_config('opt_out_tracking_persistence_type'),
32104 'cookie_prefix': this.get_config('opt_out_tracking_cookie_prefix'),
32105 'cookie_expiration': this.get_config('cookie_expiration'),
32106 'cross_site_cookie': this.get_config('cross_site_cookie'),
32107 'cross_subdomain_cookie': this.get_config('cross_subdomain_cookie'),
32108 'cookie_domain': this.get_config('cookie_domain'),
32109 'secure_cookie': this.get_config('secure_cookie'),
32110 'ignore_dnt': this.get_config('ignore_dnt')
32111 }, options);
32112
32113 // check if localStorage can be used for recording opt out status, fall back to cookie if not
32114 if (!_.localStorage.is_supported()) {
32115 options['persistence_type'] = 'cookie';
32116 }
32117
32118 return func(this.get_config('token'), {
32119 track: options['track'],
32120 trackEventName: options['track_event_name'],
32121 trackProperties: options['track_properties'],
32122 persistenceType: options['persistence_type'],
32123 persistencePrefix: options['cookie_prefix'],
32124 cookieDomain: options['cookie_domain'],
32125 cookieExpiration: options['cookie_expiration'],
32126 crossSiteCookie: options['cross_site_cookie'],
32127 crossSubdomainCookie: options['cross_subdomain_cookie'],
32128 secureCookie: options['secure_cookie'],
32129 ignoreDnt: options['ignore_dnt']
32130 });
32131 };
32132
32133 /**
32134 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
32135 *
32136 * ### Usage:
32137 *
32138 * // opt user in
32139 * mixpanel.opt_in_tracking();
32140 *
32141 * // opt user in with specific event name, properties, cookie configuration
32142 * mixpanel.opt_in_tracking({
32143 * track_event_name: 'User opted in',
32144 * track_event_properties: {
32145 * 'Email': 'jdoe@example.com'
32146 * },
32147 * cookie_expiration: 30,
32148 * secure_cookie: true
32149 * });
32150 *
32151 * @param {Object} [options] A dictionary of config options to override
32152 * @param {function} [options.track] Function used for tracking a Mixpanel event to record the opt-in action (default is this Mixpanel instance's track method)
32153 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
32154 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
32155 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
32156 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32157 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32158 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32159 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32160 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
32161 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
32162 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
32163 */
32164 MixpanelLib.prototype.opt_in_tracking = function(options) {
32165 options = _.extend({
32166 'enable_persistence': true
32167 }, options);
32168
32169 this._gdpr_call_func(optIn, options);
32170 this._gdpr_update_persistence(options);
32171 };
32172
32173 /**
32174 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
32175 *
32176 * ### Usage:
32177 *
32178 * // opt user out
32179 * mixpanel.opt_out_tracking();
32180 *
32181 * // opt user out with different cookie configuration from Mixpanel instance
32182 * mixpanel.opt_out_tracking({
32183 * cookie_expiration: 30,
32184 * secure_cookie: true
32185 * });
32186 *
32187 * @param {Object} [options] A dictionary of config options to override
32188 * @param {boolean} [options.delete_user=true] If true, will delete the currently identified user's profile and clear all charges after opting the user out
32189 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
32190 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32191 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32192 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32193 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32194 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
32195 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
32196 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
32197 */
32198 MixpanelLib.prototype.opt_out_tracking = function(options) {
32199 options = _.extend({
32200 'clear_persistence': true,
32201 'delete_user': true
32202 }, options);
32203
32204 // delete user and clear charges since these methods may be disabled by opt-out
32205 if (options['delete_user'] && this['people'] && this['people']._identify_called()) {
32206 this['people'].delete_user();
32207 this['people'].clear_charges();
32208 }
32209
32210 this._gdpr_call_func(optOut, options);
32211 this._gdpr_update_persistence(options);
32212 };
32213
32214 /**
32215 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
32216 *
32217 * ### Usage:
32218 *
32219 * var has_opted_in = mixpanel.has_opted_in_tracking();
32220 * // use has_opted_in value
32221 *
32222 * @param {Object} [options] A dictionary of config options to override
32223 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32224 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32225 * @returns {boolean} current opt-in status
32226 */
32227 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
32228 return this._gdpr_call_func(hasOptedIn, options);
32229 };
32230
32231 /**
32232 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
32233 *
32234 * ### Usage:
32235 *
32236 * var has_opted_out = mixpanel.has_opted_out_tracking();
32237 * // use has_opted_out value
32238 *
32239 * @param {Object} [options] A dictionary of config options to override
32240 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32241 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32242 * @returns {boolean} current opt-out status
32243 */
32244 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
32245 return this._gdpr_call_func(hasOptedOut, options);
32246 };
32247
32248 /**
32249 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
32250 *
32251 * ### Usage:
32252 *
32253 * // clear user's opt-in/out status
32254 * mixpanel.clear_opt_in_out_tracking();
32255 *
32256 * // clear user's opt-in/out status with specific cookie configuration - should match
32257 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
32258 * mixpanel.clear_opt_in_out_tracking({
32259 * cookie_expiration: 30,
32260 * secure_cookie: true
32261 * });
32262 *
32263 * @param {Object} [options] A dictionary of config options to override
32264 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
32265 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32266 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32267 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32268 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32269 * @param {boolean} [options.cross_site_cookie] Whether the opt-in cookie is set as cross-site-enabled (overrides value specified in this Mixpanel instance's config)
32270 * @param {boolean} [options.cross_subdomain_cookie] Whether the opt-in cookie is set as cross-subdomain or not (overrides value specified in this Mixpanel instance's config)
32271 * @param {boolean} [options.secure_cookie] Whether the opt-in cookie is set as secure or not (overrides value specified in this Mixpanel instance's config)
32272 */
32273 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
32274 options = _.extend({
32275 'enable_persistence': true
32276 }, options);
32277
32278 this._gdpr_call_func(clearOptInOut, options);
32279 this._gdpr_update_persistence(options);
32280 };
32281
32282 MixpanelLib.prototype.report_error = function(msg, err) {
32283 console$1.error.apply(console$1.error, arguments);
32284 try {
32285 if (!err && !(msg instanceof Error)) {
32286 msg = new Error(msg);
32287 }
32288 this.get_config('error_reporter')(msg, err);
32289 } catch(err) {
32290 console$1.error(err);
32291 }
32292 };
32293
32294 // EXPORTS (for closure compiler)
32295
32296 // MixpanelLib Exports
32297 MixpanelLib.prototype['init'] = MixpanelLib.prototype.init;
32298 MixpanelLib.prototype['reset'] = MixpanelLib.prototype.reset;
32299 MixpanelLib.prototype['disable'] = MixpanelLib.prototype.disable;
32300 MixpanelLib.prototype['time_event'] = MixpanelLib.prototype.time_event;
32301 MixpanelLib.prototype['track'] = MixpanelLib.prototype.track;
32302 MixpanelLib.prototype['track_links'] = MixpanelLib.prototype.track_links;
32303 MixpanelLib.prototype['track_forms'] = MixpanelLib.prototype.track_forms;
32304 MixpanelLib.prototype['track_pageview'] = MixpanelLib.prototype.track_pageview;
32305 MixpanelLib.prototype['register'] = MixpanelLib.prototype.register;
32306 MixpanelLib.prototype['register_once'] = MixpanelLib.prototype.register_once;
32307 MixpanelLib.prototype['unregister'] = MixpanelLib.prototype.unregister;
32308 MixpanelLib.prototype['identify'] = MixpanelLib.prototype.identify;
32309 MixpanelLib.prototype['alias'] = MixpanelLib.prototype.alias;
32310 MixpanelLib.prototype['name_tag'] = MixpanelLib.prototype.name_tag;
32311 MixpanelLib.prototype['set_config'] = MixpanelLib.prototype.set_config;
32312 MixpanelLib.prototype['get_config'] = MixpanelLib.prototype.get_config;
32313 MixpanelLib.prototype['get_api_host'] = MixpanelLib.prototype.get_api_host;
32314 MixpanelLib.prototype['get_property'] = MixpanelLib.prototype.get_property;
32315 MixpanelLib.prototype['get_distinct_id'] = MixpanelLib.prototype.get_distinct_id;
32316 MixpanelLib.prototype['toString'] = MixpanelLib.prototype.toString;
32317 MixpanelLib.prototype['opt_out_tracking'] = MixpanelLib.prototype.opt_out_tracking;
32318 MixpanelLib.prototype['opt_in_tracking'] = MixpanelLib.prototype.opt_in_tracking;
32319 MixpanelLib.prototype['has_opted_out_tracking'] = MixpanelLib.prototype.has_opted_out_tracking;
32320 MixpanelLib.prototype['has_opted_in_tracking'] = MixpanelLib.prototype.has_opted_in_tracking;
32321 MixpanelLib.prototype['clear_opt_in_out_tracking'] = MixpanelLib.prototype.clear_opt_in_out_tracking;
32322 MixpanelLib.prototype['get_group'] = MixpanelLib.prototype.get_group;
32323 MixpanelLib.prototype['set_group'] = MixpanelLib.prototype.set_group;
32324 MixpanelLib.prototype['add_group'] = MixpanelLib.prototype.add_group;
32325 MixpanelLib.prototype['remove_group'] = MixpanelLib.prototype.remove_group;
32326 MixpanelLib.prototype['track_with_groups'] = MixpanelLib.prototype.track_with_groups;
32327 MixpanelLib.prototype['start_batch_senders'] = MixpanelLib.prototype.start_batch_senders;
32328 MixpanelLib.prototype['stop_batch_senders'] = MixpanelLib.prototype.stop_batch_senders;
32329 MixpanelLib.prototype['start_session_recording'] = MixpanelLib.prototype.start_session_recording;
32330 MixpanelLib.prototype['stop_session_recording'] = MixpanelLib.prototype.stop_session_recording;
32331 MixpanelLib.prototype['pause_session_recording'] = MixpanelLib.prototype.pause_session_recording;
32332 MixpanelLib.prototype['resume_session_recording'] = MixpanelLib.prototype.resume_session_recording;
32333 MixpanelLib.prototype['get_session_recording_properties'] = MixpanelLib.prototype.get_session_recording_properties;
32334 MixpanelLib.prototype['get_session_replay_url'] = MixpanelLib.prototype.get_session_replay_url;
32335 MixpanelLib.prototype['get_tab_id'] = MixpanelLib.prototype.get_tab_id;
32336 MixpanelLib.prototype['DEFAULT_API_ROUTES'] = DEFAULT_API_ROUTES;
32337
32338 // Exports intended only for testing
32339 MixpanelLib.prototype['__get_recorder'] = MixpanelLib.prototype.__get_recorder;
32340
32341 // MixpanelPersistence Exports
32342 MixpanelPersistence.prototype['properties'] = MixpanelPersistence.prototype.properties;
32343 MixpanelPersistence.prototype['update_search_keyword'] = MixpanelPersistence.prototype.update_search_keyword;
32344 MixpanelPersistence.prototype['update_referrer_info'] = MixpanelPersistence.prototype.update_referrer_info;
32345 MixpanelPersistence.prototype['get_cross_subdomain'] = MixpanelPersistence.prototype.get_cross_subdomain;
32346 MixpanelPersistence.prototype['clear'] = MixpanelPersistence.prototype.clear;
32347
32348
32349 var instances = {};
32350 var extend_mp = function() {
32351 // add all the sub mixpanel instances
32352 _.each(instances, function(instance, name) {
32353 if (name !== PRIMARY_INSTANCE_NAME) { mixpanel_master[name] = instance; }
32354 });
32355
32356 // add private functions as _
32357 mixpanel_master['_'] = _;
32358 };
32359
32360 var override_mp_init_func = function() {
32361 // we override the snippets init function to handle the case where a
32362 // user initializes the mixpanel library after the script loads & runs
32363 mixpanel_master['init'] = function(token, config, name) {
32364 if (name) {
32365 // initialize a sub library
32366 if (!mixpanel_master[name]) {
32367 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
32368 mixpanel_master[name]._loaded();
32369 }
32370 return mixpanel_master[name];
32371 } else {
32372 var instance = mixpanel_master;
32373
32374 if (instances[PRIMARY_INSTANCE_NAME]) {
32375 // main mixpanel lib already initialized
32376 instance = instances[PRIMARY_INSTANCE_NAME];
32377 } else if (token) {
32378 // intialize the main mixpanel lib
32379 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
32380 instance._loaded();
32381 instances[PRIMARY_INSTANCE_NAME] = instance;
32382 }
32383
32384 mixpanel_master = instance;
32385 if (init_type === INIT_SNIPPET) {
32386 win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
32387 }
32388 extend_mp();
32389 }
32390 };
32391 };
32392
32393 var add_dom_loaded_handler = function() {
32394 // Cross browser DOM Loaded support
32395 function dom_loaded_handler() {
32396 // function flag since we only want to execute this once
32397 if (dom_loaded_handler.done) { return; }
32398 dom_loaded_handler.done = true;
32399
32400 DOM_LOADED = true;
32401 ENQUEUE_REQUESTS = false;
32402
32403 _.each(instances, function(inst) {
32404 inst._dom_loaded();
32405 });
32406 }
32407
32408 function do_scroll_check() {
32409 try {
32410 document$1.documentElement.doScroll('left');
32411 } catch(e) {
32412 setTimeout(do_scroll_check, 1);
32413 return;
32414 }
32415
32416 dom_loaded_handler();
32417 }
32418
32419 if (document$1.addEventListener) {
32420 if (document$1.readyState === 'complete') {
32421 // safari 4 can fire the DOMContentLoaded event before loading all
32422 // external JS (including this file). you will see some copypasta
32423 // on the internet that checks for 'complete' and 'loaded', but
32424 // 'loaded' is an IE thing
32425 dom_loaded_handler();
32426 } else {
32427 document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
32428 }
32429 } else if (document$1.attachEvent) {
32430 // IE
32431 document$1.attachEvent('onreadystatechange', dom_loaded_handler);
32432
32433 // check to make sure we arn't in a frame
32434 var toplevel = false;
32435 try {
32436 toplevel = win.frameElement === null;
32437 } catch(e) {
32438 // noop
32439 }
32440
32441 if (document$1.documentElement.doScroll && toplevel) {
32442 do_scroll_check();
32443 }
32444 }
32445
32446 // fallback handler, always will work
32447 _.register_event(win, 'load', dom_loaded_handler, true);
32448 };
32449
32450 function init_as_module(bundle_loader) {
32451 load_extra_bundle = bundle_loader;
32452 init_type = INIT_MODULE;
32453 mixpanel_master = new MixpanelLib();
32454
32455 override_mp_init_func();
32456 mixpanel_master['init']();
32457 add_dom_loaded_handler();
32458
32459 return mixpanel_master;
32460 }
32461
32462 // For loading separate bundles asynchronously via script tag
32463 // so that we don't load them until they are needed at runtime.
32464
32465 // For builds that have everything in one bundle, no extra work.
32466 function loadNoop (_src, onload) {
32467 onload();
32468 }
32469
32470 /* eslint camelcase: "off" */
32471
32472 var mixpanel = init_as_module(loadNoop);
32473
32474
32475
32476
32477 /***/ }),
32478
32479 /***/ "../node_modules/redux-thunk/es/index.js":
32480 /*!***********************************************!*\
32481 !*** ../node_modules/redux-thunk/es/index.js ***!
32482 \***********************************************/
32483 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
32484
32485 "use strict";
32486 __webpack_require__.r(__webpack_exports__);
32487 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
32488 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
32489 /* harmony export */ });
32490 /** A function that accepts a potential "extra argument" value to be injected later,
32491 * and returns an instance of the thunk middleware that uses that value
32492 */
32493 function createThunkMiddleware(extraArgument) {
32494 // Standard Redux middleware definition pattern:
32495 // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
32496 var middleware = function middleware(_ref) {
32497 var dispatch = _ref.dispatch,
32498 getState = _ref.getState;
32499 return function (next) {
32500 return function (action) {
32501 // The thunk middleware looks for any functions that were passed to `store.dispatch`.
32502 // If this "action" is really a function, call it and return the result.
32503 if (typeof action === 'function') {
32504 // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
32505 return action(dispatch, getState, extraArgument);
32506 } // Otherwise, pass the action down the middleware chain as usual
32507
32508
32509 return next(action);
32510 };
32511 };
32512 };
32513
32514 return middleware;
32515 }
32516
32517 var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
32518 // with whatever "extra arg" they want to inject into their thunks
32519
32520 thunk.withExtraArgument = createThunkMiddleware;
32521 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (thunk);
32522
32523 /***/ }),
32524
32525 /***/ "../node_modules/redux/es/redux.js":
32526 /*!*****************************************!*\
32527 !*** ../node_modules/redux/es/redux.js ***!
32528 \*****************************************/
32529 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
32530
32531 "use strict";
32532 __webpack_require__.r(__webpack_exports__);
32533 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
32534 /* harmony export */ __DO_NOT_USE__ActionTypes: () => (/* binding */ ActionTypes),
32535 /* harmony export */ applyMiddleware: () => (/* binding */ applyMiddleware),
32536 /* harmony export */ bindActionCreators: () => (/* binding */ bindActionCreators),
32537 /* harmony export */ combineReducers: () => (/* binding */ combineReducers),
32538 /* harmony export */ compose: () => (/* binding */ compose),
32539 /* harmony export */ createStore: () => (/* binding */ createStore),
32540 /* harmony export */ legacy_createStore: () => (/* binding */ legacy_createStore)
32541 /* harmony export */ });
32542 /* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectSpread2 */ "../node_modules/@babel/runtime/helpers/esm/objectSpread2.js");
32543
32544
32545 /**
32546 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
32547 *
32548 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
32549 * during build.
32550 * @param {number} code
32551 */
32552 function formatProdErrorMessage(code) {
32553 return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
32554 }
32555
32556 // Inlined version of the `symbol-observable` polyfill
32557 var $$observable = (function () {
32558 return typeof Symbol === 'function' && Symbol.observable || '@@observable';
32559 })();
32560
32561 /**
32562 * These are private action types reserved by Redux.
32563 * For any unknown actions, you must return the current state.
32564 * If the current state is undefined, you must return the initial state.
32565 * Do not reference these action types directly in your code.
32566 */
32567 var randomString = function randomString() {
32568 return Math.random().toString(36).substring(7).split('').join('.');
32569 };
32570
32571 var ActionTypes = {
32572 INIT: "@@redux/INIT" + randomString(),
32573 REPLACE: "@@redux/REPLACE" + randomString(),
32574 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
32575 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
32576 }
32577 };
32578
32579 /**
32580 * @param {any} obj The object to inspect.
32581 * @returns {boolean} True if the argument appears to be a plain object.
32582 */
32583 function isPlainObject(obj) {
32584 if (typeof obj !== 'object' || obj === null) return false;
32585 var proto = obj;
32586
32587 while (Object.getPrototypeOf(proto) !== null) {
32588 proto = Object.getPrototypeOf(proto);
32589 }
32590
32591 return Object.getPrototypeOf(obj) === proto;
32592 }
32593
32594 // Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
32595 function miniKindOf(val) {
32596 if (val === void 0) return 'undefined';
32597 if (val === null) return 'null';
32598 var type = typeof val;
32599
32600 switch (type) {
32601 case 'boolean':
32602 case 'string':
32603 case 'number':
32604 case 'symbol':
32605 case 'function':
32606 {
32607 return type;
32608 }
32609 }
32610
32611 if (Array.isArray(val)) return 'array';
32612 if (isDate(val)) return 'date';
32613 if (isError(val)) return 'error';
32614 var constructorName = ctorName(val);
32615
32616 switch (constructorName) {
32617 case 'Symbol':
32618 case 'Promise':
32619 case 'WeakMap':
32620 case 'WeakSet':
32621 case 'Map':
32622 case 'Set':
32623 return constructorName;
32624 } // other
32625
32626
32627 return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
32628 }
32629
32630 function ctorName(val) {
32631 return typeof val.constructor === 'function' ? val.constructor.name : null;
32632 }
32633
32634 function isError(val) {
32635 return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
32636 }
32637
32638 function isDate(val) {
32639 if (val instanceof Date) return true;
32640 return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
32641 }
32642
32643 function kindOf(val) {
32644 var typeOfVal = typeof val;
32645
32646 if (true) {
32647 typeOfVal = miniKindOf(val);
32648 }
32649
32650 return typeOfVal;
32651 }
32652
32653 /**
32654 * @deprecated
32655 *
32656 * **We recommend using the `configureStore` method
32657 * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
32658 *
32659 * Redux Toolkit is our recommended approach for writing Redux logic today,
32660 * including store setup, reducers, data fetching, and more.
32661 *
32662 * **For more details, please read this Redux docs page:**
32663 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
32664 *
32665 * `configureStore` from Redux Toolkit is an improved version of `createStore` that
32666 * simplifies setup and helps avoid common bugs.
32667 *
32668 * You should not be using the `redux` core package by itself today, except for learning purposes.
32669 * The `createStore` method from the core `redux` package will not be removed, but we encourage
32670 * all users to migrate to using Redux Toolkit for all Redux code.
32671 *
32672 * If you want to use `createStore` without this visual deprecation warning, use
32673 * the `legacy_createStore` import instead:
32674 *
32675 * `import { legacy_createStore as createStore} from 'redux'`
32676 *
32677 */
32678
32679 function createStore(reducer, preloadedState, enhancer) {
32680 var _ref2;
32681
32682 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
32683 throw new Error( false ? 0 : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');
32684 }
32685
32686 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
32687 enhancer = preloadedState;
32688 preloadedState = undefined;
32689 }
32690
32691 if (typeof enhancer !== 'undefined') {
32692 if (typeof enhancer !== 'function') {
32693 throw new Error( false ? 0 : "Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
32694 }
32695
32696 return enhancer(createStore)(reducer, preloadedState);
32697 }
32698
32699 if (typeof reducer !== 'function') {
32700 throw new Error( false ? 0 : "Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'");
32701 }
32702
32703 var currentReducer = reducer;
32704 var currentState = preloadedState;
32705 var currentListeners = [];
32706 var nextListeners = currentListeners;
32707 var isDispatching = false;
32708 /**
32709 * This makes a shallow copy of currentListeners so we can use
32710 * nextListeners as a temporary list while dispatching.
32711 *
32712 * This prevents any bugs around consumers calling
32713 * subscribe/unsubscribe in the middle of a dispatch.
32714 */
32715
32716 function ensureCanMutateNextListeners() {
32717 if (nextListeners === currentListeners) {
32718 nextListeners = currentListeners.slice();
32719 }
32720 }
32721 /**
32722 * Reads the state tree managed by the store.
32723 *
32724 * @returns {any} The current state tree of your application.
32725 */
32726
32727
32728 function getState() {
32729 if (isDispatching) {
32730 throw new Error( false ? 0 : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
32731 }
32732
32733 return currentState;
32734 }
32735 /**
32736 * Adds a change listener. It will be called any time an action is dispatched,
32737 * and some part of the state tree may potentially have changed. You may then
32738 * call `getState()` to read the current state tree inside the callback.
32739 *
32740 * You may call `dispatch()` from a change listener, with the following
32741 * caveats:
32742 *
32743 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
32744 * If you subscribe or unsubscribe while the listeners are being invoked, this
32745 * will not have any effect on the `dispatch()` that is currently in progress.
32746 * However, the next `dispatch()` call, whether nested or not, will use a more
32747 * recent snapshot of the subscription list.
32748 *
32749 * 2. The listener should not expect to see all state changes, as the state
32750 * might have been updated multiple times during a nested `dispatch()` before
32751 * the listener is called. It is, however, guaranteed that all subscribers
32752 * registered before the `dispatch()` started will be called with the latest
32753 * state by the time it exits.
32754 *
32755 * @param {Function} listener A callback to be invoked on every dispatch.
32756 * @returns {Function} A function to remove this change listener.
32757 */
32758
32759
32760 function subscribe(listener) {
32761 if (typeof listener !== 'function') {
32762 throw new Error( false ? 0 : "Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
32763 }
32764
32765 if (isDispatching) {
32766 throw new Error( false ? 0 : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
32767 }
32768
32769 var isSubscribed = true;
32770 ensureCanMutateNextListeners();
32771 nextListeners.push(listener);
32772 return function unsubscribe() {
32773 if (!isSubscribed) {
32774 return;
32775 }
32776
32777 if (isDispatching) {
32778 throw new Error( false ? 0 : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
32779 }
32780
32781 isSubscribed = false;
32782 ensureCanMutateNextListeners();
32783 var index = nextListeners.indexOf(listener);
32784 nextListeners.splice(index, 1);
32785 currentListeners = null;
32786 };
32787 }
32788 /**
32789 * Dispatches an action. It is the only way to trigger a state change.
32790 *
32791 * The `reducer` function, used to create the store, will be called with the
32792 * current state tree and the given `action`. Its return value will
32793 * be considered the **next** state of the tree, and the change listeners
32794 * will be notified.
32795 *
32796 * The base implementation only supports plain object actions. If you want to
32797 * dispatch a Promise, an Observable, a thunk, or something else, you need to
32798 * wrap your store creating function into the corresponding middleware. For
32799 * example, see the documentation for the `redux-thunk` package. Even the
32800 * middleware will eventually dispatch plain object actions using this method.
32801 *
32802 * @param {Object} action A plain object representing “what changed”. It is
32803 * a good idea to keep actions serializable so you can record and replay user
32804 * sessions, or use the time travelling `redux-devtools`. An action must have
32805 * a `type` property which may not be `undefined`. It is a good idea to use
32806 * string constants for action types.
32807 *
32808 * @returns {Object} For convenience, the same action object you dispatched.
32809 *
32810 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
32811 * return something else (for example, a Promise you can await).
32812 */
32813
32814
32815 function dispatch(action) {
32816 if (!isPlainObject(action)) {
32817 throw new Error( false ? 0 : "Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
32818 }
32819
32820 if (typeof action.type === 'undefined') {
32821 throw new Error( false ? 0 : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
32822 }
32823
32824 if (isDispatching) {
32825 throw new Error( false ? 0 : 'Reducers may not dispatch actions.');
32826 }
32827
32828 try {
32829 isDispatching = true;
32830 currentState = currentReducer(currentState, action);
32831 } finally {
32832 isDispatching = false;
32833 }
32834
32835 var listeners = currentListeners = nextListeners;
32836
32837 for (var i = 0; i < listeners.length; i++) {
32838 var listener = listeners[i];
32839 listener();
32840 }
32841
32842 return action;
32843 }
32844 /**
32845 * Replaces the reducer currently used by the store to calculate the state.
32846 *
32847 * You might need this if your app implements code splitting and you want to
32848 * load some of the reducers dynamically. You might also need this if you
32849 * implement a hot reloading mechanism for Redux.
32850 *
32851 * @param {Function} nextReducer The reducer for the store to use instead.
32852 * @returns {void}
32853 */
32854
32855
32856 function replaceReducer(nextReducer) {
32857 if (typeof nextReducer !== 'function') {
32858 throw new Error( false ? 0 : "Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
32859 }
32860
32861 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
32862 // Any reducers that existed in both the new and old rootReducer
32863 // will receive the previous state. This effectively populates
32864 // the new state tree with any relevant data from the old one.
32865
32866 dispatch({
32867 type: ActionTypes.REPLACE
32868 });
32869 }
32870 /**
32871 * Interoperability point for observable/reactive libraries.
32872 * @returns {observable} A minimal observable of state changes.
32873 * For more information, see the observable proposal:
32874 * https://github.com/tc39/proposal-observable
32875 */
32876
32877
32878 function observable() {
32879 var _ref;
32880
32881 var outerSubscribe = subscribe;
32882 return _ref = {
32883 /**
32884 * The minimal observable subscription method.
32885 * @param {Object} observer Any object that can be used as an observer.
32886 * The observer object should have a `next` method.
32887 * @returns {subscription} An object with an `unsubscribe` method that can
32888 * be used to unsubscribe the observable from the store, and prevent further
32889 * emission of values from the observable.
32890 */
32891 subscribe: function subscribe(observer) {
32892 if (typeof observer !== 'object' || observer === null) {
32893 throw new Error( false ? 0 : "Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
32894 }
32895
32896 function observeState() {
32897 if (observer.next) {
32898 observer.next(getState());
32899 }
32900 }
32901
32902 observeState();
32903 var unsubscribe = outerSubscribe(observeState);
32904 return {
32905 unsubscribe: unsubscribe
32906 };
32907 }
32908 }, _ref[$$observable] = function () {
32909 return this;
32910 }, _ref;
32911 } // When a store is created, an "INIT" action is dispatched so that every
32912 // reducer returns their initial state. This effectively populates
32913 // the initial state tree.
32914
32915
32916 dispatch({
32917 type: ActionTypes.INIT
32918 });
32919 return _ref2 = {
32920 dispatch: dispatch,
32921 subscribe: subscribe,
32922 getState: getState,
32923 replaceReducer: replaceReducer
32924 }, _ref2[$$observable] = observable, _ref2;
32925 }
32926 /**
32927 * Creates a Redux store that holds the state tree.
32928 *
32929 * **We recommend using `configureStore` from the
32930 * `@reduxjs/toolkit` package**, which replaces `createStore`:
32931 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
32932 *
32933 * The only way to change the data in the store is to call `dispatch()` on it.
32934 *
32935 * There should only be a single store in your app. To specify how different
32936 * parts of the state tree respond to actions, you may combine several reducers
32937 * into a single reducer function by using `combineReducers`.
32938 *
32939 * @param {Function} reducer A function that returns the next state tree, given
32940 * the current state tree and the action to handle.
32941 *
32942 * @param {any} [preloadedState] The initial state. You may optionally specify it
32943 * to hydrate the state from the server in universal apps, or to restore a
32944 * previously serialized user session.
32945 * If you use `combineReducers` to produce the root reducer function, this must be
32946 * an object with the same shape as `combineReducers` keys.
32947 *
32948 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
32949 * to enhance the store with third-party capabilities such as middleware,
32950 * time travel, persistence, etc. The only store enhancer that ships with Redux
32951 * is `applyMiddleware()`.
32952 *
32953 * @returns {Store} A Redux store that lets you read the state, dispatch actions
32954 * and subscribe to changes.
32955 */
32956
32957 var legacy_createStore = createStore;
32958
32959 /**
32960 * Prints a warning in the console if it exists.
32961 *
32962 * @param {String} message The warning message.
32963 * @returns {void}
32964 */
32965 function warning(message) {
32966 /* eslint-disable no-console */
32967 if (typeof console !== 'undefined' && typeof console.error === 'function') {
32968 console.error(message);
32969 }
32970 /* eslint-enable no-console */
32971
32972
32973 try {
32974 // This error was thrown as a convenience so that if you enable
32975 // "break on all exceptions" in your console,
32976 // it would pause the execution at this line.
32977 throw new Error(message);
32978 } catch (e) {} // eslint-disable-line no-empty
32979
32980 }
32981
32982 function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
32983 var reducerKeys = Object.keys(reducers);
32984 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
32985
32986 if (reducerKeys.length === 0) {
32987 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
32988 }
32989
32990 if (!isPlainObject(inputState)) {
32991 return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
32992 }
32993
32994 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
32995 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
32996 });
32997 unexpectedKeys.forEach(function (key) {
32998 unexpectedKeyCache[key] = true;
32999 });
33000 if (action && action.type === ActionTypes.REPLACE) return;
33001
33002 if (unexpectedKeys.length > 0) {
33003 return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
33004 }
33005 }
33006
33007 function assertReducerShape(reducers) {
33008 Object.keys(reducers).forEach(function (key) {
33009 var reducer = reducers[key];
33010 var initialState = reducer(undefined, {
33011 type: ActionTypes.INIT
33012 });
33013
33014 if (typeof initialState === 'undefined') {
33015 throw new Error( false ? 0 : "The slice reducer for key \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
33016 }
33017
33018 if (typeof reducer(undefined, {
33019 type: ActionTypes.PROBE_UNKNOWN_ACTION()
33020 }) === 'undefined') {
33021 throw new Error( false ? 0 : "The slice reducer for key \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle '" + ActionTypes.INIT + "' or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
33022 }
33023 });
33024 }
33025 /**
33026 * Turns an object whose values are different reducer functions, into a single
33027 * reducer function. It will call every child reducer, and gather their results
33028 * into a single state object, whose keys correspond to the keys of the passed
33029 * reducer functions.
33030 *
33031 * @param {Object} reducers An object whose values correspond to different
33032 * reducer functions that need to be combined into one. One handy way to obtain
33033 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
33034 * undefined for any action. Instead, they should return their initial state
33035 * if the state passed to them was undefined, and the current state for any
33036 * unrecognized action.
33037 *
33038 * @returns {Function} A reducer function that invokes every reducer inside the
33039 * passed object, and builds a state object with the same shape.
33040 */
33041
33042
33043 function combineReducers(reducers) {
33044 var reducerKeys = Object.keys(reducers);
33045 var finalReducers = {};
33046
33047 for (var i = 0; i < reducerKeys.length; i++) {
33048 var key = reducerKeys[i];
33049
33050 if (true) {
33051 if (typeof reducers[key] === 'undefined') {
33052 warning("No reducer provided for key \"" + key + "\"");
33053 }
33054 }
33055
33056 if (typeof reducers[key] === 'function') {
33057 finalReducers[key] = reducers[key];
33058 }
33059 }
33060
33061 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
33062 // keys multiple times.
33063
33064 var unexpectedKeyCache;
33065
33066 if (true) {
33067 unexpectedKeyCache = {};
33068 }
33069
33070 var shapeAssertionError;
33071
33072 try {
33073 assertReducerShape(finalReducers);
33074 } catch (e) {
33075 shapeAssertionError = e;
33076 }
33077
33078 return function combination(state, action) {
33079 if (state === void 0) {
33080 state = {};
33081 }
33082
33083 if (shapeAssertionError) {
33084 throw shapeAssertionError;
33085 }
33086
33087 if (true) {
33088 var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
33089
33090 if (warningMessage) {
33091 warning(warningMessage);
33092 }
33093 }
33094
33095 var hasChanged = false;
33096 var nextState = {};
33097
33098 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
33099 var _key = finalReducerKeys[_i];
33100 var reducer = finalReducers[_key];
33101 var previousStateForKey = state[_key];
33102 var nextStateForKey = reducer(previousStateForKey, action);
33103
33104 if (typeof nextStateForKey === 'undefined') {
33105 var actionType = action && action.type;
33106 throw new Error( false ? 0 : "When called with an action of type " + (actionType ? "\"" + String(actionType) + "\"" : '(unknown type)') + ", the slice reducer for key \"" + _key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.");
33107 }
33108
33109 nextState[_key] = nextStateForKey;
33110 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
33111 }
33112
33113 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
33114 return hasChanged ? nextState : state;
33115 };
33116 }
33117
33118 function bindActionCreator(actionCreator, dispatch) {
33119 return function () {
33120 return dispatch(actionCreator.apply(this, arguments));
33121 };
33122 }
33123 /**
33124 * Turns an object whose values are action creators, into an object with the
33125 * same keys, but with every function wrapped into a `dispatch` call so they
33126 * may be invoked directly. This is just a convenience method, as you can call
33127 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
33128 *
33129 * For convenience, you can also pass an action creator as the first argument,
33130 * and get a dispatch wrapped function in return.
33131 *
33132 * @param {Function|Object} actionCreators An object whose values are action
33133 * creator functions. One handy way to obtain it is to use ES6 `import * as`
33134 * syntax. You may also pass a single function.
33135 *
33136 * @param {Function} dispatch The `dispatch` function available on your Redux
33137 * store.
33138 *
33139 * @returns {Function|Object} The object mimicking the original object, but with
33140 * every action creator wrapped into the `dispatch` call. If you passed a
33141 * function as `actionCreators`, the return value will also be a single
33142 * function.
33143 */
33144
33145
33146 function bindActionCreators(actionCreators, dispatch) {
33147 if (typeof actionCreators === 'function') {
33148 return bindActionCreator(actionCreators, dispatch);
33149 }
33150
33151 if (typeof actionCreators !== 'object' || actionCreators === null) {
33152 throw new Error( false ? 0 : "bindActionCreators expected an object or a function, but instead received: '" + kindOf(actionCreators) + "'. " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
33153 }
33154
33155 var boundActionCreators = {};
33156
33157 for (var key in actionCreators) {
33158 var actionCreator = actionCreators[key];
33159
33160 if (typeof actionCreator === 'function') {
33161 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
33162 }
33163 }
33164
33165 return boundActionCreators;
33166 }
33167
33168 /**
33169 * Composes single-argument functions from right to left. The rightmost
33170 * function can take multiple arguments as it provides the signature for
33171 * the resulting composite function.
33172 *
33173 * @param {...Function} funcs The functions to compose.
33174 * @returns {Function} A function obtained by composing the argument functions
33175 * from right to left. For example, compose(f, g, h) is identical to doing
33176 * (...args) => f(g(h(...args))).
33177 */
33178 function compose() {
33179 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
33180 funcs[_key] = arguments[_key];
33181 }
33182
33183 if (funcs.length === 0) {
33184 return function (arg) {
33185 return arg;
33186 };
33187 }
33188
33189 if (funcs.length === 1) {
33190 return funcs[0];
33191 }
33192
33193 return funcs.reduce(function (a, b) {
33194 return function () {
33195 return a(b.apply(void 0, arguments));
33196 };
33197 });
33198 }
33199
33200 /**
33201 * Creates a store enhancer that applies middleware to the dispatch method
33202 * of the Redux store. This is handy for a variety of tasks, such as expressing
33203 * asynchronous actions in a concise manner, or logging every action payload.
33204 *
33205 * See `redux-thunk` package as an example of the Redux middleware.
33206 *
33207 * Because middleware is potentially asynchronous, this should be the first
33208 * store enhancer in the composition chain.
33209 *
33210 * Note that each middleware will be given the `dispatch` and `getState` functions
33211 * as named arguments.
33212 *
33213 * @param {...Function} middlewares The middleware chain to be applied.
33214 * @returns {Function} A store enhancer applying the middleware.
33215 */
33216
33217 function applyMiddleware() {
33218 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
33219 middlewares[_key] = arguments[_key];
33220 }
33221
33222 return function (createStore) {
33223 return function () {
33224 var store = createStore.apply(void 0, arguments);
33225
33226 var _dispatch = function dispatch() {
33227 throw new Error( false ? 0 : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
33228 };
33229
33230 var middlewareAPI = {
33231 getState: store.getState,
33232 dispatch: function dispatch() {
33233 return _dispatch.apply(void 0, arguments);
33234 }
33235 };
33236 var chain = middlewares.map(function (middleware) {
33237 return middleware(middlewareAPI);
33238 });
33239 _dispatch = compose.apply(void 0, chain)(store.dispatch);
33240 return (0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__["default"])((0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__["default"])({}, store), {}, {
33241 dispatch: _dispatch
33242 });
33243 };
33244 };
33245 }
33246
33247
33248
33249
33250 /***/ }),
33251
33252 /***/ "../node_modules/reselect/es/defaultMemoize.js":
33253 /*!*****************************************************!*\
33254 !*** ../node_modules/reselect/es/defaultMemoize.js ***!
33255 \*****************************************************/
33256 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
33257
33258 "use strict";
33259 __webpack_require__.r(__webpack_exports__);
33260 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
33261 /* harmony export */ createCacheKeyComparator: () => (/* binding */ createCacheKeyComparator),
33262 /* harmony export */ defaultEqualityCheck: () => (/* binding */ defaultEqualityCheck),
33263 /* harmony export */ defaultMemoize: () => (/* binding */ defaultMemoize)
33264 /* harmony export */ });
33265 // Cache implementation based on Erik Rasmussen's `lru-memoize`:
33266 // https://github.com/erikras/lru-memoize
33267 var NOT_FOUND = 'NOT_FOUND';
33268
33269 function createSingletonCache(equals) {
33270 var entry;
33271 return {
33272 get: function get(key) {
33273 if (entry && equals(entry.key, key)) {
33274 return entry.value;
33275 }
33276
33277 return NOT_FOUND;
33278 },
33279 put: function put(key, value) {
33280 entry = {
33281 key: key,
33282 value: value
33283 };
33284 },
33285 getEntries: function getEntries() {
33286 return entry ? [entry] : [];
33287 },
33288 clear: function clear() {
33289 entry = undefined;
33290 }
33291 };
33292 }
33293
33294 function createLruCache(maxSize, equals) {
33295 var entries = [];
33296
33297 function get(key) {
33298 var cacheIndex = entries.findIndex(function (entry) {
33299 return equals(key, entry.key);
33300 }); // We found a cached entry
33301
33302 if (cacheIndex > -1) {
33303 var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top
33304
33305 if (cacheIndex > 0) {
33306 entries.splice(cacheIndex, 1);
33307 entries.unshift(entry);
33308 }
33309
33310 return entry.value;
33311 } // No entry found in cache, return sentinel
33312
33313
33314 return NOT_FOUND;
33315 }
33316
33317 function put(key, value) {
33318 if (get(key) === NOT_FOUND) {
33319 // TODO Is unshift slow?
33320 entries.unshift({
33321 key: key,
33322 value: value
33323 });
33324
33325 if (entries.length > maxSize) {
33326 entries.pop();
33327 }
33328 }
33329 }
33330
33331 function getEntries() {
33332 return entries;
33333 }
33334
33335 function clear() {
33336 entries = [];
33337 }
33338
33339 return {
33340 get: get,
33341 put: put,
33342 getEntries: getEntries,
33343 clear: clear
33344 };
33345 }
33346
33347 var defaultEqualityCheck = function defaultEqualityCheck(a, b) {
33348 return a === b;
33349 };
33350 function createCacheKeyComparator(equalityCheck) {
33351 return function areArgumentsShallowlyEqual(prev, next) {
33352 if (prev === null || next === null || prev.length !== next.length) {
33353 return false;
33354 } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.
33355
33356
33357 var length = prev.length;
33358
33359 for (var i = 0; i < length; i++) {
33360 if (!equalityCheck(prev[i], next[i])) {
33361 return false;
33362 }
33363 }
33364
33365 return true;
33366 };
33367 }
33368 // defaultMemoize now supports a configurable cache size with LRU behavior,
33369 // and optional comparison of the result value with existing values
33370 function defaultMemoize(func, equalityCheckOrOptions) {
33371 var providedOptions = typeof equalityCheckOrOptions === 'object' ? equalityCheckOrOptions : {
33372 equalityCheck: equalityCheckOrOptions
33373 };
33374 var _providedOptions$equa = providedOptions.equalityCheck,
33375 equalityCheck = _providedOptions$equa === void 0 ? defaultEqualityCheck : _providedOptions$equa,
33376 _providedOptions$maxS = providedOptions.maxSize,
33377 maxSize = _providedOptions$maxS === void 0 ? 1 : _providedOptions$maxS,
33378 resultEqualityCheck = providedOptions.resultEqualityCheck;
33379 var comparator = createCacheKeyComparator(equalityCheck);
33380 var cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); // we reference arguments instead of spreading them for performance reasons
33381
33382 function memoized() {
33383 var value = cache.get(arguments);
33384
33385 if (value === NOT_FOUND) {
33386 // @ts-ignore
33387 value = func.apply(null, arguments);
33388
33389 if (resultEqualityCheck) {
33390 var entries = cache.getEntries();
33391 var matchingEntry = entries.find(function (entry) {
33392 return resultEqualityCheck(entry.value, value);
33393 });
33394
33395 if (matchingEntry) {
33396 value = matchingEntry.value;
33397 }
33398 }
33399
33400 cache.put(arguments, value);
33401 }
33402
33403 return value;
33404 }
33405
33406 memoized.clearCache = function () {
33407 return cache.clear();
33408 };
33409
33410 return memoized;
33411 }
33412
33413 /***/ }),
33414
33415 /***/ "../node_modules/reselect/es/index.js":
33416 /*!********************************************!*\
33417 !*** ../node_modules/reselect/es/index.js ***!
33418 \********************************************/
33419 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
33420
33421 "use strict";
33422 __webpack_require__.r(__webpack_exports__);
33423 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
33424 /* harmony export */ createSelector: () => (/* binding */ createSelector),
33425 /* harmony export */ createSelectorCreator: () => (/* binding */ createSelectorCreator),
33426 /* harmony export */ createStructuredSelector: () => (/* binding */ createStructuredSelector),
33427 /* harmony export */ defaultEqualityCheck: () => (/* reexport safe */ _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultEqualityCheck),
33428 /* harmony export */ defaultMemoize: () => (/* reexport safe */ _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultMemoize)
33429 /* harmony export */ });
33430 /* harmony import */ var _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defaultMemoize */ "../node_modules/reselect/es/defaultMemoize.js");
33431
33432
33433
33434 function getDependencies(funcs) {
33435 var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs;
33436
33437 if (!dependencies.every(function (dep) {
33438 return typeof dep === 'function';
33439 })) {
33440 var dependencyTypes = dependencies.map(function (dep) {
33441 return typeof dep === 'function' ? "function " + (dep.name || 'unnamed') + "()" : typeof dep;
33442 }).join(', ');
33443 throw new Error("createSelector expects all input-selectors to be functions, but received the following types: [" + dependencyTypes + "]");
33444 }
33445
33446 return dependencies;
33447 }
33448
33449 function createSelectorCreator(memoize) {
33450 for (var _len = arguments.length, memoizeOptionsFromArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
33451 memoizeOptionsFromArgs[_key - 1] = arguments[_key];
33452 }
33453
33454 var createSelector = function createSelector() {
33455 for (var _len2 = arguments.length, funcs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
33456 funcs[_key2] = arguments[_key2];
33457 }
33458
33459 var _recomputations = 0;
33460
33461 var _lastResult; // Due to the intricacies of rest params, we can't do an optional arg after `...funcs`.
33462 // So, start by declaring the default value here.
33463 // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)
33464
33465
33466 var directlyPassedOptions = {
33467 memoizeOptions: undefined
33468 }; // Normally, the result func or "output selector" is the last arg
33469
33470 var resultFunc = funcs.pop(); // If the result func is actually an _object_, assume it's our options object
33471
33472 if (typeof resultFunc === 'object') {
33473 directlyPassedOptions = resultFunc; // and pop the real result func off
33474
33475 resultFunc = funcs.pop();
33476 }
33477
33478 if (typeof resultFunc !== 'function') {
33479 throw new Error("createSelector expects an output function after the inputs, but received: [" + typeof resultFunc + "]");
33480 } // Determine which set of options we're using. Prefer options passed directly,
33481 // but fall back to options given to createSelectorCreator.
33482
33483
33484 var _directlyPassedOption = directlyPassedOptions,
33485 _directlyPassedOption2 = _directlyPassedOption.memoizeOptions,
33486 memoizeOptions = _directlyPassedOption2 === void 0 ? memoizeOptionsFromArgs : _directlyPassedOption2; // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer
33487 // is an array. In most libs I've looked at, it's an equality function or options object.
33488 // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full
33489 // user-provided array of options. Otherwise, it must be just the _first_ arg, and so
33490 // we wrap it in an array so we can apply it.
33491
33492 var finalMemoizeOptions = Array.isArray(memoizeOptions) ? memoizeOptions : [memoizeOptions];
33493 var dependencies = getDependencies(funcs);
33494 var memoizedResultFunc = memoize.apply(void 0, [function recomputationWrapper() {
33495 _recomputations++; // apply arguments instead of spreading for performance.
33496
33497 return resultFunc.apply(null, arguments);
33498 }].concat(finalMemoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.
33499
33500 var selector = memoize(function dependenciesChecker() {
33501 var params = [];
33502 var length = dependencies.length;
33503
33504 for (var i = 0; i < length; i++) {
33505 // apply arguments instead of spreading and mutate a local list of params for performance.
33506 // @ts-ignore
33507 params.push(dependencies[i].apply(null, arguments));
33508 } // apply arguments instead of spreading for performance.
33509
33510
33511 _lastResult = memoizedResultFunc.apply(null, params);
33512 return _lastResult;
33513 });
33514 Object.assign(selector, {
33515 resultFunc: resultFunc,
33516 memoizedResultFunc: memoizedResultFunc,
33517 dependencies: dependencies,
33518 lastResult: function lastResult() {
33519 return _lastResult;
33520 },
33521 recomputations: function recomputations() {
33522 return _recomputations;
33523 },
33524 resetRecomputations: function resetRecomputations() {
33525 return _recomputations = 0;
33526 }
33527 });
33528 return selector;
33529 }; // @ts-ignore
33530
33531
33532 return createSelector;
33533 }
33534 var createSelector = /* #__PURE__ */createSelectorCreator(_defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultMemoize);
33535 // Manual definition of state and output arguments
33536 var createStructuredSelector = function createStructuredSelector(selectors, selectorCreator) {
33537 if (selectorCreator === void 0) {
33538 selectorCreator = createSelector;
33539 }
33540
33541 if (typeof selectors !== 'object') {
33542 throw new Error('createStructuredSelector expects first argument to be an object ' + ("where each property is a selector, instead received a " + typeof selectors));
33543 }
33544
33545 var objectKeys = Object.keys(selectors);
33546 var resultSelector = selectorCreator( // @ts-ignore
33547 objectKeys.map(function (key) {
33548 return selectors[key];
33549 }), function () {
33550 for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
33551 values[_key3] = arguments[_key3];
33552 }
33553
33554 return values.reduce(function (composition, value, index) {
33555 composition[objectKeys[index]] = value;
33556 return composition;
33557 }, {});
33558 });
33559 return resultSelector;
33560 };
33561
33562 /***/ }),
33563
33564 /***/ "@wordpress/i18n":
33565 /*!**************************!*\
33566 !*** external "wp.i18n" ***!
33567 \**************************/
33568 /***/ ((module) => {
33569
33570 "use strict";
33571 module.exports = wp.i18n;
33572
33573 /***/ })
33574
33575 /******/ });
33576 /************************************************************************/
33577 /******/ // The module cache
33578 /******/ var __webpack_module_cache__ = {};
33579 /******/
33580 /******/ // The require function
33581 /******/ function __webpack_require__(moduleId) {
33582 /******/ // Check if module is in cache
33583 /******/ var cachedModule = __webpack_module_cache__[moduleId];
33584 /******/ if (cachedModule !== undefined) {
33585 /******/ return cachedModule.exports;
33586 /******/ }
33587 /******/ // Create a new module (and put it into the cache)
33588 /******/ var module = __webpack_module_cache__[moduleId] = {
33589 /******/ // no module.id needed
33590 /******/ // no module.loaded needed
33591 /******/ exports: {}
33592 /******/ };
33593 /******/
33594 /******/ // Execute the module function
33595 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
33596 /******/
33597 /******/ // Return the exports of the module
33598 /******/ return module.exports;
33599 /******/ }
33600 /******/
33601 /************************************************************************/
33602 /******/ /* webpack/runtime/define property getters */
33603 /******/ (() => {
33604 /******/ // define getter functions for harmony exports
33605 /******/ __webpack_require__.d = (exports, definition) => {
33606 /******/ for(var key in definition) {
33607 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
33608 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
33609 /******/ }
33610 /******/ }
33611 /******/ };
33612 /******/ })();
33613 /******/
33614 /******/ /* webpack/runtime/global */
33615 /******/ (() => {
33616 /******/ __webpack_require__.g = (function() {
33617 /******/ if (typeof globalThis === 'object') return globalThis;
33618 /******/ try {
33619 /******/ return this || new Function('return this')();
33620 /******/ } catch (e) {
33621 /******/ if (typeof window === 'object') return window;
33622 /******/ }
33623 /******/ })();
33624 /******/ })();
33625 /******/
33626 /******/ /* webpack/runtime/hasOwnProperty shorthand */
33627 /******/ (() => {
33628 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
33629 /******/ })();
33630 /******/
33631 /******/ /* webpack/runtime/make namespace object */
33632 /******/ (() => {
33633 /******/ // define __esModule on exports
33634 /******/ __webpack_require__.r = (exports) => {
33635 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
33636 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
33637 /******/ }
33638 /******/ Object.defineProperty(exports, '__esModule', { value: true });
33639 /******/ };
33640 /******/ })();
33641 /******/
33642 /************************************************************************/
33643 var __webpack_exports__ = {};
33644 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
33645 (() => {
33646 "use strict";
33647 /*!******************************************!*\
33648 !*** ../core/common/assets/js/common.js ***!
33649 \******************************************/
33650
33651
33652 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
33653 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
33654 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
33655 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
33656 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
33657 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
33658 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
33659 var _helpers = _interopRequireDefault(__webpack_require__(/*! ./utils/helpers */ "../core/common/assets/js/utils/helpers.js"));
33660 var _storage = _interopRequireDefault(__webpack_require__(/*! ./utils/storage */ "../core/common/assets/js/utils/storage.js"));
33661 var _debug = _interopRequireDefault(__webpack_require__(/*! ./utils/debug */ "../core/common/assets/js/utils/debug.js"));
33662 var _ajax = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/ajax/assets/js/ajax */ "../core/common/modules/ajax/assets/js/ajax.js"));
33663 var _finder = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/finder/assets/js/finder */ "../core/common/modules/finder/assets/js/finder.js"));
33664 var _connect = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/connect/assets/js/connect */ "../core/common/modules/connect/assets/js/connect.js"));
33665 var _component = _interopRequireDefault(__webpack_require__(/*! ./components/wordpress/component */ "../core/common/assets/js/components/wordpress/component.js"));
33666 var _component2 = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/data/component */ "../core/common/modules/event-tracker/assets/js/data/component.js"));
33667 var _events = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/events */ "../core/common/modules/event-tracker/assets/js/events.js"));
33668 var _module = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/events-manager/assets/js/module */ "../core/common/modules/events-manager/assets/js/module.js"));
33669 var _notifications = _interopRequireDefault(__webpack_require__(/*! elementor-utils/notifications */ "../assets/dev/js/utils/notifications.js"));
33670 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
33671 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
33672 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
33673 var ElementorCommonApp = /*#__PURE__*/function (_elementorModules$Vie) {
33674 function ElementorCommonApp() {
33675 (0, _classCallCheck2.default)(this, ElementorCommonApp);
33676 return _callSuper(this, ElementorCommonApp, arguments);
33677 }
33678 (0, _inherits2.default)(ElementorCommonApp, _elementorModules$Vie);
33679 return (0, _createClass2.default)(ElementorCommonApp, [{
33680 key: "setMarionetteTemplateCompiler",
33681 value: function setMarionetteTemplateCompiler() {
33682 Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate, options) {
33683 options = {
33684 evaluate: /<#([\s\S]+?)#>/g,
33685 interpolate: /{{{([\s\S]+?)}}}/g,
33686 escape: /{{([^}]+?)}}(?!})/g
33687 };
33688 return _.template(rawTemplate, options);
33689 };
33690 }
33691 }, {
33692 key: "getDefaultElements",
33693 value: function getDefaultElements() {
33694 return {
33695 $window: jQuery(window),
33696 $document: jQuery(document),
33697 $body: jQuery(document.body)
33698 };
33699 }
33700 }, {
33701 key: "initComponents",
33702 value: function initComponents() {
33703 this.events = new _events.default();
33704 this.eventsManager = new _module.default();
33705 this.debug = new _debug.default();
33706 this.helpers = new _helpers.default();
33707 this.storage = new _storage.default();
33708 this.dialogsManager = new DialogsManager.Instance();
33709 this.notifications = new _notifications.default();
33710 this.api = window.$e;
33711 $e.components.register(new _component2.default());
33712 elementorCommon.elements.$window.on('elementor:init-components', function () {
33713 $e.components.register(new _component.default());
33714 });
33715 this.initModules();
33716 }
33717 }, {
33718 key: "initModules",
33719 value: function initModules() {
33720 var _this = this;
33721 var activeModules = this.config.activeModules;
33722 var modules = {
33723 ajax: _ajax.default,
33724 finder: _finder.default,
33725 connect: _connect.default
33726 };
33727 activeModules.forEach(function (name) {
33728 if (modules[name]) {
33729 _this[name] = new modules[name](_this.config[name]);
33730 }
33731 });
33732 }
33733 }, {
33734 key: "compileArrayTemplateArgs",
33735 value: function compileArrayTemplateArgs(template, templateArgs) {
33736 return template.replace(/%(?:(\d+)\$)?s/g, function (match, number) {
33737 if (!number) {
33738 number = 1;
33739 }
33740 number--;
33741 return undefined !== templateArgs[number] ? templateArgs[number] : match;
33742 });
33743 }
33744 }, {
33745 key: "compileObjectTemplateArgs",
33746 value: function compileObjectTemplateArgs(template, templateArgs) {
33747 return template.replace(/{{(?:([ \w]+))}}/g, function (match, name) {
33748 return templateArgs[name] ? templateArgs[name] : match;
33749 });
33750 }
33751 }, {
33752 key: "compileTemplate",
33753 value: function compileTemplate(template, templateArgs) {
33754 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
33755 }
33756 }, {
33757 key: "translate",
33758 value: function translate(stringKey, context, templateArgs, i18nStack) {
33759 if (context) {
33760 i18nStack = this.config[context].i18n;
33761 }
33762 if (!i18nStack) {
33763 i18nStack = this.config.i18n;
33764 }
33765 var string = i18nStack[stringKey];
33766 if (undefined === string) {
33767 string = stringKey;
33768 }
33769 if (templateArgs) {
33770 string = this.compileTemplate(string, templateArgs);
33771 }
33772 return string;
33773 }
33774 }, {
33775 key: "onInit",
33776 value: function onInit() {
33777 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
33778 this.config = elementorCommonConfig;
33779 this.setMarionetteTemplateCompiler();
33780 }
33781 }]);
33782 }(elementorModules.ViewModule);
33783 window.elementorCommon = new ElementorCommonApp();
33784 elementorCommon.initComponents();
33785 })();
33786
33787 /******/ })()
33788 ;
33789 //# sourceMappingURL=common.js.map