PluginProbe
Elementor Website Builder – more than just a page builder / 4.3.0-beta3
Elementor Website Builder – more than just a page builder v4.3.0-beta3
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.3.0-beta3, at assets/js/common.js

24,251 lines 864.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function(_reduxjs_toolkit, _wordpress_i18n) {
2
3 //#region \0rolldown/runtime.js
4 var __create = Object.create;
5 var __defProp$2 = Object.defineProperty;
6 var __name = (target, value) => __defProp$2(target, "name", {
7 value,
8 configurable: true
9 });
10 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11 var __getOwnPropNames = Object.getOwnPropertyNames;
12 var __getProtoOf = Object.getPrototypeOf;
13 var __hasOwnProp = Object.prototype.hasOwnProperty;
14 var __esmMin = (fn, res, err) => () => {
15 if (err) throw err[0];
16 try {
17 return fn && (res = fn(fn = 0)), res;
18 } catch (e) {
19 throw err = [e], e;
20 }
21 };
22 var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
23 var __exportAll = (all, no_symbols) => {
24 let target = {};
25 for (var name in all) {
26 __defProp$2(target, name, {
27 get: all[name],
28 enumerable: true
29 });
30 }
31 if (!no_symbols) {
32 __defProp$2(target, Symbol.toStringTag, { value: "Module" });
33 }
34 return target;
35 };
36 var __copyProps = (to, from, except, desc) => {
37 if (from && typeof from === "object" || typeof from === "function") {
38 for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
39 key = keys[i];
40 if (!__hasOwnProp.call(to, key) && key !== except) {
41 __defProp$2(to, key, {
42 get: ((k) => from[k]).bind(null, key),
43 enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44 });
45 }
46 }
47 }
48 return to;
49 };
50 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$2(target, "default", {
51 value: mod,
52 enumerable: true
53 }) : target, mod));
54
55 //#endregion
56
57 //#region node_modules/@babel/runtime/helpers/esm/classCallCheck.js
58 function _classCallCheck(a, n) {
59 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
60 }
61
62 //#endregion
63 //#region node_modules/@babel/runtime/helpers/esm/typeof.js
64 function _typeof(o) {
65 "@babel/helpers - typeof";
66 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
67 return typeof o;
68 } : function(o) {
69 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
70 }, _typeof(o);
71 }
72 var init_typeof = __esmMin((() => {}));
73
74 //#endregion
75 //#region node_modules/@babel/runtime/helpers/esm/toPrimitive.js
76 function toPrimitive(t, r) {
77 if ("object" != _typeof(t) || !t) return t;
78 var e = t[Symbol.toPrimitive];
79 if (void 0 !== e) {
80 var i = e.call(t, r || "default");
81 if ("object" != _typeof(i)) return i;
82 throw new TypeError("@@toPrimitive must return a primitive value.");
83 }
84 return ("string" === r ? String : Number)(t);
85 }
86 var init_toPrimitive = __esmMin((() => {
87 init_typeof();
88 }));
89
90 //#endregion
91 //#region node_modules/@babel/runtime/helpers/esm/toPropertyKey.js
92 function toPropertyKey(t) {
93 var i = toPrimitive(t, "string");
94 return "symbol" == _typeof(i) ? i : i + "";
95 }
96 var init_toPropertyKey = __esmMin((() => {
97 init_typeof();
98 init_toPrimitive();
99 }));
100
101 //#endregion
102 //#region node_modules/@babel/runtime/helpers/esm/createClass.js
103 init_toPropertyKey();
104 function _defineProperties$1(e, r) {
105 for (var t = 0; t < r.length; t++) {
106 var o = r[t];
107 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
108 }
109 }
110 __name(_defineProperties$1, "_defineProperties");
111 function _createClass(e, r, t) {
112 return r && _defineProperties$1(e.prototype, r), t && _defineProperties$1(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e;
113 }
114
115 //#endregion
116 //#region node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
117 function _assertThisInitialized(e) {
118 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
119 return e;
120 }
121
122 //#endregion
123 //#region node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
124 init_typeof();
125 function _possibleConstructorReturn(t, e) {
126 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
127 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
128 return _assertThisInitialized(t);
129 }
130
131 //#endregion
132 //#region node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
133 function _getPrototypeOf(t) {
134 return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t) {
135 return t.__proto__ || Object.getPrototypeOf(t);
136 }, _getPrototypeOf(t);
137 }
138
139 //#endregion
140 //#region node_modules/@babel/runtime/helpers/esm/superPropBase.js
141 function _superPropBase(t, o) {
142 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
143 return t;
144 }
145
146 //#endregion
147 //#region node_modules/@babel/runtime/helpers/esm/get.js
148 function _get() {
149 return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function(e, t, r) {
150 var p = _superPropBase(e, t);
151 if (p) {
152 var n = Object.getOwnPropertyDescriptor(p, t);
153 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
154 }
155 }, _get.apply(null, arguments);
156 }
157
158 //#endregion
159 //#region node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
160 function _setPrototypeOf(t, e) {
161 return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t, e) {
162 return t.__proto__ = e, t;
163 }, _setPrototypeOf(t, e);
164 }
165
166 //#endregion
167 //#region node_modules/@babel/runtime/helpers/esm/inherits.js
168 function _inherits$1(t, e) {
169 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
170 t.prototype = Object.create(e && e.prototype, { constructor: {
171 value: t,
172 writable: !0,
173 configurable: !0
174 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e);
175 }
176 __name(_inherits$1, "_inherits");
177
178 //#endregion
179 //#region core/common/assets/js/utils/helpers.js
180 var Helpers = /*#__PURE__*/ function() {
181 function Helpers() {
182 _classCallCheck(this, Helpers);
183 }
184 return _createClass(Helpers, [
185 {
186 key: "consoleWarn",
187 value: function consoleWarn() {
188 var _elementorDevTools;
189 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
190 elementorDevTools.deprecation.deprecated("elementorCommon.helpers.consoleWarn()", "3.7.0", "elementorDevTools.consoleWarn()");
191 }
192 },
193 {
194 key: "consoleError",
195 value: function consoleError(message) {
196 console.error(message);
197 elementorDevTools.deprecation.deprecated("elementorCommon.helpers.consoleError()", "3.7.0", "console.error()");
198 }
199 },
200 {
201 key: "cloneObject",
202 value: function cloneObject(object) {
203 return JSON.parse(JSON.stringify(object));
204 }
205 },
206 {
207 key: "upperCaseWords",
208 value: function upperCaseWords(string) {
209 return (string + "").replace(/^(.)|\s+(.)/g, function($1) {
210 return $1.toUpperCase();
211 });
212 }
213 },
214 {
215 key: "getUniqueId",
216 value: function getUniqueId() {
217 return Math.random().toString(16).substr(2, 7);
218 }
219 }
220 ]);
221 }();
222
223 //#endregion
224 //#region core/common/assets/js/utils/storage.js
225 function _callSuper$34(t, o, e) {
226 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$35() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
227 }
228 __name(_callSuper$34, "_callSuper");
229 function _isNativeReflectConstruct$35() {
230 try {
231 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
232 } catch (t) {}
233 return (_isNativeReflectConstruct$35 = function _isNativeReflectConstruct() {
234 return !!t;
235 })();
236 }
237 __name(_isNativeReflectConstruct$35, "_isNativeReflectConstruct");
238 var _default$11 = /*#__PURE__*/ function(_elementorModules$Mod) {
239 function _default() {
240 _classCallCheck(this, _default);
241 return _callSuper$34(this, _default, arguments);
242 }
243 _inherits$1(_default, _elementorModules$Mod);
244 return _createClass(_default, [
245 {
246 key: "get",
247 value: function get(key, options) {
248 options = options || {};
249 var storage;
250 try {
251 storage = options.session ? sessionStorage : localStorage;
252 } catch (e) {
253 return key ? void 0 : {};
254 }
255 var elementorStorage = storage.getItem("elementor");
256 if (elementorStorage) elementorStorage = JSON.parse(elementorStorage);
257 else elementorStorage = {};
258 if (!elementorStorage.__expiration) elementorStorage.__expiration = {};
259 var expiration = elementorStorage.__expiration;
260 var expirationToCheck = [];
261 if (key) {
262 if (expiration[key]) expirationToCheck = [key];
263 } else expirationToCheck = Object.keys(expiration);
264 var entryExpired = false;
265 expirationToCheck.forEach(function(expirationKey) {
266 if (new Date(expiration[expirationKey]) < /* @__PURE__ */ new Date()) {
267 delete elementorStorage[expirationKey];
268 delete expiration[expirationKey];
269 entryExpired = true;
270 }
271 });
272 if (entryExpired) this.save(elementorStorage, options.session);
273 if (key) return elementorStorage[key];
274 return elementorStorage;
275 }
276 },
277 {
278 key: "set",
279 value: function set(key, value, options) {
280 options = options || {};
281 var elementorStorage = this.get(null, options);
282 elementorStorage[key] = value;
283 if (options.lifetimeInSeconds) {
284 var date = /* @__PURE__ */ new Date();
285 date.setTime(date.getTime() + options.lifetimeInSeconds * 1e3);
286 elementorStorage.__expiration[key] = date.getTime();
287 }
288 this.save(elementorStorage, options.session);
289 }
290 },
291 {
292 key: "save",
293 value: function save(object, session) {
294 var storage;
295 try {
296 storage = session ? sessionStorage : localStorage;
297 } catch (e) {
298 return;
299 }
300 storage.setItem("elementor", JSON.stringify(object));
301 }
302 }
303 ]);
304 }(elementorModules.Module);
305
306 //#endregion
307 //#region core/common/assets/js/utils/debug.js
308 var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
309 var Debug = function Debug() {
310 var self = this;
311 var errorStack = [];
312 var settings = {};
313 var elements = {};
314 var initSettings = function initSettings() {
315 settings = {
316 debounceDelay: 500,
317 urlsToWatch: ["elementor/assets"]
318 };
319 };
320 var initElements = function initElements() {
321 elements.$window = jQuery(window);
322 };
323 var onError = function onError(event) {
324 var _event$originalEvent;
325 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
326 if (!error) return;
327 var isInWatchList = false;
328 var urlsToWatch = settings.urlsToWatch;
329 jQuery.each(urlsToWatch, function() {
330 if (-1 !== error.stack.indexOf(this)) {
331 isInWatchList = true;
332 return false;
333 }
334 });
335 if (!isInWatchList) return;
336 self.addError({
337 type: error.name,
338 message: error.message,
339 url: event.originalEvent.filename,
340 line: event.originalEvent.lineno,
341 column: event.originalEvent.colno
342 });
343 };
344 var bindEvents = function bindEvents() {
345 elements.$window.on("error", onError);
346 };
347 var init = function init() {
348 initSettings();
349 initElements();
350 bindEvents();
351 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
352 };
353 this.addURLToWatch = function(url) {
354 settings.urlsToWatch.push(url);
355 };
356 this.addCustomError = function(error, category, tag) {
357 var errorInfo = {
358 type: error.name,
359 message: error.message,
360 url: error.fileName || error.sourceURL,
361 line: error.lineNumber || error.line,
362 column: error.columnNumber || error.column,
363 customFields: {
364 category: category || "general",
365 tag
366 }
367 };
368 if (!errorInfo.url) {
369 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
370 if (stackInfo) {
371 errorInfo.url = stackInfo[1];
372 errorInfo.line = stackInfo[2];
373 errorInfo.column = stackInfo[3];
374 }
375 }
376 this.addError(errorInfo);
377 };
378 this.addError = function(errorParams) {
379 var defaultParams = {
380 type: "Error",
381 timestamp: Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3),
382 message: null,
383 url: null,
384 line: null,
385 column: null,
386 customFields: {}
387 };
388 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
389 self.sendErrors();
390 };
391 this.sendErrors = function() {
392 elements.$window.off("error", onError);
393 jQuery.ajax({
394 url: elementorCommon.config.ajax.url,
395 method: "POST",
396 data: {
397 action: "elementor_js_log",
398 _nonce: elementorCommon.ajax.getSettings("nonce"),
399 data: errorStack
400 },
401 success: function success() {
402 errorStack = [];
403 elements.$window.on("error", onError);
404 }
405 });
406 };
407 init();
408 };
409 module.exports = Debug;
410 }));
411
412 //#endregion
413 //#region node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
414 var import_debug = /* @__PURE__ */ __toESM(require_debug());
415 function _arrayWithHoles(r) {
416 if (Array.isArray(r)) return r;
417 }
418
419 //#endregion
420 //#region node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
421 function _iterableToArrayLimit(r, l) {
422 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
423 if (null != t) {
424 var e;
425 var n;
426 var i;
427 var u;
428 var a = [];
429 var f = !0;
430 var o = !1;
431 try {
432 if (i = (t = t.call(r)).next, 0 === l) {
433 if (Object(t) !== t) return;
434 f = !1;
435 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
436 } catch (r) {
437 o = !0, n = r;
438 } finally {
439 try {
440 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
441 } finally {
442 if (o) throw n;
443 }
444 }
445 return a;
446 }
447 }
448
449 //#endregion
450 //#region node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js
451 function _arrayLikeToArray$1(r, a) {
452 (null == a || a > r.length) && (a = r.length);
453 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
454 return n;
455 }
456 __name(_arrayLikeToArray$1, "_arrayLikeToArray");
457
458 //#endregion
459 //#region node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js
460 function _unsupportedIterableToArray$1(r, a) {
461 if (r) {
462 if ("string" == typeof r) return _arrayLikeToArray$1(r, a);
463 var t = {}.toString.call(r).slice(8, -1);
464 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$1(r, a) : void 0;
465 }
466 }
467 __name(_unsupportedIterableToArray$1, "_unsupportedIterableToArray");
468
469 //#endregion
470 //#region node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
471 function _nonIterableRest() {
472 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
473 }
474
475 //#endregion
476 //#region node_modules/@babel/runtime/helpers/esm/slicedToArray.js
477 function _slicedToArray(r, e) {
478 return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray$1(r, e) || _nonIterableRest();
479 }
480
481 //#endregion
482 //#region core/common/modules/ajax/assets/js/ajax.js
483 function _callSuper$33(t, o, e) {
484 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$34() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
485 }
486 __name(_callSuper$33, "_callSuper");
487 function _isNativeReflectConstruct$34() {
488 try {
489 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
490 } catch (t) {}
491 return (_isNativeReflectConstruct$34 = function _isNativeReflectConstruct() {
492 return !!t;
493 })();
494 }
495 __name(_isNativeReflectConstruct$34, "_isNativeReflectConstruct");
496 var _default$10 = /*#__PURE__*/ function(_elementorModules$Mod) {
497 function _default() {
498 var _this;
499 _classCallCheck(this, _default);
500 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
501 _this = _callSuper$33(this, _default, [].concat(args));
502 _this.requests = {};
503 _this.cache = {};
504 _this.initRequestConstants();
505 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
506 return _this;
507 }
508 _inherits$1(_default, _elementorModules$Mod);
509 return _createClass(_default, [
510 {
511 key: "getDefaultSettings",
512 value: function getDefaultSettings() {
513 return {
514 ajaxParams: {
515 type: "POST",
516 url: elementorCommon.config.ajax.url,
517 data: {},
518 dataType: "json"
519 },
520 actionPrefix: "elementor_"
521 };
522 }
523 },
524 {
525 key: "initRequestConstants",
526 value: function initRequestConstants() {
527 this.requestConstants = { _nonce: this.getSettings("nonce") };
528 }
529 },
530 {
531 key: "addRequestConstant",
532 value: function addRequestConstant(key, value) {
533 this.requestConstants[key] = value;
534 }
535 },
536 {
537 key: "getCacheKey",
538 value: function getCacheKey(request) {
539 return JSON.stringify({
540 unique_id: request.unique_id,
541 data: request.data
542 });
543 }
544 },
545 {
546 key: "loadObjects",
547 value: function loadObjects(options) {
548 var _this2 = this;
549 var dataCollection = {};
550 var deferredArray = [];
551 if (options.before) options.before();
552 options.ids.forEach(function(objectId) {
553 deferredArray.push(_this2.load({
554 action: options.action,
555 unique_id: options.data.unique_id + objectId,
556 data: jQuery.extend({ id: objectId }, options.data)
557 }).done(function(data) {
558 return dataCollection = jQuery.extend(dataCollection, data);
559 }));
560 });
561 jQuery.when.apply(jQuery, deferredArray).done(function() {
562 return options.success(dataCollection);
563 });
564 }
565 },
566 {
567 key: "load",
568 value: function load(request, immediately) {
569 var _this3 = this;
570 if (!request.unique_id) request.unique_id = request.action;
571 if (request.before) request.before();
572 var deferred;
573 var cacheKey = this.getCacheKey(request);
574 if (_.has(this.cache, cacheKey)) deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
575 else {
576 var _request$error;
577 deferred = this.addRequest(request.action, {
578 data: request.data,
579 unique_id: request.unique_id,
580 success: function success(data) {
581 return _this3.cache[cacheKey] = data;
582 },
583 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function() {}
584 }, immediately).done(request.success);
585 }
586 return deferred;
587 }
588 },
589 {
590 key: "cancelRequest",
591 value: function cancelRequest(requestId) {
592 var request = this.requests[requestId];
593 if (!request) return null;
594 if (request.options.deferred.jqXhr) return request.options.deferred.jqXhr.abort("Request canceled");
595 if (request.options.deferred) return request.options.deferred.reject("Request canceled");
596 }
597 },
598 {
599 key: "addRequest",
600 value: function addRequest(action, options, immediately) {
601 options = options || {};
602 if (!options.unique_id) options.unique_id = action;
603 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
604 var request = {
605 action,
606 options
607 };
608 if (immediately) {
609 var requests = {};
610 requests[options.unique_id] = request;
611 options.deferred.jqXhr = this.sendBatch(requests);
612 } else {
613 var pendingRequest = this.requests[options.unique_id];
614 if (pendingRequest) {
615 if (this.getCacheKey(pendingRequest.options) === this.getCacheKey(options)) {
616 pendingRequest.options.deferred.done(function(data) {
617 return options.deferred.resolve(data);
618 }).fail(function(data) {
619 return options.deferred.reject(data);
620 });
621 return options.deferred;
622 }
623 pendingRequest.options.deferred.reject("Request replaced");
624 }
625 this.requests[options.unique_id] = request;
626 this.debounceSendBatch();
627 }
628 return options.deferred;
629 }
630 },
631 {
632 key: "sendBatch",
633 value: function sendBatch(requests) {
634 var actions = {};
635 if (!requests) {
636 requests = this.requests;
637 this.requests = {};
638 }
639 Object.entries(requests).forEach(function(_ref) {
640 var _ref2 = _slicedToArray(_ref, 2);
641 var id = _ref2[0];
642 var request = _ref2[1];
643 return actions[id] = {
644 action: request.action,
645 data: request.options.data
646 };
647 });
648 return this.send("ajax", {
649 data: { actions: JSON.stringify(actions) },
650 success: function success(data) {
651 Object.entries(data.responses).forEach(function(_ref3) {
652 var _ref4 = _slicedToArray(_ref3, 2);
653 var id = _ref4[0];
654 var response = _ref4[1];
655 var options = requests[id].options;
656 if (options) {
657 if (response.success) options.deferred.resolve(response.data);
658 else if (!response.success) options.deferred.reject(response.data);
659 }
660 });
661 },
662 error: function error(data) {
663 return Object.values(requests).forEach(function(args) {
664 if (args.options) args.options.deferred.reject(data);
665 });
666 }
667 });
668 }
669 },
670 {
671 key: "prepareSend",
672 value: function prepareSend(action, options) {
673 var _this4 = this;
674 var settings = this.getSettings();
675 var ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
676 options = options || {};
677 action = settings.actionPrefix + action;
678 jQuery.extend(ajaxParams, options);
679 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
680 requestConstants.action = action;
681 var isFormData = ajaxParams.data instanceof FormData;
682 Object.entries(requestConstants).forEach(function(_ref5) {
683 var _ref6 = _slicedToArray(_ref5, 2);
684 var key = _ref6[0];
685 var value = _ref6[1];
686 if (isFormData) ajaxParams.data.append(key, value);
687 else ajaxParams.data[key] = value;
688 });
689 var successCallback = ajaxParams.success;
690 var errorCallback = ajaxParams.error;
691 if (successCallback || errorCallback) {
692 ajaxParams.success = function(response) {
693 if (response.success && successCallback) successCallback(response.data);
694 if (!response.success && errorCallback) errorCallback(response.data);
695 };
696 if (errorCallback) ajaxParams.error = function(data) {
697 return errorCallback(data);
698 };
699 else ajaxParams.error = function(xmlHttpRequest) {
700 if (xmlHttpRequest.readyState || "abort" !== xmlHttpRequest.statusText) _this4.trigger("request:unhandledError", xmlHttpRequest);
701 };
702 }
703 return ajaxParams;
704 }
705 },
706 {
707 key: "send",
708 value: function send(action, options) {
709 return jQuery.ajax(this.prepareSend(action, options));
710 }
711 },
712 {
713 key: "addRequestCache",
714 value: function addRequestCache(request, data) {
715 var cacheKey = this.getCacheKey(request);
716 this.cache[cacheKey] = data;
717 }
718 },
719 {
720 key: "invalidateCache",
721 value: function invalidateCache(request) {
722 var cacheKey = this.getCacheKey(request);
723 delete this.cache[cacheKey];
724 }
725 }
726 ]);
727 }(elementorModules.Module);
728
729 //#endregion
730 //#region node_modules/@babel/runtime/helpers/esm/defineProperty.js
731 function _defineProperty(e, r, t) {
732 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
733 value: t,
734 enumerable: !0,
735 configurable: !0,
736 writable: !0
737 }) : e[r] = t, e;
738 }
739 var init_defineProperty = __esmMin((() => {
740 init_toPropertyKey();
741 }));
742
743 //#endregion
744 //#region assets/dev/js/modules/imports/instance-type.js
745 init_defineProperty();
746 function _superPropGet$7(t, o, e, r) {
747 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
748 return 2 & r && "function" == typeof p ? function(t) {
749 return p.apply(e, t);
750 } : p;
751 }
752 __name(_superPropGet$7, "_superPropGet");
753 var InstanceType = /*#__PURE__*/ function() {
754 function InstanceType() {
755 var _this = this;
756 _classCallCheck(this, InstanceType);
757 var target = this instanceof InstanceType ? this.constructor : void 0;
758 var prototypes = [];
759 while (target.__proto__ && target.__proto__.name) {
760 prototypes.push(target.__proto__);
761 target = target.__proto__;
762 }
763 prototypes.reverse().forEach(function(proto) {
764 return _this instanceof proto;
765 });
766 }
767 return _createClass(InstanceType, null, [{
768 key: Symbol.hasInstance,
769 value: function value(target) {
770 /**
771 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
772 * its give's opportunity to mange capabilities of instanceOf operator.
773 * saving current class each time will give option later to handle instanceOf manually.
774 */
775 var result = _superPropGet$7(InstanceType, Symbol.hasInstance, this, 2)([target]);
776 if (target && !target.constructor.getInstanceType) return result;
777 if (target) {
778 if (!target.instanceTypes) target.instanceTypes = [];
779 if (!result) {
780 if (this.getInstanceType() === target.constructor.getInstanceType()) result = true;
781 }
782 if (result) {
783 var name = this.getInstanceType === InstanceType.getInstanceType ? "BaseInstanceType" : this.getInstanceType();
784 if (-1 === target.instanceTypes.indexOf(name)) target.instanceTypes.push(name);
785 }
786 }
787 if (!result && target) result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
788 return result;
789 }
790 }, {
791 key: "getInstanceType",
792 value: function getInstanceType() {
793 elementorModules.ForceMethodImplementation();
794 }
795 }]);
796 }();
797
798 //#endregion
799 //#region assets/dev/js/editor/utils/is-instanceof.js
800 function _createForOfIteratorHelper(r, e) {
801 var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
802 if (!t) {
803 if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
804 t && (r = t);
805 var _n = 0;
806 var F = function F() {};
807 return {
808 s: F,
809 n: function n() {
810 return _n >= r.length ? { done: !0 } : {
811 done: !1,
812 value: r[_n++]
813 };
814 },
815 e: function e(r) {
816 throw r;
817 },
818 f: F
819 };
820 }
821 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
822 }
823 var o;
824 var a = !0;
825 var u = !1;
826 return {
827 s: function s() {
828 t = t.call(r);
829 },
830 n: function n() {
831 var r = t.next();
832 return a = r.done, r;
833 },
834 e: function e(r) {
835 u = !0, o = r;
836 },
837 f: function f() {
838 try {
839 a || null == t.return || t.return();
840 } finally {
841 if (u) throw o;
842 }
843 }
844 };
845 }
846 function _unsupportedIterableToArray(r, a) {
847 if (r) {
848 if ("string" == typeof r) return _arrayLikeToArray(r, a);
849 var t = {}.toString.call(r).slice(8, -1);
850 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;
851 }
852 }
853 function _arrayLikeToArray(r, a) {
854 (null == a || a > r.length) && (a = r.length);
855 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
856 return n;
857 }
858 /**
859 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
860 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
861 * check whether it's instanceof by using the objects constructor and prototype names.
862 *
863 * @param object
864 * @param constructors
865 * @return {boolean}
866 */
867 var is_instanceof_default = /* @__PURE__ */ __name((function(object, constructors) {
868 constructors = Array.isArray(constructors) ? constructors : [constructors];
869 var _iterator = _createForOfIteratorHelper(constructors);
870 var _step;
871 try {
872 for (_iterator.s(); !(_step = _iterator.n()).done;) {
873 var constructor = _step.value;
874 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) return true;
875 }
876 } catch (err) {
877 _iterator.e(err);
878 } finally {
879 _iterator.f();
880 }
881 return false;
882 }), "default");
883
884 //#endregion
885 //#region assets/dev/js/modules/imports/args-object.js
886 init_typeof();
887 function _callSuper$32(t, o, e) {
888 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$33() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
889 }
890 __name(_callSuper$32, "_callSuper");
891 function _isNativeReflectConstruct$33() {
892 try {
893 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
894 } catch (t) {}
895 return (_isNativeReflectConstruct$33 = function _isNativeReflectConstruct() {
896 return !!t;
897 })();
898 }
899 __name(_isNativeReflectConstruct$33, "_isNativeReflectConstruct");
900 var ArgsObject = /*#__PURE__*/ function(_InstanceType) {
901 /**
902 * Function constructor().
903 *
904 * Create ArgsObject.
905 *
906 * @param {{}} args
907 */
908 function ArgsObject(args) {
909 var _this;
910 _classCallCheck(this, ArgsObject);
911 _this = _callSuper$32(this, ArgsObject);
912 _this.args = args;
913 return _this;
914 }
915 /**
916 * Function requireArgument().
917 *
918 * Validate property in args.
919 *
920 * @param {string} property
921 * @param {{}} args
922 *
923 * @throws {Error}
924 */
925 _inherits$1(ArgsObject, _InstanceType);
926 return _createClass(ArgsObject, [
927 {
928 key: "requireArgument",
929 value: function requireArgument(property) {
930 var args = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this.args;
931 if (!Object.prototype.hasOwnProperty.call(args, property)) throw Error("".concat(property, " is required."));
932 }
933 },
934 {
935 key: "requireArgumentType",
936 value: function requireArgumentType(property, type) {
937 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
938 this.requireArgument(property, args);
939 if (_typeof(args[property]) !== type) throw Error("".concat(property, " invalid type: ").concat(type, "."));
940 }
941 },
942 {
943 key: "requireArgumentInstance",
944 value: function requireArgumentInstance(property, instance) {
945 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
946 this.requireArgument(property, args);
947 if (!(args[property] instanceof instance) && !is_instanceof_default(args[property], instance)) throw Error("".concat(property, " invalid instance."));
948 }
949 },
950 {
951 key: "requireArgumentConstructor",
952 value: function requireArgumentConstructor(property, type) {
953 var args = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.args;
954 this.requireArgument(property, args);
955 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) throw Error("".concat(property, " invalid constructor type."));
956 }
957 }
958 ], [{
959 key: "getInstanceType",
960 value: function getInstanceType() {
961 return "ArgsObject";
962 }
963 }]);
964 }(InstanceType);
965
966 //#endregion
967 //#region modules/web-cli/assets/js/utils/console.js
968 var Console = /*#__PURE__*/ function() {
969 function Console() {
970 _classCallCheck(this, Console);
971 }
972 return _createClass(Console, null, [{
973 key: "error",
974 value: function error(message) {
975 if ($e.devTools) $e.devTools.log.error(message);
976 if (!(message instanceof $e.modules.HookBreak)) console.error(message);
977 }
978 }, {
979 key: "warn",
980 value: function warn() {
981 var _console;
982 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
983 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
984 args.unshift("%c %c", style, "");
985 (_console = console).warn.apply(_console, args);
986 }
987 }]);
988 }();
989
990 //#endregion
991 //#region modules/web-cli/assets/js/utils/deprecation.js
992 /**
993 * @typedef {Object} Version
994 * @property {number} major1 The first number
995 * @property {number} major2 The second number
996 * @property {number} minor The third number
997 * @property {string} build The fourth number
998 */
999 var softDeprecated = function softDeprecated(name, version, replacement) {
1000 if (elementorWebCliConfig.isDebug) deprecatedMessage("soft", name, version, replacement);
1001 };
1002 var hardDeprecated = function hardDeprecated(name, version, replacement) {
1003 deprecatedMessage("hard", name, version, replacement);
1004 };
1005 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
1006 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
1007 if (replacement) message += " - Use `".concat(replacement, "` instead");
1008 Console.warn(message);
1009 };
1010 var Deprecation = /*#__PURE__*/ function() {
1011 function Deprecation() {
1012 _classCallCheck(this, Deprecation);
1013 }
1014 return _createClass(Deprecation, null, [
1015 {
1016 key: "deprecated",
1017 value: function deprecated(name, version, replacement) {
1018 if (this.isHardDeprecated(version)) hardDeprecated(name, version, replacement);
1019 else softDeprecated(name, version, replacement);
1020 }
1021 },
1022 {
1023 key: "parseVersion",
1024 value: function parseVersion(version) {
1025 var versionParts = version.split(".");
1026 if (versionParts.length < 3 || versionParts.length > 4) throw new RangeError("Invalid Semantic Version string provided");
1027 var _versionParts = _slicedToArray(versionParts, 4);
1028 var major1 = _versionParts[0];
1029 var major2 = _versionParts[1];
1030 var minor = _versionParts[2];
1031 var _versionParts$ = _versionParts[3];
1032 return {
1033 major1: parseInt(major1),
1034 major2: parseInt(major2),
1035 minor: parseInt(minor),
1036 build: _versionParts$ === void 0 ? "" : _versionParts$
1037 };
1038 }
1039 },
1040 {
1041 key: "getTotalMajor",
1042 value: function getTotalMajor(versionObj) {
1043 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
1044 total = Number((total / 10).toFixed(0));
1045 if (versionObj.major2 > 9) total = versionObj.major2 - 9;
1046 return total;
1047 }
1048 },
1049 {
1050 key: "compareVersion",
1051 value: function compareVersion(version1, version2) {
1052 var _this = this;
1053 return [this.parseVersion(version1), this.parseVersion(version2)].map(function(versionObj) {
1054 return _this.getTotalMajor(versionObj);
1055 }).reduce(function(acc, major) {
1056 return acc - major;
1057 });
1058 }
1059 },
1060 {
1061 key: "isSoftDeprecated",
1062 value: function isSoftDeprecated(version) {
1063 return this.compareVersion(version, elementorWebCliConfig.version) <= 4;
1064 }
1065 },
1066 {
1067 key: "isHardDeprecated",
1068 value: function isHardDeprecated(version) {
1069 var total = this.compareVersion(version, elementorWebCliConfig.version);
1070 return total < 0 || total >= 8;
1071 }
1072 }
1073 ]);
1074 }();
1075
1076 //#endregion
1077 //#region modules/web-cli/assets/js/modules/command-infra.js
1078 function _callSuper$31(t, o, e) {
1079 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$32() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1080 }
1081 __name(_callSuper$31, "_callSuper");
1082 function _isNativeReflectConstruct$32() {
1083 try {
1084 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1085 } catch (t) {}
1086 return (_isNativeReflectConstruct$32 = function _isNativeReflectConstruct() {
1087 return !!t;
1088 })();
1089 }
1090 __name(_isNativeReflectConstruct$32, "_isNativeReflectConstruct");
1091 /**
1092 * @typedef {import('../modules/component-base')} ComponentBase
1093 */
1094 var CommandInfra = /*#__PURE__*/ function(_ArgsObject) {
1095 /**
1096 * Function constructor().
1097 *
1098 * Create Commands Base.
1099 *
1100 * @param {{}} args
1101 */
1102 function CommandInfra() {
1103 var _this;
1104 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1105 _classCallCheck(this, CommandInfra);
1106 _this = _callSuper$31(this, CommandInfra, [args]);
1107 if (!_this.constructor.registerConfig) throw RangeError("Doing it wrong: Each command type should have `registerConfig`.");
1108 _this.command = _this.constructor.getCommand();
1109 _this.component = _this.constructor.getComponent();
1110 _this.initialize(args);
1111 args = _this.args;
1112 _this.validateArgs(args);
1113 return _this;
1114 }
1115 /**
1116 * Function initialize().
1117 *
1118 * Initialize command, called after construction.
1119 *
1120 * @param {{}} args
1121 */
1122 _inherits$1(CommandInfra, _ArgsObject);
1123 return _createClass(CommandInfra, [
1124 {
1125 key: "currentCommand",
1126 get: function get() {
1127 Deprecation.deprecated("this.currentCommand", "3.7.0", "this.command");
1128 return this.command;
1129 }
1130 },
1131 {
1132 key: "initialize",
1133 value: function initialize() {
1134 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1135 }
1136 },
1137 {
1138 key: "validateArgs",
1139 value: function validateArgs() {
1140 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1141 }
1142 },
1143 {
1144 key: "apply",
1145 value: function apply() {
1146 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1147 elementorModules.ForceMethodImplementation();
1148 }
1149 },
1150 {
1151 key: "run",
1152 value: function run() {
1153 return this.apply(this.args);
1154 }
1155 },
1156 {
1157 key: "onBeforeRun",
1158 value: function onBeforeRun() {
1159 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1160 }
1161 },
1162 {
1163 key: "onAfterRun",
1164 value: function onAfterRun() {
1165 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1166 arguments.length > 1 && arguments[1];
1167 }
1168 },
1169 {
1170 key: "onBeforeApply",
1171 value: function onBeforeApply() {
1172 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1173 }
1174 },
1175 {
1176 key: "onAfterApply",
1177 value: function onAfterApply() {
1178 arguments.length > 0 && arguments[0] !== void 0 && arguments[0];
1179 arguments.length > 1 && arguments[1];
1180 }
1181 },
1182 {
1183 key: "onCatchApply",
1184 value: function onCatchApply(e) {}
1185 }
1186 ], [
1187 {
1188 key: "getInstanceType",
1189 value: function getInstanceType() {
1190 return "CommandInfra";
1191 }
1192 },
1193 {
1194 key: "getInfo",
1195 value: function getInfo() {
1196 return {};
1197 }
1198 },
1199 {
1200 key: "getCommand",
1201 value: function getCommand() {
1202 return this.registerConfig.command;
1203 }
1204 },
1205 {
1206 key: "getComponent",
1207 value: function getComponent() {
1208 return this.registerConfig.component;
1209 }
1210 },
1211 {
1212 key: "setRegisterConfig",
1213 value: function setRegisterConfig(config) {
1214 this.registerConfig = Object.freeze(config);
1215 }
1216 }
1217 ]);
1218 }(ArgsObject);
1219 /**
1220 * @type {Object}
1221 */
1222 _defineProperty(CommandInfra, "registerConfig", null);
1223
1224 //#endregion
1225 //#region modules/web-cli/assets/js/modules/command-base.js
1226 function _callSuper$30(t, o, e) {
1227 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$31() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1228 }
1229 __name(_callSuper$30, "_callSuper");
1230 function _isNativeReflectConstruct$31() {
1231 try {
1232 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1233 } catch (t) {}
1234 return (_isNativeReflectConstruct$31 = function _isNativeReflectConstruct() {
1235 return !!t;
1236 })();
1237 }
1238 __name(_isNativeReflectConstruct$31, "_isNativeReflectConstruct");
1239 /**
1240 * @name $e.modules.CommandBase
1241 */
1242 var CommandBase = /*#__PURE__*/ function(_CommandInfra) {
1243 function CommandBase() {
1244 _classCallCheck(this, CommandBase);
1245 return _callSuper$30(this, CommandBase, arguments);
1246 }
1247 _inherits$1(CommandBase, _CommandInfra);
1248 return _createClass(CommandBase, [
1249 {
1250 key: "onBeforeRun",
1251 value: function onBeforeRun() {
1252 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1253 $e.hooks.runUIBefore(this.command, args);
1254 }
1255 },
1256 {
1257 key: "onAfterRun",
1258 value: function onAfterRun() {
1259 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1260 var result = arguments.length > 1 ? arguments[1] : void 0;
1261 $e.hooks.runUIAfter(this.command, args, result);
1262 }
1263 },
1264 {
1265 key: "onBeforeApply",
1266 value: function onBeforeApply() {
1267 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1268 $e.hooks.runDataDependency(this.command, args);
1269 }
1270 },
1271 {
1272 key: "onAfterApply",
1273 value: function onAfterApply() {
1274 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1275 var result = arguments.length > 1 ? arguments[1] : void 0;
1276 return $e.hooks.runDataAfter(this.command, args, result);
1277 }
1278 },
1279 {
1280 key: "onCatchApply",
1281 value: function onCatchApply(e) {
1282 this.runCatchHooks(e);
1283 }
1284 },
1285 {
1286 key: "runCatchHooks",
1287 value: function runCatchHooks(e) {
1288 $e.hooks.runDataCatch(this.command, this.args, e);
1289 $e.hooks.runUICatch(this.command, this.args, e);
1290 }
1291 },
1292 {
1293 key: "requireContainer",
1294 value: function requireContainer() {
1295 var _this = this;
1296 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.args;
1297 Deprecation.deprecated("requireContainer()", "3.7.0", "Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`");
1298 if (!args.container && !args.containers) throw Error("container or containers are required.");
1299 if (args.container && args.containers) throw Error("container and containers cannot go together please select one of them.");
1300 (args.containers || [args.container]).forEach(function(container) {
1301 _this.requireArgumentInstance("container", elementorModules.editor.Container, { container });
1302 });
1303 }
1304 }
1305 ], [{
1306 key: "getInstanceType",
1307 value: function getInstanceType() {
1308 return "CommandBase";
1309 }
1310 }]);
1311 }(CommandInfra);
1312
1313 //#endregion
1314 //#region modules/web-cli/assets/js/modules/command-callback-base.js
1315 function _callSuper$29(t, o, e) {
1316 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$30() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1317 }
1318 __name(_callSuper$29, "_callSuper");
1319 function _isNativeReflectConstruct$30() {
1320 try {
1321 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1322 } catch (t) {}
1323 return (_isNativeReflectConstruct$30 = function _isNativeReflectConstruct() {
1324 return !!t;
1325 })();
1326 }
1327 __name(_isNativeReflectConstruct$30, "_isNativeReflectConstruct");
1328 /**
1329 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
1330 */
1331 var CommandCallbackBase = /*#__PURE__*/ function(_CommandBase) {
1332 function CommandCallbackBase() {
1333 _classCallCheck(this, CommandCallbackBase);
1334 return _callSuper$29(this, CommandCallbackBase, arguments);
1335 }
1336 _inherits$1(CommandCallbackBase, _CommandBase);
1337 return _createClass(CommandCallbackBase, [{
1338 key: "apply",
1339 value: function apply() {
1340 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1341 return this.constructor.getCallback()(args);
1342 }
1343 }], [{
1344 key: "getInstanceType",
1345 value: function getInstanceType() {
1346 return "CommandCallbackBase";
1347 }
1348 }, {
1349 key: "getCallback",
1350 value: function getCallback() {
1351 return this.registerConfig.callback;
1352 }
1353 }]);
1354 }(CommandBase);
1355
1356 //#endregion
1357 //#region assets/dev/js/modules/imports/module.js
1358 var require_module = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1359 init_typeof();
1360 var Module = function Module() {
1361 var $ = jQuery;
1362 var instanceParams = arguments;
1363 var self = this;
1364 var events = {};
1365 var settings;
1366 var ensureClosureMethods = function ensureClosureMethods() {
1367 $.each(self, function(methodName) {
1368 var oldMethod = self[methodName];
1369 if ("function" !== typeof oldMethod) return;
1370 self[methodName] = function() {
1371 return oldMethod.apply(self, arguments);
1372 };
1373 });
1374 };
1375 var initSettings = function initSettings() {
1376 settings = self.getDefaultSettings();
1377 var instanceSettings = instanceParams[0];
1378 if (instanceSettings) $.extend(true, settings, instanceSettings);
1379 };
1380 var init = function init() {
1381 self.__construct.apply(self, instanceParams);
1382 ensureClosureMethods();
1383 initSettings();
1384 self.trigger("init");
1385 };
1386 this.getItems = function(items, itemKey) {
1387 if (itemKey) {
1388 var keyStack = itemKey.split(".");
1389 var currentKey = keyStack.splice(0, 1);
1390 if (!keyStack.length) return items[currentKey];
1391 if (!items[currentKey]) return;
1392 return this.getItems(items[currentKey], keyStack.join("."));
1393 }
1394 return items;
1395 };
1396 this.getSettings = function(setting) {
1397 return this.getItems(settings, setting);
1398 };
1399 this.setSettings = function(settingKey, value, settingsContainer) {
1400 if (!settingsContainer) settingsContainer = settings;
1401 if ("object" === _typeof(settingKey)) {
1402 $.extend(settingsContainer, settingKey);
1403 return self;
1404 }
1405 var keyStack = settingKey.split(".");
1406 var currentKey = keyStack.splice(0, 1);
1407 if (!keyStack.length) {
1408 settingsContainer[currentKey] = value;
1409 return self;
1410 }
1411 if (!settingsContainer[currentKey]) settingsContainer[currentKey] = {};
1412 return self.setSettings(keyStack.join("."), value, settingsContainer[currentKey]);
1413 };
1414 this.getErrorMessage = function(type, functionName) {
1415 var message;
1416 switch (type) {
1417 case "forceMethodImplementation":
1418 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
1419 break;
1420 default: message = "An error occurs";
1421 }
1422 return message;
1423 };
1424 this.forceMethodImplementation = function(functionName) {
1425 throw new Error(this.getErrorMessage("forceMethodImplementation", functionName));
1426 };
1427 this.on = function(eventName, callback) {
1428 if ("object" === _typeof(eventName)) {
1429 $.each(eventName, function(singleEventName) {
1430 self.on(singleEventName, this);
1431 });
1432 return self;
1433 }
1434 eventName.split(" ").forEach(function(singleEventName) {
1435 if (!events[singleEventName]) events[singleEventName] = [];
1436 events[singleEventName].push(callback);
1437 });
1438 return self;
1439 };
1440 this.off = function(eventName, callback) {
1441 if (!events[eventName]) return self;
1442 if (!callback) {
1443 delete events[eventName];
1444 return self;
1445 }
1446 var callbackIndex = events[eventName].indexOf(callback);
1447 if (-1 !== callbackIndex) {
1448 delete events[eventName][callbackIndex];
1449 events[eventName] = events[eventName].filter(function(val) {
1450 return val;
1451 });
1452 }
1453 return self;
1454 };
1455 this.trigger = function(eventName) {
1456 var methodName = "on" + eventName[0].toUpperCase() + eventName.slice(1);
1457 var params = Array.prototype.slice.call(arguments, 1);
1458 if (self[methodName]) self[methodName].apply(self, params);
1459 var callbacks = events[eventName];
1460 if (!callbacks) return self;
1461 $.each(callbacks, function(index, callback) {
1462 callback.apply(self, params);
1463 });
1464 return self;
1465 };
1466 init();
1467 };
1468 Module.prototype.__construct = function() {};
1469 Module.prototype.getDefaultSettings = function() {
1470 return {};
1471 };
1472 Module.prototype.getConstructorID = function() {
1473 return this.constructor.name;
1474 };
1475 Module.extend = function(properties) {
1476 var $ = jQuery;
1477 var parent = this;
1478 var child = function child() {
1479 return parent.apply(this, arguments);
1480 };
1481 $.extend(child, parent);
1482 child.prototype = Object.create($.extend({}, parent.prototype, properties));
1483 child.prototype.constructor = child;
1484 child.__super__ = parent.prototype;
1485 return child;
1486 };
1487 module.exports = Module;
1488 }));
1489
1490 //#endregion
1491 //#region node_modules/@babel/runtime/helpers/esm/isNativeFunction.js
1492 var import_module = /* @__PURE__ */ __toESM(require_module());
1493 function _isNativeFunction(t) {
1494 try {
1495 return -1 !== Function.toString.call(t).indexOf("[native code]");
1496 } catch (n) {
1497 return "function" == typeof t;
1498 }
1499 }
1500
1501 //#endregion
1502 //#region node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js
1503 function _isNativeReflectConstruct$29() {
1504 try {
1505 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1506 } catch (t) {}
1507 return (_isNativeReflectConstruct$29 = function _isNativeReflectConstruct() {
1508 return !!t;
1509 })();
1510 }
1511 __name(_isNativeReflectConstruct$29, "_isNativeReflectConstruct");
1512
1513 //#endregion
1514 //#region node_modules/@babel/runtime/helpers/esm/construct.js
1515 function _construct$1(t, e, r) {
1516 if (_isNativeReflectConstruct$29()) return Reflect.construct.apply(null, arguments);
1517 var o = [null];
1518 o.push.apply(o, e);
1519 var p = new (t.bind.apply(t, o))();
1520 return r && _setPrototypeOf(p, r.prototype), p;
1521 }
1522 __name(_construct$1, "_construct");
1523
1524 //#endregion
1525 //#region node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js
1526 function _wrapNativeSuper(t) {
1527 var r = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0;
1528 return _wrapNativeSuper = function _wrapNativeSuper(t) {
1529 if (null === t || !_isNativeFunction(t)) return t;
1530 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
1531 if (void 0 !== r) {
1532 if (r.has(t)) return r.get(t);
1533 r.set(t, Wrapper);
1534 }
1535 function Wrapper() {
1536 return _construct$1(t, arguments, _getPrototypeOf(this).constructor);
1537 }
1538 return Wrapper.prototype = Object.create(t.prototype, { constructor: {
1539 value: Wrapper,
1540 enumerable: !1,
1541 writable: !0,
1542 configurable: !0
1543 } }), _setPrototypeOf(Wrapper, t);
1544 }, _wrapNativeSuper(t);
1545 }
1546
1547 //#endregion
1548 //#region modules/web-cli/assets/js/utils/force-method-implementation.js
1549 function _callSuper$28(t, o, e) {
1550 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$28() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1551 }
1552 __name(_callSuper$28, "_callSuper");
1553 function _isNativeReflectConstruct$28() {
1554 try {
1555 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1556 } catch (t) {}
1557 return (_isNativeReflectConstruct$28 = function _isNativeReflectConstruct() {
1558 return !!t;
1559 })();
1560 }
1561 __name(_isNativeReflectConstruct$28, "_isNativeReflectConstruct");
1562 var ForceMethodImplementation = /*#__PURE__*/ function(_Error) {
1563 function ForceMethodImplementation() {
1564 var _this;
1565 var info = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1566 _classCallCheck(this, ForceMethodImplementation);
1567 _this = _callSuper$28(this, ForceMethodImplementation, ["".concat(info.isStatic ? "static " : "").concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
1568 Error.captureStackTrace(_this, ForceMethodImplementation);
1569 return _this;
1570 }
1571 _inherits$1(ForceMethodImplementation, _Error);
1572 return _createClass(ForceMethodImplementation);
1573 }(/*#__PURE__*/ _wrapNativeSuper(Error));
1574 var force_method_implementation_default = /* @__PURE__ */ __name((function() {
1575 var caller = Error().stack.split("\n")[2].trim();
1576 var callerName = caller.startsWith("at new") ? "constructor" : caller.split(" ")[1];
1577 var info = {};
1578 info.functionName = callerName;
1579 info.fullName = callerName;
1580 if (info.functionName.includes(".")) {
1581 var parts = info.functionName.split(".");
1582 info.className = parts[0];
1583 info.functionName = parts[1];
1584 } else info.isStatic = true;
1585 throw new ForceMethodImplementation(info);
1586 }), "default");
1587
1588 //#endregion
1589 //#region modules/web-cli/assets/js/modules/component-base.js
1590 init_defineProperty();
1591 function ownKeys$4(e, r) {
1592 var t = Object.keys(e);
1593 if (Object.getOwnPropertySymbols) {
1594 var o = Object.getOwnPropertySymbols(e);
1595 r && (o = o.filter(function(r) {
1596 return Object.getOwnPropertyDescriptor(e, r).enumerable;
1597 })), t.push.apply(t, o);
1598 }
1599 return t;
1600 }
1601 __name(ownKeys$4, "ownKeys");
1602 function _objectSpread$4(e) {
1603 for (var r = 1; r < arguments.length; r++) {
1604 var t = null != arguments[r] ? arguments[r] : {};
1605 r % 2 ? ownKeys$4(Object(t), !0).forEach(function(r) {
1606 _defineProperty(e, r, t[r]);
1607 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function(r) {
1608 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
1609 });
1610 }
1611 return e;
1612 }
1613 __name(_objectSpread$4, "_objectSpread");
1614 function _callSuper$27(t, o, e) {
1615 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$27() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
1616 }
1617 __name(_callSuper$27, "_callSuper");
1618 function _isNativeReflectConstruct$27() {
1619 try {
1620 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1621 } catch (t) {}
1622 return (_isNativeReflectConstruct$27 = function _isNativeReflectConstruct() {
1623 return !!t;
1624 })();
1625 }
1626 __name(_isNativeReflectConstruct$27, "_isNativeReflectConstruct");
1627 /**
1628 * @typedef {import('./command-infra')} CommandInfra
1629 * @typedef {import('./hook-base')} HookBase
1630 * @typedef {import('../core/states/ui-state-base')} UiStateBase
1631 */
1632 var ComponentBase = /*#__PURE__*/ function(_Module) {
1633 function ComponentBase() {
1634 _classCallCheck(this, ComponentBase);
1635 return _callSuper$27(this, ComponentBase, arguments);
1636 }
1637 _inherits$1(ComponentBase, _Module);
1638 return _createClass(ComponentBase, [
1639 {
1640 key: "__construct",
1641 value: function __construct() {
1642 var args = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
1643 if (args.manager) this.manager = args.manager;
1644 this.commands = this.defaultCommands();
1645 this.commandsInternal = this.defaultCommandsInternal();
1646 this.hooks = this.defaultHooks();
1647 this.routes = this.defaultRoutes();
1648 this.tabs = this.defaultTabs();
1649 this.shortcuts = this.defaultShortcuts();
1650 this.utils = this.defaultUtils();
1651 this.data = this.defaultData();
1652 this.uiStates = this.defaultUiStates();
1653 this.states = this.defaultStates();
1654 this.defaultRoute = "";
1655 this.currentTab = "";
1656 }
1657 },
1658 {
1659 key: "registerAPI",
1660 value: function registerAPI() {
1661 var _this = this;
1662 Object.entries(this.getTabs()).forEach(function(tab) {
1663 return _this.registerTabRoute(tab[0]);
1664 });
1665 Object.entries(this.getRoutes()).forEach(function(_ref) {
1666 var _ref2 = _slicedToArray(_ref, 2);
1667 var route = _ref2[0];
1668 var callback = _ref2[1];
1669 return _this.registerRoute(route, callback);
1670 });
1671 Object.entries(this.getCommands()).forEach(function(_ref3) {
1672 var _ref4 = _slicedToArray(_ref3, 2);
1673 var command = _ref4[0];
1674 var callback = _ref4[1];
1675 return _this.registerCommand(command, callback);
1676 });
1677 Object.entries(this.getCommandsInternal()).forEach(function(_ref5) {
1678 var _ref6 = _slicedToArray(_ref5, 2);
1679 var command = _ref6[0];
1680 var callback = _ref6[1];
1681 return _this.registerCommandInternal(command, callback);
1682 });
1683 Object.values(this.getHooks()).forEach(function(instance) {
1684 return _this.registerHook(instance);
1685 });
1686 Object.entries(this.getData()).forEach(function(_ref7) {
1687 var _ref8 = _slicedToArray(_ref7, 2);
1688 var command = _ref8[0];
1689 var callback = _ref8[1];
1690 return _this.registerData(command, callback);
1691 });
1692 Object.values(this.getUiStates()).forEach(function(instance) {
1693 return _this.registerUiState(instance);
1694 });
1695 Object.entries(this.getStates()).forEach(function(_ref9) {
1696 var _ref0 = _slicedToArray(_ref9, 2);
1697 var id = _ref0[0];
1698 var state = _ref0[1];
1699 return _this.registerState(id, state);
1700 });
1701 }
1702 },
1703 {
1704 key: "getNamespace",
1705 value: function getNamespace() {
1706 force_method_implementation_default();
1707 }
1708 },
1709 {
1710 key: "getRootContainer",
1711 value: function getRootContainer() {
1712 Deprecation.deprecated("getRootContainer()", "3.7.0", "getServiceName()");
1713 return this.getServiceName();
1714 }
1715 },
1716 {
1717 key: "getServiceName",
1718 value: function getServiceName() {
1719 return this.getNamespace().split("/")[0];
1720 }
1721 },
1722 {
1723 key: "store",
1724 get: function get() {
1725 return $e.store.get(this.getNamespace());
1726 }
1727 },
1728 {
1729 key: "defaultTabs",
1730 value: function defaultTabs() {
1731 return {};
1732 }
1733 },
1734 {
1735 key: "defaultRoutes",
1736 value: function defaultRoutes() {
1737 return {};
1738 }
1739 },
1740 {
1741 key: "defaultCommands",
1742 value: function defaultCommands() {
1743 return {};
1744 }
1745 },
1746 {
1747 key: "defaultCommandsInternal",
1748 value: function defaultCommandsInternal() {
1749 return {};
1750 }
1751 },
1752 {
1753 key: "defaultHooks",
1754 value: function defaultHooks() {
1755 return {};
1756 }
1757 },
1758 {
1759 key: "defaultUiStates",
1760 value: function defaultUiStates() {
1761 return {};
1762 }
1763 },
1764 {
1765 key: "defaultStates",
1766 value: function defaultStates() {
1767 return {};
1768 }
1769 },
1770 {
1771 key: "defaultShortcuts",
1772 value: function defaultShortcuts() {
1773 return {};
1774 }
1775 },
1776 {
1777 key: "defaultUtils",
1778 value: function defaultUtils() {
1779 return {};
1780 }
1781 },
1782 {
1783 key: "defaultData",
1784 value: function defaultData() {
1785 return {};
1786 }
1787 },
1788 {
1789 key: "getCommands",
1790 value: function getCommands() {
1791 return this.commands;
1792 }
1793 },
1794 {
1795 key: "getCommandsInternal",
1796 value: function getCommandsInternal() {
1797 return this.commandsInternal;
1798 }
1799 },
1800 {
1801 key: "getHooks",
1802 value: function getHooks() {
1803 return this.hooks;
1804 }
1805 },
1806 {
1807 key: "getUiStates",
1808 value: function getUiStates() {
1809 return this.uiStates;
1810 }
1811 },
1812 {
1813 key: "getStates",
1814 value: function getStates() {
1815 return this.states;
1816 }
1817 },
1818 {
1819 key: "getRoutes",
1820 value: function getRoutes() {
1821 return this.routes;
1822 }
1823 },
1824 {
1825 key: "getTabs",
1826 value: function getTabs() {
1827 return this.tabs;
1828 }
1829 },
1830 {
1831 key: "getShortcuts",
1832 value: function getShortcuts() {
1833 return this.shortcuts;
1834 }
1835 },
1836 {
1837 key: "getData",
1838 value: function getData() {
1839 return this.data;
1840 }
1841 },
1842 {
1843 key: "registerCommand",
1844 value: function registerCommand(command, context) {
1845 var commandsType = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "default";
1846 var commandsManager;
1847 switch (commandsType) {
1848 case "default":
1849 commandsManager = $e.commands;
1850 break;
1851 case "internal":
1852 commandsManager = $e.commandsInternal;
1853 break;
1854 case "data":
1855 commandsManager = $e.data;
1856 break;
1857 default: throw new Error("Invalid commands type: '".concat(command, "'"));
1858 }
1859 var fullCommand = this.getNamespace() + "/" + command;
1860 var instanceType = context.getInstanceType ? context.getInstanceType() : false;
1861 var registerConfig = {
1862 command: fullCommand,
1863 component: this
1864 };
1865 if (!instanceType) {
1866 if ($e.devTools) $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
1867 registerConfig.callback = context;
1868 context = /*#__PURE__*/ function(_CommandCallbackBase) {
1869 function context() {
1870 _classCallCheck(this, context);
1871 return _callSuper$27(this, context, arguments);
1872 }
1873 _inherits$1(context, _CommandCallbackBase);
1874 return _createClass(context);
1875 }(CommandCallbackBase);
1876 }
1877 context.setRegisterConfig(registerConfig);
1878 commandsManager.register(this, command, context);
1879 }
1880 },
1881 {
1882 key: "registerHook",
1883 value: function registerHook(instance) {
1884 return instance.register();
1885 }
1886 },
1887 {
1888 key: "registerCommandInternal",
1889 value: function registerCommandInternal(command, context) {
1890 this.registerCommand(command, context, "internal");
1891 }
1892 },
1893 {
1894 key: "registerUiState",
1895 value: function registerUiState(instance) {
1896 $e.uiStates.register(instance);
1897 }
1898 },
1899 {
1900 key: "registerState",
1901 value: function registerState(id, stateConfig) {
1902 id = this.getNamespace() + (id ? "/".concat(id) : "");
1903 var slice = (0, _reduxjs_toolkit.createSlice)(_objectSpread$4(_objectSpread$4({}, stateConfig), {}, { name: id }));
1904 $e.store.register(id, slice);
1905 }
1906 },
1907 {
1908 key: "registerRoute",
1909 value: function registerRoute(route, callback) {
1910 $e.routes.register(this, route, callback);
1911 }
1912 },
1913 {
1914 key: "registerData",
1915 value: function registerData(command, context) {
1916 this.registerCommand(command, context, "data");
1917 }
1918 },
1919 {
1920 key: "unregisterRoute",
1921 value: function unregisterRoute(route) {
1922 $e.routes.unregister(this, route);
1923 }
1924 },
1925 {
1926 key: "registerTabRoute",
1927 value: function registerTabRoute(tab) {
1928 var _this2 = this;
1929 this.registerRoute(tab, function(args) {
1930 return _this2.activateTab(tab, args);
1931 });
1932 }
1933 },
1934 {
1935 key: "dependency",
1936 value: function dependency() {
1937 return true;
1938 }
1939 },
1940 {
1941 key: "open",
1942 value: function open() {
1943 return true;
1944 }
1945 },
1946 {
1947 key: "close",
1948 value: function close() {
1949 if (!this.isOpen) return false;
1950 this.isOpen = false;
1951 this.inactivate();
1952 $e.routes.clearCurrent(this.getNamespace());
1953 $e.routes.clearHistory(this.getServiceName());
1954 return true;
1955 }
1956 },
1957 {
1958 key: "activate",
1959 value: function activate() {
1960 $e.components.activate(this.getNamespace());
1961 }
1962 },
1963 {
1964 key: "inactivate",
1965 value: function inactivate() {
1966 $e.components.inactivate(this.getNamespace());
1967 }
1968 },
1969 {
1970 key: "isActive",
1971 value: function isActive() {
1972 return $e.components.isActive(this.getNamespace());
1973 }
1974 },
1975 {
1976 key: "onRoute",
1977 value: function onRoute(route) {
1978 this.toggleRouteClass(route, true);
1979 this.toggleHistoryClass();
1980 this.activate();
1981 this.trigger("route/open", route);
1982 }
1983 },
1984 {
1985 key: "onCloseRoute",
1986 value: function onCloseRoute(route) {
1987 this.toggleRouteClass(route, false);
1988 this.inactivate();
1989 this.trigger("route/close", route);
1990 }
1991 },
1992 {
1993 key: "setDefaultRoute",
1994 value: function setDefaultRoute(route) {
1995 this.defaultRoute = this.getNamespace() + "/" + route;
1996 }
1997 },
1998 {
1999 key: "getDefaultRoute",
2000 value: function getDefaultRoute() {
2001 return this.defaultRoute;
2002 }
2003 },
2004 {
2005 key: "removeTab",
2006 value: function removeTab(tab) {
2007 delete this.tabs[tab];
2008 this.unregisterRoute(tab);
2009 }
2010 },
2011 {
2012 key: "hasTab",
2013 value: function hasTab(tab) {
2014 return !!this.tabs[tab];
2015 }
2016 },
2017 {
2018 key: "addTab",
2019 value: function addTab(tab, args, position) {
2020 var _this3 = this;
2021 this.tabs[tab] = args;
2022 if ("undefined" !== typeof position) {
2023 var newTabs = {};
2024 var ids = Object.keys(this.tabs);
2025 ids.pop();
2026 ids.splice(position, 0, tab);
2027 ids.forEach(function(id) {
2028 newTabs[id] = _this3.tabs[id];
2029 });
2030 this.tabs = newTabs;
2031 }
2032 this.registerTabRoute(tab);
2033 }
2034 },
2035 {
2036 key: "getTabsWrapperSelector",
2037 value: function getTabsWrapperSelector() {
2038 return "";
2039 }
2040 },
2041 {
2042 key: "getTabRoute",
2043 value: function getTabRoute(tab) {
2044 return this.getNamespace() + "/" + tab;
2045 }
2046 },
2047 {
2048 key: "renderTab",
2049 value: function renderTab(tab) {}
2050 },
2051 {
2052 key: "activateTab",
2053 value: function activateTab(tab, args) {
2054 var _this4 = this;
2055 this.renderTab(tab, args);
2056 jQuery(this.getTabsWrapperSelector() + " .elementor-component-tab").off("click").on("click", function(event) {
2057 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
2058 }).removeClass("elementor-active").filter("[data-tab=\"" + tab + "\"]").addClass("elementor-active");
2059 }
2060 },
2061 {
2062 key: "getActiveTabConfig",
2063 value: function getActiveTabConfig() {
2064 return this.tabs[this.currentTab] || {};
2065 }
2066 },
2067 {
2068 key: "getBodyClass",
2069 value: function getBodyClass(route) {
2070 return "e-route-" + route.replace(/\//g, "-");
2071 }
2072 },
2073 {
2074 key: "normalizeCommandName",
2075 value: function normalizeCommandName(commandName) {
2076 return commandName.replace(/[A-Z]/g, function(match, offset) {
2077 return (offset > 0 ? "-" : "") + match.toLowerCase();
2078 });
2079 }
2080 },
2081 {
2082 key: "importCommands",
2083 value: function importCommands(commandsFromImport) {
2084 var _this5 = this;
2085 var commands = {};
2086 Object.entries(commandsFromImport).forEach(function(_ref1) {
2087 var _ref10 = _slicedToArray(_ref1, 2);
2088 var className = _ref10[0];
2089 var Class = _ref10[1];
2090 var command = _this5.normalizeCommandName(className);
2091 commands[command] = Class;
2092 });
2093 return commands;
2094 }
2095 },
2096 {
2097 key: "importHooks",
2098 value: function importHooks(hooksFromImport) {
2099 var hooks = {};
2100 for (var key in hooksFromImport) {
2101 var hook = new hooksFromImport[key]();
2102 hooks[hook.getId()] = hook;
2103 }
2104 return hooks;
2105 }
2106 },
2107 {
2108 key: "importUiStates",
2109 value: function importUiStates(statesFromImport) {
2110 var _this6 = this;
2111 var uiStates = {};
2112 Object.values(statesFromImport).forEach(function(className) {
2113 var uiState = new className(_this6);
2114 uiStates[uiState.getId()] = uiState;
2115 });
2116 return uiStates;
2117 }
2118 },
2119 {
2120 key: "setUiState",
2121 value: function setUiState(state, value) {
2122 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
2123 }
2124 },
2125 {
2126 key: "toggleRouteClass",
2127 value: function toggleRouteClass(route, state) {
2128 document.body.classList.toggle(this.getBodyClass(route), state);
2129 }
2130 },
2131 {
2132 key: "toggleHistoryClass",
2133 value: function toggleHistoryClass() {
2134 document.body.classList.toggle("e-routes-has-history", !!$e.routes.getHistory(this.getServiceName()).length);
2135 }
2136 }
2137 ]);
2138 }(import_module.default);
2139
2140 //#endregion
2141 //#region modules/web-cli/assets/js/modules/commands/close.js
2142 function _callSuper$26(t, o, e) {
2143 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$26() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2144 }
2145 __name(_callSuper$26, "_callSuper");
2146 function _isNativeReflectConstruct$26() {
2147 try {
2148 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2149 } catch (t) {}
2150 return (_isNativeReflectConstruct$26 = function _isNativeReflectConstruct() {
2151 return !!t;
2152 })();
2153 }
2154 __name(_isNativeReflectConstruct$26, "_isNativeReflectConstruct");
2155 var Close = /*#__PURE__*/ function(_CommandBase) {
2156 function Close() {
2157 _classCallCheck(this, Close);
2158 return _callSuper$26(this, Close, arguments);
2159 }
2160 _inherits$1(Close, _CommandBase);
2161 return _createClass(Close, [{
2162 key: "apply",
2163 value: function apply() {
2164 this.component.close();
2165 }
2166 }]);
2167 }(CommandBase);
2168
2169 //#endregion
2170 //#region modules/web-cli/assets/js/modules/commands/open.js
2171 function _callSuper$25(t, o, e) {
2172 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$25() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2173 }
2174 __name(_callSuper$25, "_callSuper");
2175 function _isNativeReflectConstruct$25() {
2176 try {
2177 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2178 } catch (t) {}
2179 return (_isNativeReflectConstruct$25 = function _isNativeReflectConstruct() {
2180 return !!t;
2181 })();
2182 }
2183 __name(_isNativeReflectConstruct$25, "_isNativeReflectConstruct");
2184 var Open = /*#__PURE__*/ function(_CommandBase) {
2185 function Open() {
2186 _classCallCheck(this, Open);
2187 return _callSuper$25(this, Open, arguments);
2188 }
2189 _inherits$1(Open, _CommandBase);
2190 return _createClass(Open, [{
2191 key: "apply",
2192 value: function apply() {
2193 $e.route(this.component.getNamespace());
2194 }
2195 }]);
2196 }(CommandBase);
2197
2198 //#endregion
2199 //#region modules/web-cli/assets/js/modules/commands/toggle.js
2200 function _callSuper$24(t, o, e) {
2201 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$24() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2202 }
2203 __name(_callSuper$24, "_callSuper");
2204 function _isNativeReflectConstruct$24() {
2205 try {
2206 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2207 } catch (t) {}
2208 return (_isNativeReflectConstruct$24 = function _isNativeReflectConstruct() {
2209 return !!t;
2210 })();
2211 }
2212 __name(_isNativeReflectConstruct$24, "_isNativeReflectConstruct");
2213 var Toggle = /*#__PURE__*/ function(_CommandBase) {
2214 function Toggle() {
2215 _classCallCheck(this, Toggle);
2216 return _callSuper$24(this, Toggle, arguments);
2217 }
2218 _inherits$1(Toggle, _CommandBase);
2219 return _createClass(Toggle, [{
2220 key: "apply",
2221 value: function apply() {
2222 if (this.component.isOpen) this.component.close();
2223 else $e.route(this.component.getNamespace());
2224 }
2225 }]);
2226 }(CommandBase);
2227
2228 //#endregion
2229 //#region modules/web-cli/assets/js/modules/commands/index.js
2230 var commands_exports$1 = /* @__PURE__ */ __exportAll({
2231 Close: () => Close,
2232 Open: () => Open,
2233 Toggle: () => Toggle
2234 });
2235
2236 //#endregion
2237 //#region modules/web-cli/assets/js/modules/component-modal-base.js
2238 function _callSuper$23(t, o, e) {
2239 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$23() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2240 }
2241 __name(_callSuper$23, "_callSuper");
2242 function _isNativeReflectConstruct$23() {
2243 try {
2244 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2245 } catch (t) {}
2246 return (_isNativeReflectConstruct$23 = function _isNativeReflectConstruct() {
2247 return !!t;
2248 })();
2249 }
2250 __name(_isNativeReflectConstruct$23, "_isNativeReflectConstruct");
2251 function _superPropGet$6(t, o, e, r) {
2252 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
2253 return 2 & r && "function" == typeof p ? function(t) {
2254 return p.apply(e, t);
2255 } : p;
2256 }
2257 __name(_superPropGet$6, "_superPropGet");
2258 var ComponentModalBase = /*#__PURE__*/ function(_ComponentBase) {
2259 function ComponentModalBase() {
2260 _classCallCheck(this, ComponentModalBase);
2261 return _callSuper$23(this, ComponentModalBase, arguments);
2262 }
2263 _inherits$1(ComponentModalBase, _ComponentBase);
2264 return _createClass(ComponentModalBase, [
2265 {
2266 key: "registerAPI",
2267 value: function registerAPI() {
2268 var _this = this;
2269 _superPropGet$6(ComponentModalBase, "registerAPI", this, 3)([]);
2270 $e.shortcuts.register("esc", {
2271 scopes: [this.getNamespace()],
2272 callback: function callback() {
2273 return _this.close();
2274 }
2275 });
2276 }
2277 },
2278 {
2279 key: "defaultCommands",
2280 value: function defaultCommands() {
2281 return this.importCommands(commands_exports$1);
2282 }
2283 },
2284 {
2285 key: "defaultRoutes",
2286 value: function defaultRoutes() {
2287 return { "": function _() {} };
2288 }
2289 },
2290 {
2291 key: "open",
2292 value: function open() {
2293 var _this2 = this;
2294 if (!this.layout) {
2295 var layout = this.getModalLayout();
2296 this.layout = new layout({ component: this });
2297 this.layout.getModal().on("hide", function() {
2298 return _this2.close();
2299 });
2300 }
2301 this.layout.showModal();
2302 return true;
2303 }
2304 },
2305 {
2306 key: "close",
2307 value: function close() {
2308 if (!_superPropGet$6(ComponentModalBase, "close", this, 3)([])) return false;
2309 elementor.hooks.applyFilters("component/modal/close", this.layout.getModal().hide.bind(this.layout.getModal()), this)();
2310 return true;
2311 }
2312 },
2313 {
2314 key: "getModalLayout",
2315 value: function getModalLayout() {
2316 force_method_implementation_default();
2317 }
2318 }
2319 ]);
2320 }(ComponentBase);
2321
2322 //#endregion
2323 //#region assets/dev/js/editor/utils/editor-one-events.js
2324 init_defineProperty();
2325 function ownKeys$3(e, r) {
2326 var t = Object.keys(e);
2327 if (Object.getOwnPropertySymbols) {
2328 var o = Object.getOwnPropertySymbols(e);
2329 r && (o = o.filter(function(r) {
2330 return Object.getOwnPropertyDescriptor(e, r).enumerable;
2331 })), t.push.apply(t, o);
2332 }
2333 return t;
2334 }
2335 __name(ownKeys$3, "ownKeys");
2336 function _objectSpread$3(e) {
2337 for (var r = 1; r < arguments.length; r++) {
2338 var t = null != arguments[r] ? arguments[r] : {};
2339 r % 2 ? ownKeys$3(Object(t), !0).forEach(function(r) {
2340 _defineProperty(e, r, t[r]);
2341 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r) {
2342 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
2343 });
2344 }
2345 return e;
2346 }
2347 __name(_objectSpread$3, "_objectSpread");
2348 var EditorOneEventManager = /*#__PURE__*/ function() {
2349 function EditorOneEventManager() {
2350 _classCallCheck(this, EditorOneEventManager);
2351 }
2352 return _createClass(EditorOneEventManager, null, [
2353 {
2354 key: "getEventsManager",
2355 value: function getEventsManager() {
2356 var _elementorCommon;
2357 return (_elementorCommon = elementorCommon) === null || _elementorCommon === void 0 ? void 0 : _elementorCommon.eventsManager;
2358 }
2359 },
2360 {
2361 key: "getConfig",
2362 value: function getConfig() {
2363 var _this$getEventsManage;
2364 return (_this$getEventsManage = this.getEventsManager()) === null || _this$getEventsManage === void 0 ? void 0 : _this$getEventsManage.config;
2365 }
2366 },
2367 {
2368 key: "canSendEvents",
2369 value: function canSendEvents() {
2370 var _elementorCommon2;
2371 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;
2372 }
2373 },
2374 {
2375 key: "isEventsManagerAvailable",
2376 value: function isEventsManagerAvailable() {
2377 var eventsManager = this.getEventsManager();
2378 return eventsManager && "function" === typeof eventsManager.dispatchEvent;
2379 }
2380 },
2381 {
2382 key: "dispatchEvent",
2383 value: function dispatchEvent(eventName, payload) {
2384 try {
2385 if (!this.isEventsManagerAvailable() || !this.canSendEvents()) return false;
2386 this.getEventsManager().dispatchEvent(eventName, payload);
2387 return true;
2388 } catch (error) {
2389 return false;
2390 }
2391 }
2392 },
2393 {
2394 key: "toLowerSnake",
2395 value: function toLowerSnake(value) {
2396 if (!value || "string" !== typeof value) return value;
2397 return value.replace(/\s+/g, "_").toLowerCase();
2398 }
2399 },
2400 {
2401 key: "decodeHtmlEntities",
2402 value: function decodeHtmlEntities(text) {
2403 if (!text || "string" !== typeof text) return text;
2404 return new DOMParser().parseFromString(text, "text/html").body.textContent || text;
2405 }
2406 },
2407 {
2408 key: "isInEditorContext",
2409 value: function isInEditorContext() {
2410 var _window$elementor;
2411 return "undefined" !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
2412 }
2413 },
2414 {
2415 key: "getFinderContext",
2416 value: function getFinderContext() {
2417 var _config$appTypes;
2418 var _config$appTypes2;
2419 var _config$locations;
2420 var _config$locations2;
2421 var config = this.getConfig();
2422 var isEditor = this.isInEditorContext();
2423 return {
2424 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,
2425 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)
2426 };
2427 }
2428 },
2429 {
2430 key: "createBasePayload",
2431 value: function createBasePayload() {
2432 var _config$appTypes$edit;
2433 var _config$appTypes3;
2434 var overrides = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2435 var config = this.getConfig();
2436 return _objectSpread$3({ window_name: (_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" }, overrides);
2437 }
2438 },
2439 {
2440 key: "sendTopBarPublishDropdown",
2441 value: function sendTopBarPublishDropdown(targetName) {
2442 var _config$names;
2443 var _config$triggers;
2444 var _config$targetTypes;
2445 var _config$interactionRe;
2446 var _config$locations3;
2447 var _config$secondaryLoca;
2448 var _config$targetTypes2;
2449 var config = this.getConfig();
2450 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({
2451 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
2452 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
2453 target_name: targetName,
2454 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
2455 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
2456 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
2457 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
2458 interaction_description: "User selected an action from the publish dropdown"
2459 }));
2460 }
2461 },
2462 {
2463 key: "sendTopBarPageList",
2464 value: function sendTopBarPageList(targetName) {
2465 var _config$names2;
2466 var _config$triggers2;
2467 var _config$targetTypes3;
2468 var _config$interactionRe2;
2469 var _config$interactionRe3;
2470 var _config$locations4;
2471 var _config$secondaryLoca2;
2472 var _config$targetTypes4;
2473 var isCreate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2474 var config = this.getConfig();
2475 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({
2476 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
2477 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
2478 target_name: targetName,
2479 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,
2480 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
2481 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
2482 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
2483 interaction_description: "User selected an action from the page list dropdown"
2484 }));
2485 }
2486 },
2487 {
2488 key: "sendSiteSettingsSession",
2489 value: function sendSiteSettingsSession(_ref) {
2490 var _config$names3;
2491 var _config$triggers3;
2492 var _config$interactionRe4;
2493 var _config$locations5;
2494 var _config$secondaryLoca3;
2495 var targetType = _ref.targetType;
2496 var _ref$visitedItems = _ref.visitedItems;
2497 var visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems;
2498 var _ref$savedItems = _ref.savedItems;
2499 var savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems;
2500 var state = _ref.state;
2501 var config = this.getConfig();
2502 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({
2503 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
2504 target_type: targetType,
2505 target_name: "site_settings",
2506 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
2507 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
2508 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
2509 interaction_description: "Records areas visited as part of the site setting session",
2510 metadata: {
2511 visited_items: visitedItems,
2512 saved_items: savedItems
2513 },
2514 state
2515 }));
2516 }
2517 },
2518 {
2519 key: "sendELibraryNav",
2520 value: function sendELibraryNav(tabName) {
2521 var _config$names4;
2522 var _config$triggers4;
2523 var _config$targetTypes5;
2524 var _config$interactionRe5;
2525 var _config$locations6;
2526 var _config$secondaryLoca4;
2527 var config = this.getConfig();
2528 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({
2529 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
2530 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
2531 target_name: this.toLowerSnake(tabName),
2532 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
2533 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
2534 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
2535 interaction_description: "User navigates within elementor library"
2536 }));
2537 }
2538 },
2539 {
2540 key: "sendELibraryInsert",
2541 value: function sendELibraryInsert(_ref2) {
2542 var _config$triggers5;
2543 var _config$targetTypes6;
2544 var _config$interactionRe6;
2545 var _config$locations7;
2546 var _config$secondaryLoca5;
2547 var _config$names5;
2548 var assetId = _ref2.assetId;
2549 var assetName = _ref2.assetName;
2550 var libraryType = _ref2.libraryType;
2551 var _ref2$proRequired = _ref2.proRequired;
2552 var proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
2553 var config = this.getConfig();
2554 var payload = this.createBasePayload({
2555 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
2556 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
2557 target_name: String(assetId),
2558 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
2559 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
2560 location_l1: this.toLowerSnake(libraryType),
2561 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
2562 interaction_description: "User inserts block/pages from elementor library",
2563 metadata: {
2564 template_id: String(assetId),
2565 template_name: this.decodeHtmlEntities(assetName) || ""
2566 }
2567 });
2568 if (proRequired) payload.state = "pro_plan_required";
2569 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);
2570 }
2571 },
2572 {
2573 key: "sendELibraryFavorite",
2574 value: function sendELibraryFavorite(_ref3) {
2575 var _config$triggers6;
2576 var _config$targetTypes7;
2577 var _config$interactionRe7;
2578 var _config$locations8;
2579 var _config$secondaryLoca6;
2580 var _config$names6;
2581 var assetId = _ref3.assetId;
2582 var assetName = _ref3.assetName;
2583 var libraryType = _ref3.libraryType;
2584 var isFavorite = _ref3.isFavorite;
2585 var _ref3$proRequired = _ref3.proRequired;
2586 var proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
2587 var config = this.getConfig();
2588 var payload = this.createBasePayload({
2589 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
2590 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
2591 target_name: String(assetId),
2592 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
2593 target_value: Boolean(isFavorite),
2594 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
2595 location_l1: this.toLowerSnake(libraryType),
2596 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
2597 interaction_description: "User favorite block/pages from elementor library",
2598 metadata: {
2599 template_id: String(assetId),
2600 template_name: this.decodeHtmlEntities(assetName) || ""
2601 }
2602 });
2603 if (proRequired) payload.state = "pro_plan_required";
2604 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);
2605 }
2606 },
2607 {
2608 key: "sendELibraryGenerateAi",
2609 value: function sendELibraryGenerateAi(_ref4) {
2610 var _config$names7;
2611 var _config$triggers7;
2612 var _config$targetTypes8;
2613 var _config$interactionRe8;
2614 var _config$locations9;
2615 var _config$secondaryLoca7;
2616 var assetId = _ref4.assetId;
2617 var assetName = _ref4.assetName;
2618 var libraryType = _ref4.libraryType;
2619 var config = this.getConfig();
2620 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({
2621 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
2622 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
2623 target_name: String(assetId),
2624 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
2625 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
2626 location_l1: this.toLowerSnake(libraryType),
2627 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
2628 interaction_description: "User generated block/page based on a library asset",
2629 metadata: {
2630 template_id: String(assetId),
2631 template_name: this.decodeHtmlEntities(assetName) || ""
2632 }
2633 }));
2634 }
2635 },
2636 {
2637 key: "sendFinderSearchInput",
2638 value: function sendFinderSearchInput(_ref5) {
2639 var _config$triggers8;
2640 var _config$targetTypes9;
2641 var _config$interactionRe9;
2642 var _config$interactionRe0;
2643 var _config$secondaryLoca8;
2644 var _config$names8;
2645 var resultsCount = _ref5.resultsCount;
2646 var _ref5$searchTerm = _ref5.searchTerm;
2647 var searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
2648 var config = this.getConfig();
2649 var hasResults = resultsCount > 0;
2650 var finderContext = this.getFinderContext();
2651 var payload = this.createBasePayload({
2652 window_name: finderContext.windowName,
2653 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
2654 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
2655 target_name: "finder",
2656 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,
2657 target_location: finderContext.targetLocation,
2658 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
2659 interaction_description: "Finder search input, follows debounce behavior",
2660 metadata: { results_count: resultsCount }
2661 });
2662 if (!hasResults && searchTerm) payload.metadata.search_term = searchTerm;
2663 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);
2664 }
2665 },
2666 {
2667 key: "sendFinderResultSelect",
2668 value: function sendFinderResultSelect(choice) {
2669 var _config$names9;
2670 var _config$triggers9;
2671 var _config$targetTypes0;
2672 var _config$interactionRe1;
2673 var _config$secondaryLoca9;
2674 var _config$secondaryLoca0;
2675 var config = this.getConfig();
2676 var finderContext = this.getFinderContext();
2677 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({
2678 window_name: finderContext.windowName,
2679 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
2680 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
2681 target_name: choice,
2682 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
2683 target_location: finderContext.targetLocation,
2684 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
2685 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
2686 interaction_description: "Finder search results was selected"
2687 }));
2688 }
2689 },
2690 {
2691 key: "sendCanvasEmptyBoxAction",
2692 value: function sendCanvasEmptyBoxAction(_ref6) {
2693 var _config$triggers0;
2694 var _config$targetTypes1;
2695 var _config$interactionRe10;
2696 var _config$locations0;
2697 var _config$secondaryLoca1;
2698 var _config$names0;
2699 var targetName = _ref6.targetName;
2700 var _ref6$metadata = _ref6.metadata;
2701 var metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata;
2702 var _ref6$containerCreate = _ref6.containerCreated;
2703 var containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
2704 var config = this.getConfig();
2705 var payload = this.createBasePayload({
2706 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
2707 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
2708 target_name: targetName,
2709 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
2710 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
2711 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
2712 interaction_description: "Empty box on canvas actions"
2713 });
2714 if (Object.keys(metadata).length > 0) payload.metadata = metadata;
2715 if (containerCreated !== null) payload.state = containerCreated;
2716 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);
2717 }
2718 },
2719 {
2720 key: "sendWidgetPanelSearch",
2721 value: function sendWidgetPanelSearch(_ref7) {
2722 var _config$triggers1;
2723 var _config$targetTypes10;
2724 var _config$interactionRe11;
2725 var _config$interactionRe12;
2726 var _config$locations1;
2727 var _config$locations10;
2728 var _config$secondaryLoca10;
2729 var _config$names1;
2730 var resultsCount = _ref7.resultsCount;
2731 var _ref7$userInput = _ref7.userInput;
2732 var userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
2733 var config = this.getConfig();
2734 var hasResults = resultsCount > 0;
2735 var payload = this.createBasePayload({
2736 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
2737 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
2738 target_name: "search_widget",
2739 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,
2740 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
2741 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
2742 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
2743 interaction_description: "Widget search input, follows debounce behavior"
2744 });
2745 if (!hasResults && userInput) payload.metadata = { user_input: userInput };
2746 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);
2747 }
2748 },
2749 {
2750 key: "createWpDashPayload",
2751 value: function createWpDashPayload() {
2752 var _config$appTypes$wpDa;
2753 var _config$appTypes4;
2754 var _config$locations11;
2755 var overrides = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
2756 var config = this.getConfig();
2757 return this.createBasePayload(_objectSpread$3({
2758 window_name: (_config$appTypes$wpDa = config === null || config === void 0 || (_config$appTypes4 = config.appTypes) === null || _config$appTypes4 === void 0 ? void 0 : _config$appTypes4.wpDash) !== null && _config$appTypes$wpDa !== void 0 ? _config$appTypes$wpDa : "wpdash",
2759 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations11 = config.locations) === null || _config$locations11 === void 0 ? void 0 : _config$locations11.wpDashAdmin),
2760 location_l2: ""
2761 }, overrides));
2762 }
2763 },
2764 {
2765 key: "sendWpDashElementorMenuClick",
2766 value: function sendWpDashElementorMenuClick() {
2767 var _config$names10;
2768 var _config$triggers10;
2769 var _config$targetTypes11;
2770 var _config$interactionRe13;
2771 var _config$secondaryLoca11;
2772 var config = this.getConfig();
2773 return this.dispatchEvent(config === null || config === void 0 || (_config$names10 = config.names) === null || _config$names10 === void 0 || (_config$names10 = _config$names10.editorOne) === null || _config$names10 === void 0 ? void 0 : _config$names10.wpDashElementorMenuClick, this.createWpDashPayload({
2774 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers10 = config.triggers) === null || _config$triggers10 === void 0 ? void 0 : _config$triggers10.click),
2775 target_type: config === null || config === void 0 || (_config$targetTypes11 = config.targetTypes) === null || _config$targetTypes11 === void 0 ? void 0 : _config$targetTypes11.wpDashAdminMenuItem,
2776 target_name: "elementor_menu_item",
2777 interaction_result: config === null || config === void 0 || (_config$interactionRe13 = config.interactionResults) === null || _config$interactionRe13 === void 0 ? void 0 : _config$interactionRe13.elementorSideMenuOpened,
2778 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca11 = config.secondaryLocations) === null || _config$secondaryLoca11 === void 0 ? void 0 : _config$secondaryLoca11.wpDashElementorCoreMenu),
2779 interaction_description: "core_user_clicked_elementor_menu_item"
2780 }));
2781 }
2782 },
2783 {
2784 key: "sendWpDashEditorSubMenuHover",
2785 value: function sendWpDashEditorSubMenuHover() {
2786 var _config$names11;
2787 var _config$triggers11;
2788 var _config$targetTypes12;
2789 var _config$interactionRe14;
2790 var _config$secondaryLoca12;
2791 var config = this.getConfig();
2792 return this.dispatchEvent(config === null || config === void 0 || (_config$names11 = config.names) === null || _config$names11 === void 0 || (_config$names11 = _config$names11.editorOne) === null || _config$names11 === void 0 ? void 0 : _config$names11.wpDashEditorSubMenuHover, this.createWpDashPayload({
2793 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers11 = config.triggers) === null || _config$triggers11 === void 0 ? void 0 : _config$triggers11.hover),
2794 target_type: config === null || config === void 0 || (_config$targetTypes12 = config.targetTypes) === null || _config$targetTypes12 === void 0 ? void 0 : _config$targetTypes12.wpDashEditorMenu,
2795 target_name: "wpdash_editor_sub_menu",
2796 interaction_result: config === null || config === void 0 || (_config$interactionRe14 = config.interactionResults) === null || _config$interactionRe14 === void 0 ? void 0 : _config$interactionRe14.editorSubMenuOpened,
2797 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca12 = config.secondaryLocations) === null || _config$secondaryLoca12 === void 0 ? void 0 : _config$secondaryLoca12.wpDashElementorCoreSubMenu),
2798 interaction_description: "core_user_hovered_sub_menu"
2799 }));
2800 }
2801 },
2802 {
2803 key: "sendWpDashThemeBuilderClick",
2804 value: function sendWpDashThemeBuilderClick() {
2805 var _config$names12;
2806 var _config$triggers12;
2807 var _config$targetTypes13;
2808 var _config$interactionRe15;
2809 var _config$secondaryLoca13;
2810 var config = this.getConfig();
2811 return this.dispatchEvent(config === null || config === void 0 || (_config$names12 = config.names) === null || _config$names12 === void 0 || (_config$names12 = _config$names12.editorOne) === null || _config$names12 === void 0 ? void 0 : _config$names12.wpDashThemeBuilderClick, this.createWpDashPayload({
2812 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers12 = config.triggers) === null || _config$triggers12 === void 0 ? void 0 : _config$triggers12.click),
2813 target_type: config === null || config === void 0 || (_config$targetTypes13 = config.targetTypes) === null || _config$targetTypes13 === void 0 ? void 0 : _config$targetTypes13.wpDashSubMenuItem,
2814 target_name: "theme_builder_menu_item",
2815 interaction_result: config === null || config === void 0 || (_config$interactionRe15 = config.interactionResults) === null || _config$interactionRe15 === void 0 ? void 0 : _config$interactionRe15.themeBuilderPromotionWindow,
2816 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca13 = config.secondaryLocations) === null || _config$secondaryLoca13 === void 0 ? void 0 : _config$secondaryLoca13.wpDashThemeBuilder),
2817 interaction_description: "core_user_clicked_theme_builder_menu_item"
2818 }));
2819 }
2820 },
2821 {
2822 key: "sendSidebarMenuItemClicked",
2823 value: function sendSidebarMenuItemClicked(_ref8) {
2824 var eventId = _ref8.eventId;
2825 var groupEventId = _ref8.groupEventId;
2826 try {
2827 var _config$windowNames;
2828 var _config$triggers13;
2829 var _config$targetTypes14;
2830 var _config$interactionRe16;
2831 var _config$locations12;
2832 var _config$names13;
2833 var config = this.getConfig();
2834 var payload = this.createBasePayload({
2835 window_name: config === null || config === void 0 || (_config$windowNames = config.windowNames) === null || _config$windowNames === void 0 ? void 0 : _config$windowNames.sidebarMenu,
2836 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers13 = config.triggers) === null || _config$triggers13 === void 0 ? void 0 : _config$triggers13.click),
2837 target_type: config === null || config === void 0 || (_config$targetTypes14 = config.targetTypes) === null || _config$targetTypes14 === void 0 ? void 0 : _config$targetTypes14.link,
2838 target_name: eventId,
2839 interaction_result: config === null || config === void 0 || (_config$interactionRe16 = config.interactionResults) === null || _config$interactionRe16 === void 0 ? void 0 : _config$interactionRe16.pageOpened,
2840 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations12 = config.locations) === null || _config$locations12 === void 0 ? void 0 : _config$locations12.sidebar)
2841 });
2842 if (groupEventId) payload.location_l1 = groupEventId;
2843 return this.dispatchEvent(config === null || config === void 0 || (_config$names13 = config.names) === null || _config$names13 === void 0 || (_config$names13 = _config$names13.editorOne) === null || _config$names13 === void 0 ? void 0 : _config$names13.sidebarMenuItemClicked, payload);
2844 } catch (error) {
2845 return false;
2846 }
2847 }
2848 },
2849 {
2850 key: "sendSidebarMenuGroupToggled",
2851 value: function sendSidebarMenuGroupToggled(_ref9) {
2852 var eventId = _ref9.eventId;
2853 var isExpanded = _ref9.isExpanded;
2854 try {
2855 var _config$interactionRe17;
2856 var _config$interactionRe18;
2857 var _config$names14;
2858 var _config$windowNames2;
2859 var _config$triggers14;
2860 var _config$targetTypes15;
2861 var _config$locations13;
2862 var config = this.getConfig();
2863 var interactionResult = isExpanded ? config === null || config === void 0 || (_config$interactionRe17 = config.interactionResults) === null || _config$interactionRe17 === void 0 ? void 0 : _config$interactionRe17.expanded : config === null || config === void 0 || (_config$interactionRe18 = config.interactionResults) === null || _config$interactionRe18 === void 0 ? void 0 : _config$interactionRe18.collapsed;
2864 return this.dispatchEvent(config === null || config === void 0 || (_config$names14 = config.names) === null || _config$names14 === void 0 || (_config$names14 = _config$names14.editorOne) === null || _config$names14 === void 0 ? void 0 : _config$names14.sidebarMenuGroupToggled, this.createBasePayload({
2865 window_name: config === null || config === void 0 || (_config$windowNames2 = config.windowNames) === null || _config$windowNames2 === void 0 ? void 0 : _config$windowNames2.sidebarMenu,
2866 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers14 = config.triggers) === null || _config$triggers14 === void 0 ? void 0 : _config$triggers14.click),
2867 target_type: config === null || config === void 0 || (_config$targetTypes15 = config.targetTypes) === null || _config$targetTypes15 === void 0 ? void 0 : _config$targetTypes15.toggle,
2868 target_name: eventId,
2869 interaction_result: interactionResult,
2870 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations13 = config.locations) === null || _config$locations13 === void 0 ? void 0 : _config$locations13.sidebar)
2871 }));
2872 } catch (error) {
2873 return false;
2874 }
2875 }
2876 }
2877 ]);
2878 }();
2879 var createDebouncedFinderSearch = function createDebouncedFinderSearch() {
2880 var delay = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 300;
2881 return _.debounce(function(resultsCount, searchTerm) {
2882 EditorOneEventManager.sendFinderSearchInput({
2883 resultsCount,
2884 searchTerm
2885 });
2886 }, delay);
2887 };
2888
2889 //#endregion
2890 //#region core/common/modules/finder/assets/js/modal/views/item.js
2891 function _callSuper$22(t, o, e) {
2892 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$22() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2893 }
2894 __name(_callSuper$22, "_callSuper");
2895 function _isNativeReflectConstruct$22() {
2896 try {
2897 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2898 } catch (t) {}
2899 return (_isNativeReflectConstruct$22 = function _isNativeReflectConstruct() {
2900 return !!t;
2901 })();
2902 }
2903 __name(_isNativeReflectConstruct$22, "_isNativeReflectConstruct");
2904 var _default$9 = /*#__PURE__*/ function(_Marionette$ItemView) {
2905 function _default() {
2906 _classCallCheck(this, _default);
2907 return _callSuper$22(this, _default, arguments);
2908 }
2909 _inherits$1(_default, _Marionette$ItemView);
2910 return _createClass(_default, [
2911 {
2912 key: "className",
2913 value: function className() {
2914 return "elementor-finder__results__item";
2915 }
2916 },
2917 {
2918 key: "getTemplate",
2919 value: function getTemplate() {
2920 return "#tmpl-elementor-finder__results__item";
2921 }
2922 },
2923 {
2924 key: "events",
2925 value: function events() {
2926 this.$el[0].addEventListener("click", this.onClick.bind(this), true);
2927 }
2928 },
2929 {
2930 key: "trackResultSelect",
2931 value: function trackResultSelect() {
2932 var title = this.model.get("title");
2933 EditorOneEventManager.sendFinderResultSelect(title);
2934 }
2935 },
2936 {
2937 key: "onClick",
2938 value: function onClick(e) {
2939 var _this = this;
2940 var lockOptions = this.model.get("lock");
2941 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
2942 this.trackResultSelect();
2943 var url = this.model.get("url") || "";
2944 if (url.includes("page=elementor-app") && window.$e) {
2945 e.preventDefault();
2946 e.stopImmediatePropagation();
2947 $e.run("finder/close");
2948 $e.run("app/open", { url });
2949 }
2950 return;
2951 }
2952 e.preventDefault();
2953 e.stopImmediatePropagation();
2954 elementorCommon.dialogsManager.createWidget("confirm", {
2955 id: "elementor-finder__lock-dialog",
2956 headerMessage: lockOptions.content.heading,
2957 message: lockOptions.content.description,
2958 position: {
2959 my: "center center",
2960 at: "center center"
2961 },
2962 strings: {
2963 confirm: lockOptions.button.text,
2964 cancel: (0, _wordpress_i18n.__)("Cancel", "elementor")
2965 },
2966 onConfirm: function onConfirm() {
2967 _this.trackResultSelect();
2968 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
2969 window.open(link, "_blank");
2970 }
2971 }).show();
2972 }
2973 },
2974 {
2975 key: "replaceLockLinkPlaceholders",
2976 value: function replaceLockLinkPlaceholders(link) {
2977 return link.replace(/%%utm_source%%/g, "finder").replace(/%%utm_medium%%/g, "wp-dash");
2978 }
2979 }
2980 ]);
2981 }(Marionette.ItemView);
2982
2983 //#endregion
2984 //#region core/common/modules/finder/assets/js/modal/model/item.js
2985 function _callSuper$21(t, o, e) {
2986 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$21() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
2987 }
2988 __name(_callSuper$21, "_callSuper");
2989 function _isNativeReflectConstruct$21() {
2990 try {
2991 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
2992 } catch (t) {}
2993 return (_isNativeReflectConstruct$21 = function _isNativeReflectConstruct() {
2994 return !!t;
2995 })();
2996 }
2997 __name(_isNativeReflectConstruct$21, "_isNativeReflectConstruct");
2998 var _default$8 = /*#__PURE__*/ function(_Backbone$Model) {
2999 function _default() {
3000 _classCallCheck(this, _default);
3001 return _callSuper$21(this, _default, arguments);
3002 }
3003 _inherits$1(_default, _Backbone$Model);
3004 return _createClass(_default, [{
3005 key: "defaults",
3006 value: function defaults() {
3007 return {
3008 description: "",
3009 icon: "settings",
3010 url: "",
3011 keywords: [],
3012 actions: [],
3013 lock: null
3014 };
3015 }
3016 }]);
3017 }(Backbone.Model);
3018
3019 //#endregion
3020 //#region core/common/modules/finder/assets/js/modal/views/category.js
3021 function _callSuper$20(t, o, e) {
3022 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$20() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3023 }
3024 __name(_callSuper$20, "_callSuper");
3025 function _isNativeReflectConstruct$20() {
3026 try {
3027 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3028 } catch (t) {}
3029 return (_isNativeReflectConstruct$20 = function _isNativeReflectConstruct() {
3030 return !!t;
3031 })();
3032 }
3033 __name(_isNativeReflectConstruct$20, "_isNativeReflectConstruct");
3034 var _default$7 = /*#__PURE__*/ function(_Marionette$Composite) {
3035 function _default() {
3036 _classCallCheck(this, _default);
3037 return _callSuper$20(this, _default, arguments);
3038 }
3039 _inherits$1(_default, _Marionette$Composite);
3040 return _createClass(_default, [
3041 {
3042 key: "className",
3043 value: function className() {
3044 return "elementor-finder__results__category";
3045 }
3046 },
3047 {
3048 key: "getTemplate",
3049 value: function getTemplate() {
3050 return "#tmpl-elementor-finder__results__category";
3051 }
3052 },
3053 {
3054 key: "getChildView",
3055 value: function getChildView() {
3056 return _default$9;
3057 }
3058 },
3059 {
3060 key: "initialize",
3061 value: function initialize() {
3062 this.childViewContainer = ".elementor-finder__results__category__items";
3063 this.isVisible = true;
3064 var items = this.model.get("items");
3065 if (items) items = Object.values(items);
3066 this.collection = new Backbone.Collection(items, { model: _default$8 });
3067 }
3068 },
3069 {
3070 key: "filter",
3071 value: function filter(childModel) {
3072 var textFilter = this.getTextFilter();
3073 if (childModel.get("title").toLowerCase().indexOf(textFilter) >= 0) return true;
3074 return childModel.get("keywords").some(function(keyword) {
3075 return keyword.indexOf(textFilter) >= 0;
3076 });
3077 }
3078 },
3079 {
3080 key: "getTextFilter",
3081 value: function getTextFilter() {
3082 return elementorCommon.finder.channel.request("filter:text").trim().toLowerCase();
3083 }
3084 },
3085 {
3086 key: "toggleElement",
3087 value: function toggleElement() {
3088 var isCurrentlyVisible = !!this.children.length;
3089 if (isCurrentlyVisible !== this.isVisible) {
3090 this.isVisible = isCurrentlyVisible;
3091 this.$el.toggle(isCurrentlyVisible);
3092 this.triggerMethod("toggle:visibility");
3093 }
3094 }
3095 },
3096 {
3097 key: "onRender",
3098 value: function onRender() {
3099 this.listenTo(elementorCommon.finder.channel, "filter:change", this.onFilterChange.bind(this));
3100 }
3101 },
3102 {
3103 key: "onFilterChange",
3104 value: function onFilterChange() {
3105 this._renderChildren();
3106 }
3107 },
3108 {
3109 key: "onRenderCollection",
3110 value: function onRenderCollection() {
3111 this.toggleElement();
3112 }
3113 }
3114 ]);
3115 }(Marionette.CompositeView);
3116
3117 //#endregion
3118 //#region core/common/modules/finder/assets/js/modal/views/dynamic-category.js
3119 function _callSuper$19(t, o, e) {
3120 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$19() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3121 }
3122 __name(_callSuper$19, "_callSuper");
3123 function _isNativeReflectConstruct$19() {
3124 try {
3125 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3126 } catch (t) {}
3127 return (_isNativeReflectConstruct$19 = function _isNativeReflectConstruct() {
3128 return !!t;
3129 })();
3130 }
3131 __name(_isNativeReflectConstruct$19, "_isNativeReflectConstruct");
3132 function _superPropGet$5(t, o, e, r) {
3133 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3134 return 2 & r && "function" == typeof p ? function(t) {
3135 return p.apply(e, t);
3136 } : p;
3137 }
3138 __name(_superPropGet$5, "_superPropGet");
3139 var _default$6 = /*#__PURE__*/ function(_Category) {
3140 function _default() {
3141 _classCallCheck(this, _default);
3142 return _callSuper$19(this, _default, arguments);
3143 }
3144 _inherits$1(_default, _Category);
3145 return _createClass(_default, [
3146 {
3147 key: "className",
3148 value: function className() {
3149 return _superPropGet$5(_default, "className", this, 3)([]) + " elementor-finder__results__category--dynamic";
3150 }
3151 },
3152 {
3153 key: "ui",
3154 value: function ui() {
3155 return { title: ".elementor-finder__results__category__title" };
3156 }
3157 },
3158 {
3159 key: "fetchData",
3160 value: function fetchData() {
3161 var _this = this;
3162 this.ui.loadingIcon.show();
3163 elementorCommon.ajax.addRequest("finder_get_category_items", {
3164 data: {
3165 category: this.model.get("name"),
3166 filter: this.getTextFilter()
3167 },
3168 success: function success(data) {
3169 if (_this.isDestroyed) return;
3170 _this.collection.set(data);
3171 _this.toggleElement();
3172 _this.ui.loadingIcon.hide();
3173 }
3174 });
3175 }
3176 },
3177 {
3178 key: "filter",
3179 value: function filter() {
3180 return true;
3181 }
3182 },
3183 {
3184 key: "onFilterChange",
3185 value: function onFilterChange() {
3186 this.fetchData();
3187 }
3188 },
3189 {
3190 key: "onRender",
3191 value: function onRender() {
3192 _superPropGet$5(_default, "onRender", this, 3)([]);
3193 this.ui.loadingIcon = jQuery("<i>", { class: "eicon-loading eicon-animation-spin" });
3194 this.ui.title.after(this.ui.loadingIcon);
3195 this.fetchData();
3196 }
3197 }
3198 ]);
3199 }(_default$7);
3200
3201 //#endregion
3202 //#region core/common/modules/finder/assets/js/modal/views/categories.js
3203 function _callSuper$18(t, o, e) {
3204 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$18() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3205 }
3206 __name(_callSuper$18, "_callSuper");
3207 function _isNativeReflectConstruct$18() {
3208 try {
3209 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3210 } catch (t) {}
3211 return (_isNativeReflectConstruct$18 = function _isNativeReflectConstruct() {
3212 return !!t;
3213 })();
3214 }
3215 __name(_isNativeReflectConstruct$18, "_isNativeReflectConstruct");
3216 var _default$5 = /*#__PURE__*/ function(_Marionette$Composite) {
3217 function _default() {
3218 _classCallCheck(this, _default);
3219 return _callSuper$18(this, _default, arguments);
3220 }
3221 _inherits$1(_default, _Marionette$Composite);
3222 return _createClass(_default, [
3223 {
3224 key: "id",
3225 value: function id() {
3226 return "elementor-finder__results-container";
3227 }
3228 },
3229 {
3230 key: "ui",
3231 value: function ui() {
3232 this.selectors = {
3233 noResults: "#elementor-finder__no-results",
3234 categoryItem: ".elementor-finder__results__item"
3235 };
3236 return this.selectors;
3237 }
3238 },
3239 {
3240 key: "events",
3241 value: function events() {
3242 return { "mouseenter @ui.categoryItem": "onCategoryItemMouseEnter" };
3243 }
3244 },
3245 {
3246 key: "getTemplate",
3247 value: function getTemplate() {
3248 return "#tmpl-elementor-finder-results-container";
3249 }
3250 },
3251 {
3252 key: "getChildView",
3253 value: function getChildView(childModel) {
3254 return childModel.get("dynamic") ? _default$6 : _default$7;
3255 }
3256 },
3257 {
3258 key: "initialize",
3259 value: function initialize() {
3260 this.$activeItem = null;
3261 this.childViewContainer = "#elementor-finder__results";
3262 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings("data")));
3263 }
3264 },
3265 {
3266 key: "activateItem",
3267 value: function activateItem($item) {
3268 if (this.$activeItem) this.$activeItem.removeClass("elementor-active");
3269 $item.addClass("elementor-active");
3270 this.$activeItem = $item;
3271 }
3272 },
3273 {
3274 key: "activateNextItem",
3275 value: function activateNextItem(reverse) {
3276 var $allItems = jQuery(this.selectors.categoryItem);
3277 var nextItemIndex = 0;
3278 if (this.$activeItem) {
3279 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3280 if (nextItemIndex >= $allItems.length) nextItemIndex = 0;
3281 else if (nextItemIndex < 0) nextItemIndex = $allItems.length - 1;
3282 }
3283 var $nextItem = $allItems.eq(nextItemIndex);
3284 this.activateItem($nextItem);
3285 $nextItem[0].scrollIntoView({ block: "nearest" });
3286 }
3287 },
3288 {
3289 key: "goToActiveItem",
3290 value: function goToActiveItem(event) {
3291 var $a = this.$activeItem.children("a");
3292 var isControlClicked = $e.shortcuts.isControlEvent(event);
3293 if (isControlClicked) $a.attr("target", "_blank");
3294 $a[0].click();
3295 if (isControlClicked) $a.removeAttr("target");
3296 }
3297 },
3298 {
3299 key: "onCategoryItemMouseEnter",
3300 value: function onCategoryItemMouseEnter(event) {
3301 this.activateItem(jQuery(event.currentTarget));
3302 }
3303 },
3304 {
3305 key: "onChildviewToggleVisibility",
3306 value: function onChildviewToggleVisibility() {
3307 var allCategoriesAreEmpty = this.children.every(function(child) {
3308 return !child.isVisible;
3309 });
3310 this.ui.noResults.toggle(allCategoriesAreEmpty);
3311 }
3312 }
3313 ]);
3314 }(Marionette.CompositeView);
3315
3316 //#endregion
3317 //#region core/common/modules/finder/assets/js/modal/views/content.js
3318 function _callSuper$17(t, o, e) {
3319 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$17() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3320 }
3321 __name(_callSuper$17, "_callSuper");
3322 function _isNativeReflectConstruct$17() {
3323 try {
3324 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3325 } catch (t) {}
3326 return (_isNativeReflectConstruct$17 = function _isNativeReflectConstruct() {
3327 return !!t;
3328 })();
3329 }
3330 __name(_isNativeReflectConstruct$17, "_isNativeReflectConstruct");
3331 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3332 var _default$4 = /*#__PURE__*/ function(_Marionette$LayoutVie) {
3333 function _default() {
3334 _classCallCheck(this, _default);
3335 return _callSuper$17(this, _default, arguments);
3336 }
3337 _inherits$1(_default, _Marionette$LayoutVie);
3338 return _createClass(_default, [
3339 {
3340 key: "id",
3341 value: function id() {
3342 return "elementor-finder";
3343 }
3344 },
3345 {
3346 key: "getTemplate",
3347 value: function getTemplate() {
3348 return "#tmpl-elementor-finder";
3349 }
3350 },
3351 {
3352 key: "ui",
3353 value: function ui() {
3354 return { searchInput: "#elementor-finder__search__input" };
3355 }
3356 },
3357 {
3358 key: "events",
3359 value: function events() {
3360 return { "input @ui.searchInput": "onSearchInputInput" };
3361 }
3362 },
3363 {
3364 key: "regions",
3365 value: function regions() {
3366 return { content: "#elementor-finder__content" };
3367 }
3368 },
3369 {
3370 key: "initialize",
3371 value: function initialize() {
3372 this.debouncedTrackSearch = createDebouncedFinderSearch(FINDER_SEARCH_DEBOUNCE_MS);
3373 }
3374 },
3375 {
3376 key: "showCategoriesView",
3377 value: function showCategoriesView() {
3378 this.content.show(new _default$5());
3379 }
3380 },
3381 {
3382 key: "getResultsCount",
3383 value: function getResultsCount() {
3384 if (!this.content.currentView) return 0;
3385 return this.content.currentView.$el.find(".elementor-finder__results__item:visible").length;
3386 }
3387 },
3388 {
3389 key: "onSearchInputInput",
3390 value: function onSearchInputInput() {
3391 var _this = this;
3392 var value = this.ui.searchInput.val();
3393 if (value) {
3394 elementorCommon.finder.channel.reply("filter:text", value).trigger("filter:change");
3395 if (!(this.content.currentView instanceof _default$5)) this.showCategoriesView();
3396 setTimeout(function() {
3397 var resultsCount = _this.getResultsCount();
3398 _this.debouncedTrackSearch(resultsCount, value);
3399 }, 50);
3400 }
3401 this.content.currentView.$el.toggle(!!value);
3402 }
3403 },
3404 {
3405 key: "onDestroy",
3406 value: function onDestroy() {
3407 var _this$debouncedTrackS;
3408 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) this.debouncedTrackSearch.cancel();
3409 }
3410 }
3411 ]);
3412 }(Marionette.LayoutView);
3413
3414 //#endregion
3415 //#region core/common/modules/finder/assets/js/modal/views/layout.js
3416 function _callSuper$16(t, o, e) {
3417 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$16() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3418 }
3419 __name(_callSuper$16, "_callSuper");
3420 function _isNativeReflectConstruct$16() {
3421 try {
3422 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3423 } catch (t) {}
3424 return (_isNativeReflectConstruct$16 = function _isNativeReflectConstruct() {
3425 return !!t;
3426 })();
3427 }
3428 __name(_isNativeReflectConstruct$16, "_isNativeReflectConstruct");
3429 function _superPropGet$4(t, o, e, r) {
3430 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3431 return 2 & r && "function" == typeof p ? function(t) {
3432 return p.apply(e, t);
3433 } : p;
3434 }
3435 __name(_superPropGet$4, "_superPropGet");
3436 var _default$3 = /*#__PURE__*/ function(_elementorModules$com) {
3437 function _default() {
3438 _classCallCheck(this, _default);
3439 return _callSuper$16(this, _default, arguments);
3440 }
3441 _inherits$1(_default, _elementorModules$com);
3442 return _createClass(_default, [
3443 {
3444 key: "getModalOptions",
3445 value: function getModalOptions() {
3446 return {
3447 id: "elementor-finder__modal",
3448 draggable: true,
3449 effects: {
3450 show: "show",
3451 hide: "hide"
3452 },
3453 position: { enable: false }
3454 };
3455 }
3456 },
3457 {
3458 key: "getLogoOptions",
3459 value: function getLogoOptions() {
3460 return { title: (0, _wordpress_i18n.__)("Finder", "elementor") };
3461 }
3462 },
3463 {
3464 key: "initialize",
3465 value: function initialize() {
3466 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
3467 _superPropGet$4(_default, "initialize", this, 3)(args);
3468 this.showLogo();
3469 this.showContentView();
3470 }
3471 },
3472 {
3473 key: "showContentView",
3474 value: function showContentView() {
3475 this.modalContent.show(new _default$4());
3476 }
3477 },
3478 {
3479 key: "showModal",
3480 value: function showModal() {
3481 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];
3482 _superPropGet$4(_default, "showModal", this, 3)(args);
3483 this.modalContent.currentView.ui.searchInput.focus();
3484 }
3485 }
3486 ]);
3487 }(elementorModules.common.views.modal.Layout);
3488
3489 //#endregion
3490 //#region core/common/modules/finder/assets/js/commands/navigate-down.js
3491 function _callSuper$15(t, o, e) {
3492 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$15() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3493 }
3494 __name(_callSuper$15, "_callSuper");
3495 function _isNativeReflectConstruct$15() {
3496 try {
3497 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3498 } catch (t) {}
3499 return (_isNativeReflectConstruct$15 = function _isNativeReflectConstruct() {
3500 return !!t;
3501 })();
3502 }
3503 __name(_isNativeReflectConstruct$15, "_isNativeReflectConstruct");
3504 var NavigateDown = /*#__PURE__*/ function(_CommandBase) {
3505 function NavigateDown() {
3506 _classCallCheck(this, NavigateDown);
3507 return _callSuper$15(this, NavigateDown, arguments);
3508 }
3509 _inherits$1(NavigateDown, _CommandBase);
3510 return _createClass(NavigateDown, [{
3511 key: "apply",
3512 value: function apply() {
3513 this.component.getItemsView().activateNextItem();
3514 }
3515 }]);
3516 }(CommandBase);
3517
3518 //#endregion
3519 //#region core/common/modules/finder/assets/js/commands/navigate-select.js
3520 function _callSuper$14(t, o, e) {
3521 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$14() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3522 }
3523 __name(_callSuper$14, "_callSuper");
3524 function _isNativeReflectConstruct$14() {
3525 try {
3526 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3527 } catch (t) {}
3528 return (_isNativeReflectConstruct$14 = function _isNativeReflectConstruct() {
3529 return !!t;
3530 })();
3531 }
3532 __name(_isNativeReflectConstruct$14, "_isNativeReflectConstruct");
3533 var NavigateSelect = /*#__PURE__*/ function(_CommandBase) {
3534 function NavigateSelect() {
3535 _classCallCheck(this, NavigateSelect);
3536 return _callSuper$14(this, NavigateSelect, arguments);
3537 }
3538 _inherits$1(NavigateSelect, _CommandBase);
3539 return _createClass(NavigateSelect, [{
3540 key: "apply",
3541 value: function apply(args) {
3542 this.component.getItemsView().goToActiveItem(args);
3543 }
3544 }]);
3545 }(CommandBase);
3546
3547 //#endregion
3548 //#region core/common/modules/finder/assets/js/commands/navigate-up.js
3549 function _callSuper$13(t, o, e) {
3550 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$13() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3551 }
3552 __name(_callSuper$13, "_callSuper");
3553 function _isNativeReflectConstruct$13() {
3554 try {
3555 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3556 } catch (t) {}
3557 return (_isNativeReflectConstruct$13 = function _isNativeReflectConstruct() {
3558 return !!t;
3559 })();
3560 }
3561 __name(_isNativeReflectConstruct$13, "_isNativeReflectConstruct");
3562 var NavigateUp = /*#__PURE__*/ function(_CommandBase) {
3563 function NavigateUp() {
3564 _classCallCheck(this, NavigateUp);
3565 return _callSuper$13(this, NavigateUp, arguments);
3566 }
3567 _inherits$1(NavigateUp, _CommandBase);
3568 return _createClass(NavigateUp, [{
3569 key: "apply",
3570 value: function apply() {
3571 this.component.getItemsView().activateNextItem(true);
3572 }
3573 }]);
3574 }(CommandBase);
3575
3576 //#endregion
3577 //#region core/common/modules/finder/assets/js/commands/index.js
3578 var commands_exports = /* @__PURE__ */ __exportAll({
3579 NavigateDown: () => NavigateDown,
3580 NavigateSelect: () => NavigateSelect,
3581 NavigateUp: () => NavigateUp
3582 });
3583
3584 //#endregion
3585 //#region core/common/modules/finder/assets/js/component.js
3586 init_defineProperty();
3587 function ownKeys$2(e, r) {
3588 var t = Object.keys(e);
3589 if (Object.getOwnPropertySymbols) {
3590 var o = Object.getOwnPropertySymbols(e);
3591 r && (o = o.filter(function(r) {
3592 return Object.getOwnPropertyDescriptor(e, r).enumerable;
3593 })), t.push.apply(t, o);
3594 }
3595 return t;
3596 }
3597 __name(ownKeys$2, "ownKeys");
3598 function _objectSpread$2(e) {
3599 for (var r = 1; r < arguments.length; r++) {
3600 var t = null != arguments[r] ? arguments[r] : {};
3601 r % 2 ? ownKeys$2(Object(t), !0).forEach(function(r) {
3602 _defineProperty(e, r, t[r]);
3603 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function(r) {
3604 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
3605 });
3606 }
3607 return e;
3608 }
3609 __name(_objectSpread$2, "_objectSpread");
3610 function _callSuper$12(t, o, e) {
3611 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$12() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3612 }
3613 __name(_callSuper$12, "_callSuper");
3614 function _isNativeReflectConstruct$12() {
3615 try {
3616 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3617 } catch (t) {}
3618 return (_isNativeReflectConstruct$12 = function _isNativeReflectConstruct() {
3619 return !!t;
3620 })();
3621 }
3622 __name(_isNativeReflectConstruct$12, "_isNativeReflectConstruct");
3623 function _superPropGet$3(t, o, e, r) {
3624 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3625 return 2 & r && "function" == typeof p ? function(t) {
3626 return p.apply(e, t);
3627 } : p;
3628 }
3629 __name(_superPropGet$3, "_superPropGet");
3630 var Component$2 = /*#__PURE__*/ function(_ComponentModalBase) {
3631 function Component() {
3632 _classCallCheck(this, Component);
3633 return _callSuper$12(this, Component, arguments);
3634 }
3635 _inherits$1(Component, _ComponentModalBase);
3636 return _createClass(Component, [
3637 {
3638 key: "getNamespace",
3639 value: function getNamespace() {
3640 return "finder";
3641 }
3642 },
3643 {
3644 key: "defaultShortcuts",
3645 value: function defaultShortcuts() {
3646 var _this = this;
3647 return {
3648 "": { keys: "ctrl+e" },
3649 "navigate-down": {
3650 keys: "down",
3651 scopes: [this.getNamespace()],
3652 dependency: function dependency() {
3653 return _this.getItemsView();
3654 }
3655 },
3656 "navigate-up": {
3657 keys: "up",
3658 scopes: [this.getNamespace()],
3659 dependency: function dependency() {
3660 return _this.getItemsView();
3661 }
3662 },
3663 "navigate-select": {
3664 keys: "enter",
3665 scopes: [this.getNamespace()],
3666 dependency: function dependency() {
3667 return _this.getItemsView().$activeItem;
3668 }
3669 }
3670 };
3671 }
3672 },
3673 {
3674 key: "defaultCommands",
3675 value: function defaultCommands() {
3676 return _objectSpread$2(_objectSpread$2({
3677 "navigate/down": function navigate_down() {
3678 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", "3.0.0", "$e.run( 'finder/navigate-down' )");
3679 $e.run("finder/navigate-down");
3680 },
3681 "navigate/up": function navigate_up() {
3682 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", "3.0.0", "$e.run( 'finder/navigate-up' )");
3683 $e.run("finder/navigate-up");
3684 },
3685 "navigate/select": function navigate_select(event) {
3686 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", "3.0.0", "$e.run( 'finder/navigate-select', event )");
3687 $e.run("finder/navigate-select", event);
3688 }
3689 }, _superPropGet$3(Component, "defaultCommands", this, 3)([])), this.importCommands(commands_exports));
3690 }
3691 },
3692 {
3693 key: "getModalLayout",
3694 value: function getModalLayout() {
3695 return _default$3;
3696 }
3697 },
3698 {
3699 key: "getItemsView",
3700 value: function getItemsView() {
3701 return this.layout.modalContent.currentView.content.currentView;
3702 }
3703 }
3704 ]);
3705 }(ComponentModalBase);
3706
3707 //#endregion
3708 //#region core/common/modules/finder/assets/js/finder.js
3709 function _callSuper$11(t, o, e) {
3710 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$11() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3711 }
3712 __name(_callSuper$11, "_callSuper");
3713 function _isNativeReflectConstruct$11() {
3714 try {
3715 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3716 } catch (t) {}
3717 return (_isNativeReflectConstruct$11 = function _isNativeReflectConstruct() {
3718 return !!t;
3719 })();
3720 }
3721 __name(_isNativeReflectConstruct$11, "_isNativeReflectConstruct");
3722 var _default$2 = /*#__PURE__*/ function(_elementorModules$Mod) {
3723 function _default() {
3724 _classCallCheck(this, _default);
3725 return _callSuper$11(this, _default, arguments);
3726 }
3727 _inherits$1(_default, _elementorModules$Mod);
3728 return _createClass(_default, [{
3729 key: "onInit",
3730 value: function onInit() {
3731 if (window.top !== window) return;
3732 this.channel = Backbone.Radio.channel("ELEMENTOR:finder");
3733 $e.components.register(new Component$2({ manager: this }));
3734 }
3735 }]);
3736 }(elementorModules.Module);
3737
3738 //#endregion
3739 //#region core/common/modules/connect/assets/js/connect.js
3740 function _callSuper$10(t, o, e) {
3741 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$10() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
3742 }
3743 __name(_callSuper$10, "_callSuper");
3744 function _isNativeReflectConstruct$10() {
3745 try {
3746 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
3747 } catch (t) {}
3748 return (_isNativeReflectConstruct$10 = function _isNativeReflectConstruct() {
3749 return !!t;
3750 })();
3751 }
3752 __name(_isNativeReflectConstruct$10, "_isNativeReflectConstruct");
3753 function _superPropGet$2(t, o, e, r) {
3754 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
3755 return 2 & r && "function" == typeof p ? function(t) {
3756 return p.apply(e, t);
3757 } : p;
3758 }
3759 __name(_superPropGet$2, "_superPropGet");
3760 var _default$1 = /*#__PURE__*/ function(_elementorModules$Vie) {
3761 function _default() {
3762 _classCallCheck(this, _default);
3763 return _callSuper$10(this, _default, arguments);
3764 }
3765 _inherits$1(_default, _elementorModules$Vie);
3766 return _createClass(_default, [
3767 {
3768 key: "addPopupPlugin",
3769 value: function addPopupPlugin() {
3770 var counter = 0;
3771 jQuery.fn.elementorConnect = function(options) {
3772 var _this = this;
3773 if (options !== null && options !== void 0 && options.popup) {
3774 jQuery(this).on("click", function(event) {
3775 var _options$popup;
3776 var _options$popup2;
3777 event.preventDefault();
3778 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600;
3779 var height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
3780 window.open(jQuery(_this).attr("href") + "&mode=popup", "elementorConnect", "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
3781 });
3782 delete options.popup;
3783 }
3784 var settings = jQuery.extend({
3785 success: function success() {
3786 return location.reload();
3787 },
3788 error: function error() {
3789 elementor.notifications.showToast({ message: (0, _wordpress_i18n.__)("Unable to connect", "elementor") });
3790 },
3791 parseUrl: function parseUrl(url) {
3792 return url;
3793 }
3794 }, options);
3795 this.each(function() {
3796 counter++;
3797 var $this = jQuery(this);
3798 var callbackId = "cb" + counter;
3799 $this.attr({
3800 target: "_blank",
3801 rel: "opener",
3802 href: settings.parseUrl($this.attr("href") + "&mode=popup&callback_id=" + callbackId)
3803 });
3804 elementorCommon.elements.$window.on("elementor/connect/success/" + callbackId, settings.success).on("elementor/connect/error/" + callbackId, settings.error);
3805 });
3806 return this;
3807 };
3808 }
3809 },
3810 {
3811 key: "getDefaultSettings",
3812 value: function getDefaultSettings() {
3813 return { selectors: { connectButton: "#elementor-template-library-connect__button" } };
3814 }
3815 },
3816 {
3817 key: "getDefaultElements",
3818 value: function getDefaultElements() {
3819 return { $connectButton: jQuery(this.getSettings("selectors.connectButton")) };
3820 }
3821 },
3822 {
3823 key: "applyPopup",
3824 value: function applyPopup() {
3825 this.elements.$connectButton.elementorConnect();
3826 }
3827 },
3828 {
3829 key: "onInit",
3830 value: function onInit() {
3831 _superPropGet$2(_default, "onInit", this, 3)([]);
3832 this.addPopupPlugin();
3833 this.applyPopup();
3834 }
3835 }
3836 ]);
3837 }(elementorModules.ViewModule);
3838
3839 //#endregion
3840 //#region node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
3841 function asyncGeneratorStep$1(n, t, e, r, o, a, c) {
3842 try {
3843 var i = n[a](c);
3844 var u = i.value;
3845 } catch (n) {
3846 e(n);
3847 return;
3848 }
3849 i.done ? t(u) : Promise.resolve(u).then(r, o);
3850 }
3851 __name(asyncGeneratorStep$1, "asyncGeneratorStep");
3852 function _asyncToGenerator(n) {
3853 return function() {
3854 var t = this;
3855 var e = arguments;
3856 return new Promise(function(r, o) {
3857 var a = n.apply(t, e);
3858 function _next(n) {
3859 asyncGeneratorStep$1(a, r, o, _next, _throw, "next", n);
3860 }
3861 function _throw(n) {
3862 asyncGeneratorStep$1(a, r, o, _next, _throw, "throw", n);
3863 }
3864 _next(void 0);
3865 });
3866 };
3867 }
3868
3869 //#endregion
3870 //#region node_modules/@babel/runtime/helpers/OverloadYield.js
3871 var require_OverloadYield = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3872 function _OverloadYield(e, d) {
3873 this.v = e, this.k = d;
3874 }
3875 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
3876 }));
3877
3878 //#endregion
3879 //#region node_modules/@babel/runtime/helpers/regeneratorDefine.js
3880 var require_regeneratorDefine = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3881 function _regeneratorDefine(e, r, n, t) {
3882 var i = Object.defineProperty;
3883 try {
3884 i({}, "", {});
3885 } catch (e) {
3886 i = 0;
3887 }
3888 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
3889 function o(r, n) {
3890 _regeneratorDefine(e, r, function(e) {
3891 return this._invoke(r, n, e);
3892 });
3893 }
3894 r ? i ? i(e, r, {
3895 value: n,
3896 enumerable: !t,
3897 configurable: !t,
3898 writable: !t
3899 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
3900 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
3901 }
3902 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
3903 }));
3904
3905 //#endregion
3906 //#region node_modules/@babel/runtime/helpers/regenerator.js
3907 var require_regenerator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3908 var regeneratorDefine = require_regeneratorDefine();
3909 function _regenerator() {
3910 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
3911 var e;
3912 var t;
3913 var r = "function" == typeof Symbol ? Symbol : {};
3914 var n = r.iterator || "@@iterator";
3915 var o = r.toStringTag || "@@toStringTag";
3916 function i(r, n, o, i) {
3917 var c = n && n.prototype instanceof Generator ? n : Generator;
3918 var u = Object.create(c.prototype);
3919 return regeneratorDefine(u, "_invoke", function(r, n, o) {
3920 var i;
3921 var c;
3922 var u;
3923 var f = 0;
3924 var p = o || [];
3925 var y = !1;
3926 var G = {
3927 p: 0,
3928 n: 0,
3929 v: e,
3930 a: d,
3931 f: d.bind(e, 4),
3932 d: function d(t, r) {
3933 return i = t, c = 0, u = e, G.n = r, a;
3934 }
3935 };
3936 function d(r, n) {
3937 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
3938 var o;
3939 var i = p[t];
3940 var d = G.p;
3941 var l = i[2];
3942 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));
3943 }
3944 if (o || r > 1) return a;
3945 throw y = !0, n;
3946 }
3947 return function(o, p, l) {
3948 if (f > 1) throw TypeError("Generator is already running");
3949 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
3950 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
3951 try {
3952 if (f = 2, i) {
3953 if (c || (o = "next"), t = i[o]) {
3954 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
3955 if (!t.done) return t;
3956 u = t.value, c < 2 && (c = 0);
3957 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
3958 i = e;
3959 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
3960 } catch (t) {
3961 i = e, c = 1, u = t;
3962 } finally {
3963 f = 1;
3964 }
3965 }
3966 return {
3967 value: t,
3968 done: y
3969 };
3970 };
3971 }(r, o, i), !0), u;
3972 }
3973 var a = {};
3974 function Generator() {}
3975 function GeneratorFunction() {}
3976 function GeneratorFunctionPrototype() {}
3977 t = Object.getPrototypeOf;
3978 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function() {
3979 return this;
3980 }), t);
3981 var u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
3982 function f(e) {
3983 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
3984 }
3985 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() {
3986 return this;
3987 }), regeneratorDefine(u, "toString", function() {
3988 return "[object Generator]";
3989 }), (module.exports = _regenerator = function _regenerator() {
3990 return {
3991 w: i,
3992 m: f
3993 };
3994 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
3995 }
3996 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
3997 }));
3998
3999 //#endregion
4000 //#region node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js
4001 var require_regeneratorAsyncIterator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4002 var OverloadYield = require_OverloadYield();
4003 var regeneratorDefine = require_regeneratorDefine();
4004 function AsyncIterator(t, e) {
4005 function n(r, o, i, f) {
4006 try {
4007 var c = t[r](o);
4008 var u = c.value;
4009 return u instanceof OverloadYield ? e.resolve(u.v).then(function(t) {
4010 n("next", t, i, f);
4011 }, function(t) {
4012 n("throw", t, i, f);
4013 }) : e.resolve(u).then(function(t) {
4014 c.value = t, i(c);
4015 }, function(t) {
4016 return n("throw", t, i, f);
4017 });
4018 } catch (t) {
4019 f(t);
4020 }
4021 }
4022 var r;
4023 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function() {
4024 return this;
4025 })), regeneratorDefine(this, "_invoke", function(t, o, i) {
4026 function f() {
4027 return new e(function(e, r) {
4028 n(t, i, e, r);
4029 });
4030 }
4031 return r = r ? r.then(f, f) : f();
4032 }, !0);
4033 }
4034 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
4035 }));
4036
4037 //#endregion
4038 //#region node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js
4039 var require_regeneratorAsyncGen = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4040 var regenerator = require_regenerator$1();
4041 var regeneratorAsyncIterator = require_regeneratorAsyncIterator();
4042 function _regeneratorAsyncGen(r, e, t, o, n) {
4043 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
4044 }
4045 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
4046 }));
4047
4048 //#endregion
4049 //#region node_modules/@babel/runtime/helpers/regeneratorAsync.js
4050 var require_regeneratorAsync = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4051 var regeneratorAsyncGen = require_regeneratorAsyncGen();
4052 function _regeneratorAsync(n, e, r, t, o) {
4053 var a = regeneratorAsyncGen(n, e, r, t, o);
4054 return a.next().then(function(n) {
4055 return n.done ? n.value : a.next();
4056 });
4057 }
4058 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
4059 }));
4060
4061 //#endregion
4062 //#region node_modules/@babel/runtime/helpers/regeneratorKeys.js
4063 var require_regeneratorKeys = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4064 function _regeneratorKeys(e) {
4065 var n = Object(e);
4066 var r = [];
4067 for (var t in n) r.unshift(t);
4068 return function e() {
4069 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
4070 return e.done = !0, e;
4071 };
4072 }
4073 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
4074 }));
4075
4076 //#endregion
4077 //#region node_modules/@babel/runtime/helpers/typeof.js
4078 var require_typeof = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4079 function _typeof(o) {
4080 "@babel/helpers - typeof";
4081 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
4082 return typeof o;
4083 } : function(o) {
4084 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
4085 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
4086 }
4087 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
4088 }));
4089
4090 //#endregion
4091 //#region node_modules/@babel/runtime/helpers/regeneratorValues.js
4092 var require_regeneratorValues = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4093 var _typeof = require_typeof()["default"];
4094 function _regeneratorValues(e) {
4095 if (null != e) {
4096 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"];
4097 var r = 0;
4098 if (t) return t.call(e);
4099 if ("function" == typeof e.next) return e;
4100 if (!isNaN(e.length)) return { next: function next() {
4101 return e && r >= e.length && (e = void 0), {
4102 value: e && e[r++],
4103 done: !e
4104 };
4105 } };
4106 }
4107 throw new TypeError(_typeof(e) + " is not iterable");
4108 }
4109 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
4110 }));
4111
4112 //#endregion
4113 //#region node_modules/@babel/runtime/helpers/regeneratorRuntime.js
4114 var require_regeneratorRuntime = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4115 var OverloadYield = require_OverloadYield();
4116 var regenerator = require_regenerator$1();
4117 var regeneratorAsync = require_regeneratorAsync();
4118 var regeneratorAsyncGen = require_regeneratorAsyncGen();
4119 var regeneratorAsyncIterator = require_regeneratorAsyncIterator();
4120 var regeneratorKeys = require_regeneratorKeys();
4121 var regeneratorValues = require_regeneratorValues();
4122 function _regeneratorRuntime() {
4123 "use strict";
4124 var r = regenerator();
4125 var e = r.m(_regeneratorRuntime);
4126 var t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
4127 function n(r) {
4128 var e = "function" == typeof r && r.constructor;
4129 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
4130 }
4131 var o = {
4132 "throw": 1,
4133 "return": 2,
4134 "break": 3,
4135 "continue": 3
4136 };
4137 function a(r) {
4138 var e;
4139 var t;
4140 return function(n) {
4141 e || (e = {
4142 stop: function stop() {
4143 return t(n.a, 2);
4144 },
4145 "catch": function _catch() {
4146 return n.v;
4147 },
4148 abrupt: function abrupt(r, e) {
4149 return t(n.a, o[r], e);
4150 },
4151 delegateYield: function delegateYield(r, o, a) {
4152 return e.resultName = o, t(n.d, regeneratorValues(r), a);
4153 },
4154 finish: function finish(r) {
4155 return t(n.f, r);
4156 }
4157 }, t = function t(r, _t, o) {
4158 n.p = e.prev, n.n = e.next;
4159 try {
4160 return r(_t, o);
4161 } finally {
4162 e.next = n.n;
4163 }
4164 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
4165 try {
4166 return r.call(this, e);
4167 } finally {
4168 n.p = e.prev, n.n = e.next;
4169 }
4170 };
4171 }
4172 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
4173 return {
4174 wrap: function wrap(e, t, n, o) {
4175 return r.w(a(e), t, n, o && o.reverse());
4176 },
4177 isGeneratorFunction: n,
4178 mark: r.m,
4179 awrap: function awrap(r, e) {
4180 return new OverloadYield(r, e);
4181 },
4182 AsyncIterator: regeneratorAsyncIterator,
4183 async: function async(r, e, t, o, u) {
4184 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
4185 },
4186 keys: regeneratorKeys,
4187 values: regeneratorValues
4188 };
4189 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
4190 }
4191 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
4192 }));
4193
4194 //#endregion
4195 //#region node_modules/@babel/runtime/regenerator/index.js
4196 var require_regenerator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
4197 var runtime = require_regeneratorRuntime()();
4198 module.exports = runtime;
4199 try {
4200 regeneratorRuntime = runtime;
4201 } catch (accidentalStrictMode) {
4202 if (typeof globalThis === "object") globalThis.regeneratorRuntime = runtime;
4203 else Function("r", "regeneratorRuntime = r")(runtime);
4204 }
4205 }));
4206
4207 //#endregion
4208 //#region modules/web-cli/assets/js/core/data/errors/base-error.js
4209 var import_regenerator = /* @__PURE__ */ __toESM(require_regenerator());
4210 init_defineProperty();
4211 function ownKeys$1(e, r) {
4212 var t = Object.keys(e);
4213 if (Object.getOwnPropertySymbols) {
4214 var o = Object.getOwnPropertySymbols(e);
4215 r && (o = o.filter(function(r) {
4216 return Object.getOwnPropertyDescriptor(e, r).enumerable;
4217 })), t.push.apply(t, o);
4218 }
4219 return t;
4220 }
4221 __name(ownKeys$1, "ownKeys");
4222 function _objectSpread$1(e) {
4223 for (var r = 1; r < arguments.length; r++) {
4224 var t = null != arguments[r] ? arguments[r] : {};
4225 r % 2 ? ownKeys$1(Object(t), !0).forEach(function(r) {
4226 _defineProperty(e, r, t[r]);
4227 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r) {
4228 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
4229 });
4230 }
4231 return e;
4232 }
4233 __name(_objectSpread$1, "_objectSpread");
4234 function _callSuper$9(t, o, e) {
4235 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$9() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4236 }
4237 __name(_callSuper$9, "_callSuper");
4238 function _isNativeReflectConstruct$9() {
4239 try {
4240 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4241 } catch (t) {}
4242 return (_isNativeReflectConstruct$9 = function _isNativeReflectConstruct() {
4243 return !!t;
4244 })();
4245 }
4246 __name(_isNativeReflectConstruct$9, "_isNativeReflectConstruct");
4247 var BaseError = /*#__PURE__*/ function(_Error) {
4248 /**
4249 * Error constructor.
4250 *
4251 * @param {string} message
4252 * @param {string} code
4253 * @param {*} data
4254 */
4255 function BaseError() {
4256 var _this;
4257 var message = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
4258 var code = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
4259 var data = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
4260 _classCallCheck(this, BaseError);
4261 _this = _callSuper$9(this, BaseError, [message]);
4262 /**
4263 * The server error code.
4264 *
4265 * @type {string}
4266 */
4267 _defineProperty(_this, "code", "");
4268 /**
4269 * Additional data about the current error.
4270 *
4271 * @type {*[]}
4272 */
4273 _defineProperty(_this, "data", []);
4274 _this.code = code;
4275 _this.data = data;
4276 return _this;
4277 }
4278 /**
4279 * Notify a message when the error occurs.
4280 */
4281 _inherits$1(BaseError, _Error);
4282 return _createClass(BaseError, [{
4283 key: "notify",
4284 value: function notify() {
4285 Console.error(_objectSpread$1({ message: this.message }, this));
4286 }
4287 }], [{
4288 key: "create",
4289 value: function create(message) {
4290 var code = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
4291 var data = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
4292 return new this(message, code, data);
4293 }
4294 }, {
4295 key: "getHTTPErrorCode",
4296 value: function getHTTPErrorCode() {
4297 force_method_implementation_default();
4298 }
4299 }]);
4300 }(/*#__PURE__*/ _wrapNativeSuper(Error));
4301
4302 //#endregion
4303 //#region modules/web-cli/assets/js/core/data/errors/default-error.js
4304 function _callSuper$8(t, o, e) {
4305 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$8() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4306 }
4307 __name(_callSuper$8, "_callSuper");
4308 function _isNativeReflectConstruct$8() {
4309 try {
4310 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4311 } catch (t) {}
4312 return (_isNativeReflectConstruct$8 = function _isNativeReflectConstruct() {
4313 return !!t;
4314 })();
4315 }
4316 __name(_isNativeReflectConstruct$8, "_isNativeReflectConstruct");
4317 var DefaultError = /*#__PURE__*/ function(_BaseError) {
4318 function DefaultError() {
4319 _classCallCheck(this, DefaultError);
4320 return _callSuper$8(this, DefaultError, arguments);
4321 }
4322 _inherits$1(DefaultError, _BaseError);
4323 return _createClass(DefaultError, null, [{
4324 key: "getHTTPErrorCode",
4325 value: function getHTTPErrorCode() {
4326 return 501;
4327 }
4328 }]);
4329 }(BaseError);
4330
4331 //#endregion
4332 //#region modules/web-cli/assets/js/core/data/errors/error-404.js
4333 function _callSuper$7(t, o, e) {
4334 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$7() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4335 }
4336 __name(_callSuper$7, "_callSuper");
4337 function _isNativeReflectConstruct$7() {
4338 try {
4339 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4340 } catch (t) {}
4341 return (_isNativeReflectConstruct$7 = function _isNativeReflectConstruct() {
4342 return !!t;
4343 })();
4344 }
4345 __name(_isNativeReflectConstruct$7, "_isNativeReflectConstruct");
4346 var Error404 = /*#__PURE__*/ function(_BaseError) {
4347 function Error404() {
4348 _classCallCheck(this, Error404);
4349 return _callSuper$7(this, Error404, arguments);
4350 }
4351 _inherits$1(Error404, _BaseError);
4352 return _createClass(Error404, [{
4353 key: "notify",
4354 value: function notify() {
4355 Console.warn(this.message);
4356 }
4357 }], [{
4358 key: "getHTTPErrorCode",
4359 value: function getHTTPErrorCode() {
4360 return 404;
4361 }
4362 }]);
4363 }(BaseError);
4364
4365 //#endregion
4366 //#region modules/web-cli/assets/js/core/data/errors/index.js
4367 var errors_exports = /* @__PURE__ */ __exportAll({
4368 DefaultError: () => DefaultError,
4369 Error404: () => Error404
4370 });
4371
4372 //#endregion
4373 //#region modules/web-cli/assets/js/modules/command-data.js
4374 init_defineProperty();
4375 function _callSuper$6(t, o, e) {
4376 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$6() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4377 }
4378 __name(_callSuper$6, "_callSuper");
4379 function _isNativeReflectConstruct$6() {
4380 try {
4381 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4382 } catch (t) {}
4383 return (_isNativeReflectConstruct$6 = function _isNativeReflectConstruct() {
4384 return !!t;
4385 })();
4386 }
4387 __name(_isNativeReflectConstruct$6, "_isNativeReflectConstruct");
4388 /**
4389 * @name $e.modules.CommandData
4390 */
4391 /**
4392 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4393 */
4394 /**
4395 * @typedef {{}} RequestData
4396 */
4397 /**
4398 * @typedef {import('../core/data/errors/base-error')} BaseError
4399 */
4400 var CommandData = /*#__PURE__*/ function(_CommandBase) {
4401 function CommandData(args) {
4402 var _this$args$options;
4403 var _this;
4404 var commandsAPI = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : $e.data;
4405 _classCallCheck(this, CommandData);
4406 _this = _callSuper$6(this, CommandData, [args, commandsAPI]);
4407 /**
4408 * Data returned from remote.
4409 *
4410 * @type {*}
4411 */
4412 _defineProperty(_this, "data", void 0);
4413 /**
4414 * Fetch type.
4415 *
4416 * @type {DataTypes}
4417 */
4418 _defineProperty(_this, "type", void 0);
4419 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) _this.type = _this.args.options.type;
4420 return _this;
4421 }
4422 /**
4423 * Function getEndpointFormat().
4424 *
4425 * @return {null|string} endpoint format
4426 */
4427 _inherits$1(CommandData, _CommandBase);
4428 return _createClass(CommandData, [
4429 {
4430 key: "getApplyMethods",
4431 value: function getApplyMethods() {
4432 var type = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.type;
4433 var before;
4434 var after;
4435 switch (type) {
4436 case "create":
4437 before = this.applyBeforeCreate;
4438 after = this.applyAfterCreate;
4439 break;
4440 case "delete":
4441 before = this.applyBeforeDelete;
4442 after = this.applyAfterDelete;
4443 break;
4444 case "get":
4445 before = this.applyBeforeGet;
4446 after = this.applyAfterGet;
4447 break;
4448 case "update":
4449 before = this.applyBeforeUpdate;
4450 after = this.applyAfterUpdate;
4451 break;
4452 case "options":
4453 before = this.applyBeforeOptions;
4454 after = this.applyAfterOptions;
4455 break;
4456 default: return false;
4457 }
4458 return {
4459 before: before.bind(this),
4460 after: after.bind(this)
4461 };
4462 }
4463 },
4464 {
4465 key: "getRequestData",
4466 value: function getRequestData() {
4467 return {
4468 type: this.type,
4469 args: this.args,
4470 timestamp: (/* @__PURE__ */ new Date()).getTime(),
4471 component: this.component,
4472 command: this.command,
4473 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4474 };
4475 }
4476 },
4477 {
4478 key: "apply",
4479 value: function apply() {
4480 var _this2 = this;
4481 var applyMethods = this.getApplyMethods();
4482 this.args = applyMethods.before(this.args);
4483 var requestData = this.getRequestData();
4484 return $e.data.fetch(requestData).then(function(data) {
4485 _this2.data = data;
4486 _this2.data = applyMethods.after(data, _this2.args);
4487 _this2.data = { data: _this2.data };
4488 _this2.data = Object.assign({ __requestData__: requestData }, _this2.data);
4489 return _this2.data;
4490 });
4491 }
4492 },
4493 {
4494 key: "applyBeforeCreate",
4495 value: function applyBeforeCreate() {
4496 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4497 }
4498 },
4499 {
4500 key: "applyAfterCreate",
4501 value: function applyAfterCreate(data) {
4502 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4503 return data;
4504 }
4505 },
4506 {
4507 key: "applyBeforeDelete",
4508 value: function applyBeforeDelete() {
4509 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4510 }
4511 },
4512 {
4513 key: "applyAfterDelete",
4514 value: function applyAfterDelete(data) {
4515 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4516 return data;
4517 }
4518 },
4519 {
4520 key: "applyBeforeGet",
4521 value: function applyBeforeGet() {
4522 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4523 }
4524 },
4525 {
4526 key: "applyAfterGet",
4527 value: function applyAfterGet(data) {
4528 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4529 return data;
4530 }
4531 },
4532 {
4533 key: "applyBeforeUpdate",
4534 value: function applyBeforeUpdate() {
4535 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4536 }
4537 },
4538 {
4539 key: "applyAfterUpdate",
4540 value: function applyAfterUpdate(data) {
4541 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4542 return data;
4543 }
4544 },
4545 {
4546 key: "applyBeforeOptions",
4547 value: function applyBeforeOptions() {
4548 return arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4549 }
4550 },
4551 {
4552 key: "applyAfterOptions",
4553 value: function applyAfterOptions(data) {
4554 arguments.length > 1 && arguments[1] !== void 0 && arguments[1];
4555 return data;
4556 }
4557 },
4558 {
4559 key: "applyAfterCatch",
4560 value: function applyAfterCatch(e) {
4561 e.notify();
4562 }
4563 },
4564 {
4565 key: "onCatchApply",
4566 value: function onCatchApply(e) {
4567 var _e;
4568 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4569 var dataError = Object.values(errors_exports).find(function(error) {
4570 return error.getHTTPErrorCode() === httpErrorCode;
4571 });
4572 if (!dataError) dataError = DefaultError;
4573 e = dataError.create(e.message, e.code, e.data || []);
4574 this.runCatchHooks(e);
4575 this.applyAfterCatch(e);
4576 }
4577 }
4578 ], [{
4579 key: "getInstanceType",
4580 value: function getInstanceType() {
4581 return "CommandData";
4582 }
4583 }, {
4584 key: "getEndpointFormat",
4585 value: function getEndpointFormat() {
4586 return null;
4587 }
4588 }]);
4589 }(CommandBase);
4590
4591 //#endregion
4592 //#region assets/dev/js/editor/utils/files-upload-handler.js
4593 var FilesUploadHandler = /*#__PURE__*/ function() {
4594 function FilesUploadHandler() {
4595 _classCallCheck(this, FilesUploadHandler);
4596 }
4597 return _createClass(FilesUploadHandler, null, [
4598 {
4599 key: "isUploadEnabled",
4600 value: function isUploadEnabled(mediaType) {
4601 if (!["svg", "application/json"].includes(mediaType)) return true;
4602 return elementorCommon.config.filesUpload.unfilteredFiles;
4603 }
4604 },
4605 {
4606 key: "setUploadTypeCaller",
4607 value: function setUploadTypeCaller(frame) {
4608 frame.uploader.uploader.param("uploadTypeCaller", "elementor-wp-media-upload");
4609 }
4610 },
4611 {
4612 key: "getUnfilteredFilesNonAdminDialog",
4613 value: function getUnfilteredFilesNonAdminDialog() {
4614 return elementorCommon.dialogsManager.createWidget("alert", {
4615 id: "e-unfiltered-files-disabled-dialog",
4616 headerMessage: (0, _wordpress_i18n.__)("Sorry, you can't upload that file yet", "elementor"),
4617 message: (0, _wordpress_i18n.__)("This is because JSON files may pose a security risk.", "elementor") + "<br><br>" + (0, _wordpress_i18n.__)("To upload them anyway, ask the site administrator to enable unfiltered file uploads.", "elementor"),
4618 strings: { confirm: (0, _wordpress_i18n.__)("Got it", "elementor") }
4619 });
4620 }
4621 },
4622 {
4623 key: "getUnfilteredFilesNotEnabledDialog",
4624 value: function getUnfilteredFilesNotEnabledDialog(callback) {
4625 var elementorInstance = window.elementorAdmin || window.elementor;
4626 if (!elementorInstance.config.user.is_administrator) return this.getUnfilteredFilesNonAdminDialog();
4627 return elementorInstance.helpers.getSimpleDialog("e-enable-unfiltered-files-dialog", (0, _wordpress_i18n.__)("Enable Unfiltered File Uploads", "elementor"), (0, _wordpress_i18n.__)("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"), (0, _wordpress_i18n.__)("Enable", "elementor"), function onConfirm() {
4628 elementorCommon.ajax.addRequest("enable_unfiltered_files_upload", {}, true);
4629 elementorCommon.config.filesUpload.unfilteredFiles = true;
4630 callback();
4631 });
4632 }
4633 },
4634 {
4635 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
4636 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
4637 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) return this.getUnfilteredFilesNonAdminDialog();
4638 return elementorCommon.dialogsManager.createWidget("confirm", {
4639 id: "e-enable-unfiltered-files-dialog-import-template",
4640 headerMessage: (0, _wordpress_i18n.__)("Enable Unfiltered File Uploads", "elementor"),
4641 message: (0, _wordpress_i18n.__)("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 />" + (0, _wordpress_i18n.__)("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"),
4642 position: {
4643 my: "center center",
4644 at: "center center"
4645 },
4646 strings: {
4647 confirm: (0, _wordpress_i18n.__)("Enable and Import", "elementor"),
4648 cancel: (0, _wordpress_i18n.__)("Import Without Enabling", "elementor")
4649 },
4650 onConfirm: function onConfirm() {
4651 elementorCommon.ajax.addRequest("enable_unfiltered_files_upload", { success: function success() {
4652 elementorCommon.config.filesUpload.unfilteredFiles = true;
4653 callback();
4654 } }, true);
4655 },
4656 onCancel: function onCancel() {
4657 return callback();
4658 }
4659 });
4660 }
4661 }
4662 ]);
4663 }();
4664
4665 //#endregion
4666 //#region core/common/assets/js/components/wordpress/commands-data/media.js
4667 function _callSuper$5(t, o, e) {
4668 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$5() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4669 }
4670 __name(_callSuper$5, "_callSuper");
4671 function _isNativeReflectConstruct$5() {
4672 try {
4673 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4674 } catch (t) {}
4675 return (_isNativeReflectConstruct$5 = function _isNativeReflectConstruct() {
4676 return !!t;
4677 })();
4678 }
4679 __name(_isNativeReflectConstruct$5, "_isNativeReflectConstruct");
4680 function _superPropGet$1(t, o, e, r) {
4681 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
4682 return 2 & r && "function" == typeof p ? function(t) {
4683 return p.apply(e, t);
4684 } : p;
4685 }
4686 __name(_superPropGet$1, "_superPropGet");
4687 var Media = /*#__PURE__*/ function(_CommandData) {
4688 function Media() {
4689 _classCallCheck(this, Media);
4690 return _callSuper$5(this, Media, arguments);
4691 }
4692 _inherits$1(Media, _CommandData);
4693 return _createClass(Media, [
4694 {
4695 key: "validateArgs",
4696 value: function validateArgs() {
4697 this.requireArgumentInstance("file", File);
4698 }
4699 },
4700 {
4701 key: "getRequestData",
4702 value: function getRequestData() {
4703 var requestData = _superPropGet$1(Media, "getRequestData", this, 3)([]);
4704 requestData.namespace = "wp";
4705 requestData.version = "2";
4706 return requestData;
4707 }
4708 },
4709 {
4710 key: "applyBeforeCreate",
4711 value: function applyBeforeCreate(args) {
4712 var _args$options;
4713 args.headers = {
4714 "Content-Disposition": "attachment; filename=".concat(this.file.name),
4715 "Content-Type": this.file.type
4716 };
4717 args.query = { uploadTypeCaller: "elementor-wp-media-upload" };
4718 args.data = this.file;
4719 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) this.toast = elementor.notifications.showToast({
4720 message: (0, _wordpress_i18n.__)("Uploading..."),
4721 sticky: true
4722 });
4723 return args;
4724 }
4725 },
4726 {
4727 key: "applyAfterCreate",
4728 value: function applyAfterCreate(data, args) {
4729 var _args$options2;
4730 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) this.toast.hide();
4731 return data;
4732 }
4733 },
4734 {
4735 key: "run",
4736 value: function() {
4737 var _run = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee() {
4738 return import_regenerator.default.wrap(function(_context) {
4739 while (1) switch (_context.prev = _context.next) {
4740 case 0:
4741 this.file = this.args.file;
4742 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
4743 _context.next = 1;
4744 break;
4745 }
4746 throw new Error((0, _wordpress_i18n.__)("The file exceeds the maximum upload size for this site.", "elementor"));
4747 case 1:
4748 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(",").includes(this.file.name.split(".").pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
4749 _context.next = 2;
4750 break;
4751 }
4752 FilesUploadHandler.getUnfilteredFilesNotEnabledDialog(function() {}).show();
4753 return _context.abrupt("return");
4754 case 2:
4755 _context.next = 3;
4756 return _superPropGet$1(Media, "run", this, 3)([]);
4757 case 3: return _context.abrupt("return", _context.sent);
4758 case 4:
4759 case "end": return _context.stop();
4760 }
4761 }, _callee, this);
4762 }));
4763 function run() {
4764 return _run.apply(this, arguments);
4765 }
4766 return run;
4767 }()
4768 }
4769 ], [{
4770 key: "getEndpointFormat",
4771 value: function getEndpointFormat() {
4772 return "media";
4773 }
4774 }]);
4775 }(CommandData);
4776
4777 //#endregion
4778 //#region core/common/assets/js/components/wordpress/commands-data/index.js
4779 var commands_data_exports$1 = /* @__PURE__ */ __exportAll({ Media: () => Media });
4780
4781 //#endregion
4782 //#region core/common/assets/js/components/wordpress/component.js
4783 function _callSuper$4(t, o, e) {
4784 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$4() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4785 }
4786 __name(_callSuper$4, "_callSuper");
4787 function _isNativeReflectConstruct$4() {
4788 try {
4789 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4790 } catch (t) {}
4791 return (_isNativeReflectConstruct$4 = function _isNativeReflectConstruct() {
4792 return !!t;
4793 })();
4794 }
4795 __name(_isNativeReflectConstruct$4, "_isNativeReflectConstruct");
4796 var Component$1 = /*#__PURE__*/ function(_ComponentBase) {
4797 function Component() {
4798 _classCallCheck(this, Component);
4799 return _callSuper$4(this, Component, arguments);
4800 }
4801 _inherits$1(Component, _ComponentBase);
4802 return _createClass(Component, [{
4803 key: "getNamespace",
4804 value: function getNamespace() {
4805 return "wp";
4806 }
4807 }, {
4808 key: "defaultData",
4809 value: function defaultData() {
4810 return this.importCommands(commands_data_exports$1);
4811 }
4812 }]);
4813 }(ComponentBase);
4814
4815 //#endregion
4816 //#region core/common/modules/event-tracker/assets/js/data/commands-data/index.js
4817 var commands_data_exports = /* @__PURE__ */ __exportAll({ Index: () => Index });
4818 function _callSuper$3(t, o, e) {
4819 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$3() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4820 }
4821 __name(_callSuper$3, "_callSuper");
4822 function _isNativeReflectConstruct$3() {
4823 try {
4824 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4825 } catch (t) {}
4826 return (_isNativeReflectConstruct$3 = function _isNativeReflectConstruct() {
4827 return !!t;
4828 })();
4829 }
4830 __name(_isNativeReflectConstruct$3, "_isNativeReflectConstruct");
4831 var Index = /*#__PURE__*/ function(_CommandData) {
4832 function Index() {
4833 _classCallCheck(this, Index);
4834 return _callSuper$3(this, Index, arguments);
4835 }
4836 _inherits$1(Index, _CommandData);
4837 return _createClass(Index, null, [{
4838 key: "getEndpointFormat",
4839 value: function getEndpointFormat() {
4840 return "send-event";
4841 }
4842 }]);
4843 }(CommandData);
4844
4845 //#endregion
4846 //#region core/common/modules/event-tracker/assets/js/data/component.js
4847 function _callSuper$2(t, o, e) {
4848 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$2() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
4849 }
4850 __name(_callSuper$2, "_callSuper");
4851 function _isNativeReflectConstruct$2() {
4852 try {
4853 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
4854 } catch (t) {}
4855 return (_isNativeReflectConstruct$2 = function _isNativeReflectConstruct() {
4856 return !!t;
4857 })();
4858 }
4859 __name(_isNativeReflectConstruct$2, "_isNativeReflectConstruct");
4860 var Component = /*#__PURE__*/ function(_ComponentBase) {
4861 function Component() {
4862 _classCallCheck(this, Component);
4863 return _callSuper$2(this, Component, arguments);
4864 }
4865 _inherits$1(Component, _ComponentBase);
4866 return _createClass(Component, [{
4867 key: "getNamespace",
4868 value: function getNamespace() {
4869 return "event-tracker";
4870 }
4871 }, {
4872 key: "defaultData",
4873 value: function defaultData() {
4874 return this.importCommands(commands_data_exports);
4875 }
4876 }]);
4877 }(ComponentBase);
4878
4879 //#endregion
4880 //#region assets/dev/js/utils/time.js
4881 /**
4882 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
4883 *
4884 * @since 3.6.0
4885 *
4886 * @param {Date} date
4887 * @return {Date} timestamp
4888 */
4889 function getUserTimestamp() {
4890 var date = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : /* @__PURE__ */ new Date();
4891 var timezoneOffset = date.getTimezoneOffset();
4892 var UTCTimestamp = (/* @__PURE__ */ new Date(date.getTime() - timezoneOffset * 6e4)).toISOString();
4893 UTCTimestamp = UTCTimestamp.slice(0, -1);
4894 var decimalTimezoneOffset = timezoneOffset / 60;
4895 var sign = 0 <= decimalTimezoneOffset ? "+" : "-";
4896 var hours = Math.abs(Math.floor(decimalTimezoneOffset));
4897 var minutes = Math.abs(decimalTimezoneOffset % 1) * 60;
4898 var addZeroToHour = 10 > hours ? "0" : "";
4899 var addZeroToMinutes = 10 > minutes ? "0" : "";
4900 var formattedTimezoneOffset = sign + addZeroToHour + hours + ":" + addZeroToMinutes + minutes;
4901 return UTCTimestamp + formattedTimezoneOffset;
4902 }
4903
4904 //#endregion
4905 //#region core/common/modules/event-tracker/assets/js/events.js
4906 var Events = /*#__PURE__*/ function() {
4907 function Events() {
4908 _classCallCheck(this, Events);
4909 }
4910 return _createClass(Events, [{
4911 key: "dispatchEvent",
4912 value: function dispatchEvent(eventData) {
4913 if (!eventData) return;
4914 eventData.ts = getUserTimestamp();
4915 $e.data.create("event-tracker/index", { event_data: eventData });
4916 }
4917 }]);
4918 }();
4919
4920 //#endregion
4921 //#region core/common/modules/events-manager/assets/js/events-config.js
4922 var eventsConfig = {
4923 appTypes: {
4924 editor: "editor",
4925 wpAdmin: "wpadmin",
4926 wpDash: "wpdash"
4927 },
4928 windowNames: { sidebarMenu: "sidebar_menu" },
4929 targetTypes: {
4930 dropdownItem: "dropdown_item",
4931 button: "button",
4932 tab: "tab",
4933 toggle: "toggle",
4934 searchInput: "search_input",
4935 searchResult: "search_result",
4936 buttons: "buttons",
4937 searchWidget: "search_widget",
4938 wpDashAdminMenuItem: "wpdash_admin_menu_item",
4939 wpDashEditorMenu: "wpdash_editor_menu",
4940 wpDashSubMenuItem: "wpdash_sub_menu_item",
4941 link: "link"
4942 },
4943 interactionResults: {
4944 actionSelected: "action_selected",
4945 navigate: "navigate",
4946 create: "create",
4947 sessionEnd: "session_end",
4948 tabChanged: "tab_changed",
4949 assetInserted: "asset_inserted",
4950 assetFavorite: "asset_favorite",
4951 aiGenerate: "ai_generate",
4952 resultsUpdated: "results_updated",
4953 noResults: "no_results",
4954 selected: "selected",
4955 promotionViewed: "promotion_viewed",
4956 upgradeNow: "upgrade_now",
4957 elementorSideMenuOpened: "elementor_side_menu_opened",
4958 editorSubMenuOpened: "wpdash_editor_sub_menu_opened",
4959 themeBuilderPromotionWindow: "theme_builder_promotion_window",
4960 pageOpened: "page_opened",
4961 expanded: "expanded",
4962 collapsed: "collapsed"
4963 },
4964 targetNames: {
4965 publishDropdown: {
4966 saveDraft: "save_draft",
4967 saveAsTemplate: "save_as_template",
4968 viewPage: "view_page",
4969 copyAndShare: "copy_and_share"
4970 },
4971 pageList: { addNewPage: "add_new_page" }
4972 },
4973 triggers: {
4974 click: "Click",
4975 rightClick: "Right Click",
4976 doubleClick: "Double Click",
4977 accordionClick: "Accordion Click",
4978 toggleClick: "Toggle Click",
4979 dropdownClick: "Click Dropdown",
4980 editorLoaded: "Editor Loaded",
4981 visible: "Visible",
4982 pageLoaded: "Page Loaded",
4983 typing: "Typing",
4984 tabSelect: "Tab Select",
4985 insert: "Insert",
4986 hover: "Hover"
4987 },
4988 locations: {
4989 widgetPanel: "Widget Panel",
4990 topBar: "Top Bar",
4991 sidebar: "Sidebar",
4992 elementorEditor: "Elementor Editor",
4993 templatesLibrary: { library: "Templates Library" },
4994 app: {
4995 import: "Import Kit",
4996 export: "Export Kit",
4997 kitLibrary: "Kit Library",
4998 cloudKitLibrary: "Cloud Kit Library"
4999 },
5000 variables: "Variables Panel",
5001 variablesManager: "Variables Manager",
5002 admin: "WP admin",
5003 wpDashAdmin: "wpdash_admin",
5004 structurePanel: "Structure Panel",
5005 canvas: "Canvas",
5006 leftPanel: "Left Panel",
5007 elementorLibrary: "Elementor Library",
5008 components: { instanceEditingPanel: "Instance Editing Panel" }
5009 },
5010 secondaryLocations: {
5011 layout: "Layout Section",
5012 basic: "Basic Section",
5013 "pro-elements": "Pro Section",
5014 general: "General Section",
5015 "theme-elements": "Site Section",
5016 "theme-elements-single": "Single Section",
5017 "woocommerce-elements": "WooCommerce Section",
5018 wordpress: "WordPress Section",
5019 categories: "Widgets Tab",
5020 global: "Globals Tab",
5021 "whats-new": "What's New",
5022 "document-settings": "Document Settings icon",
5023 "preview-page": "Preview Page",
5024 "publish-button": "Publish Button",
5025 "widget-panel": "Widget Panel Icon",
5026 finder: "Finder",
5027 help: "Help",
5028 elementorLogoDropdown: "top_bar_elementor_logo_dropdown",
5029 elementorLogo: "Elementor Logo",
5030 eLogoMenu: "E-logo Menu",
5031 notes: "Notes",
5032 siteSettings: "Site Settings",
5033 structure: "Structure",
5034 documentNameDropdown: "Document Name dropdown",
5035 responsiveControls: "Responsive controls",
5036 launchpad: "launchpad",
5037 checklistHeader: "Checklist Header",
5038 checklistSteps: "Checklist Steps",
5039 userPreferences: "User Preferences",
5040 contextMenu: "Context Menu",
5041 templateLibrary: {
5042 saveModal: "Save to Modal",
5043 moveModal: "Move to Modal",
5044 bulkMoveModal: "Bulk Move to Modal",
5045 copyModal: "Copy to Modal",
5046 bulkCopyModal: "Bulk Copy to Modal",
5047 saveModalSelectFolder: "Save to Modal - select folder",
5048 saveModalSelectConnect: "Save to Modal - connect",
5049 saveModalSelectUpgrade: "Save to Modal - upgrade",
5050 importModal: "Import Modal",
5051 newFolderModal: "New Folder Modal",
5052 deleteDialog: "Delete Dialog",
5053 deleteFolderDialog: "Delete Folder Dialog",
5054 renameDialog: "Rename Dialog",
5055 createFolderDialog: "Create Folder Dialog",
5056 applySettingsDialog: "Apply Settings Dialog",
5057 cloudTab: "Cloud Tab",
5058 siteTab: "Site Tab",
5059 cloudTabFolder: "Cloud Tab - Folder",
5060 cloudTabConnect: "Cloud Tab - Connect",
5061 cloudTabUpgrade: "Cloud Tab - Upgrade",
5062 morePopup: "Context Menu",
5063 quotaBar: "Quota Bar"
5064 },
5065 kitLibrary: {
5066 cloudKitLibrary: "kits_cloud_library",
5067 cloudKitLibraryConnect: "kits_cloud_library_connect",
5068 cloudKitLibraryUpgrade: "kits_cloud_library_upgrade",
5069 kitExportCustomization: "kit_export_customization",
5070 kitExport: "kit_export",
5071 kitExportCustomizationEdit: "kit_export_customization_edit",
5072 kitExportSummary: "kit_export_summary",
5073 kitImportUploadBox: "kit_import_upload_box",
5074 kitImportCustomization: "kit_import_customization",
5075 kitImportSummary: "kit_import_summary"
5076 },
5077 variablesPopover: "Variables Popover",
5078 admin: {
5079 pluginToolsTab: "plugin_tools_tab",
5080 pluginWebsiteTemplatesTab: "plugin_website_templates_tab"
5081 },
5082 componentsTab: "Components Tab",
5083 canvasElement: "Canvas Element",
5084 publishDropdown: "Publish Dropdown",
5085 pageListDropdown: "Page List Dropdown",
5086 emptyBox: "Empty Box",
5087 searchBar: "Search Bar",
5088 finderResults: "Finder Results",
5089 libraryTabs: "Library Tabs",
5090 assetCard: "Asset Card",
5091 wpDashElementorCoreMenu: "elementor_editor_core_menu",
5092 wpDashElementorCoreSubMenu: "elementor_editor_core_sub_menu",
5093 wpDashThemeBuilder: "wpdash_core_sub_menu_theme_builder"
5094 },
5095 elements: {
5096 accordionSection: "Accordion section",
5097 buttonIcon: "Button Icon",
5098 mainCta: "Main CTA",
5099 button: "Button",
5100 link: "Link",
5101 dropdown: "Dropdown",
5102 toggle: "Toggle",
5103 launchpadChecklist: "Checklist popup"
5104 },
5105 names: {
5106 v1: {
5107 layout: "v1_widgets_tab_layout_section",
5108 basic: "v1_widgets_tab_basic_section",
5109 "pro-elements": "v1_widgets_tab_pro_section",
5110 general: "v1_widgets_tab_general_section",
5111 "theme-elements": "v1_widgets_tab_site_section",
5112 "theme-elements-single": "v1_widgets_tab_single_section",
5113 "woocommerce-elements": "v1_widgets_tab_woocommerce_section",
5114 wordpress: "v1_widgets_tab_wordpress_section",
5115 categories: "v1_widgets_tab",
5116 global: "v1_globals_tab"
5117 },
5118 topBar: {
5119 whatsNew: "top_bar_whats_new",
5120 documentSettings: "top_bar_document_settings_icon",
5121 previewPage: "top_bar_preview_page",
5122 publishButton: "top_bar_publish_button",
5123 widgetPanel: "top_bar_widget_panel_icon",
5124 finder: "top_bar_finder",
5125 help: "top_bar_help",
5126 history: "top_bar_elementor_logo_dropdown_history",
5127 userPreferences: "top_bar_elementor_logo_dropdown_user_preferences",
5128 keyboardShortcuts: "top_bar_elementor_logo_dropdown_keyboard_shortcuts",
5129 exitToWordpress: "top_bar_elementor_logo_dropdown_exit_to_wordpress",
5130 themeBuilder: "top_bar_elementor_logo_dropdown_theme_builder",
5131 notes: "top_bar_notes",
5132 siteSettings: "top_bar_site_setting",
5133 structure: "top_bar_structure",
5134 documentNameDropdown: "top_bar_document_name_dropdown",
5135 responsiveControls: "top_bar_responsive_controls",
5136 launchpadOn: "top_bar_checklist_icon_show",
5137 launchpadOff: "top_bar_checklist_icon_hide",
5138 elementorLogoDropdown: "open_e_menu",
5139 connectAccount: "connect_account",
5140 accountConnected: "account_connected"
5141 },
5142 elementorEditor: {
5143 editorLoaded: "editor_loaded",
5144 checklist: {
5145 checklistHeaderClose: "checklist_header_close_icon",
5146 checklistFirstPopup: "checklist popup triggered"
5147 },
5148 userPreferences: {
5149 checklistShow: "checklist_userpreferences_toggle_show",
5150 checklistHide: "checklist_userpreferences_toggle_hide"
5151 }
5152 },
5153 variables: {
5154 open: "open_variables_popover",
5155 add: "add_new_variable",
5156 connect: "connect_variable",
5157 save: "save_new_variable",
5158 update: "update_variable",
5159 openManager: "open_variables_manager",
5160 saveChanges: "save_variables_changes",
5161 delete: "delete_variable",
5162 variableSyncToV3: "variable_sync_to_v3"
5163 },
5164 design_system: {
5165 importOpened: "design_system_import_opened",
5166 fileSelected: "design_system_file_selected",
5167 validationFailed: "design_system_validation_failed",
5168 conflictChoice: "design_system_conflict_choice",
5169 confirmed: "design_system_import_confirmed",
5170 imported: "design_system_imported",
5171 importFailed: "design_system_import_failed",
5172 export: "design_system_export",
5173 opened: "design_system_opened"
5174 },
5175 components: {
5176 createClicked: "component_create_clicked",
5177 createCancelled: "component_creation_cancelled",
5178 created: "component_created",
5179 instanceAdded: "component_instance_added",
5180 edited: "component_edited",
5181 propertiesPanelOpened: "component_properties_panel_opened",
5182 propertiesGroupCreated: "component_properties_group_created",
5183 propertyExposed: "component_property_exposed",
5184 propertyRemoved: "component_property_removed",
5185 detached: "component_detached"
5186 },
5187 global_classes: {
5188 classApplied: "class_applied",
5189 classRemoved: "class_removed",
5190 classManagerFilterCleared: "class_manager_filter_cleared",
5191 classDeleted: "class_deleted",
5192 classPublishConflict: "class_publish_conflict",
5193 classRenamed: "class_renamed",
5194 classCreated: "class_created",
5195 classManagerSearched: "class_manager_searched",
5196 classManagerFiltersOpened: "class_manager_filters_opened",
5197 classManagerOpened: "class_manager_opened",
5198 classManagerReorder: "class_manager_reorder",
5199 classManagerFilterUsed: "class_manager_filter_used",
5200 classUsageLocate: "class_usage_locate",
5201 classUsageHovered: "class_usage_hovered",
5202 classStyled: "class_styled",
5203 classStateClicked: "class_state_clicked",
5204 classUsageClicked: "class_usage_clicked",
5205 classDuplicate: "class_duplicate",
5206 classSyncToV3PopupShown: "class_sync_to_v3_popup_shown",
5207 classSyncToV3: "class_sync_to_v3",
5208 classSyncToV3PopupClick: "class_sync_to_v3_popup_click"
5209 },
5210 editorOne: {
5211 topBarPublishDropdown: "top_bar_publish_dropdown",
5212 topBarPageList: "top_bar_page_list",
5213 siteSettingsSession: "site_settings_session",
5214 eLibraryNav: "e_library_nav",
5215 eLibraryInsert: "e_library_insert",
5216 eLibraryFavorite: "e_library_favorite",
5217 eLibraryGenerateAi: "e_library_generate_ai",
5218 finderSearchInput: "finder_search_input",
5219 finderResultSelect: "finder_result_select",
5220 canvasEmptyBoxAction: "canvas_empty_box_action",
5221 widgetPanelSearch: "widget_panel_search",
5222 wpDashElementorMenuClick: "wpdash_elementor_menu_click",
5223 wpDashEditorSubMenuHover: "wpdash_editor_sub_menu_hover",
5224 wpDashThemeBuilderClick: "wpdash_theme_builder_click",
5225 sidebarMenuItemClicked: "sidebar_menu_item_clicked",
5226 sidebarMenuGroupToggled: "sidebar_menu_group_toggled"
5227 },
5228 interactions: { created: "interactions_created" },
5229 promotions: {
5230 viewPromotion: "view_promotion",
5231 upgradePromotionClick: "upgrade_promotion_click"
5232 }
5233 }
5234 };
5235
5236 //#endregion
5237 //#region node_modules/mixpanel-browser/dist/mixpanel.module.js
5238 var win;
5239 if (typeof window === "undefined") {
5240 var loc = { hostname: "" };
5241 win = {
5242 crypto: { randomUUID: function() {
5243 throw Error("unsupported");
5244 } },
5245 navigator: {
5246 userAgent: "",
5247 onLine: true
5248 },
5249 document: {
5250 createElement: function() {
5251 return {};
5252 },
5253 location: loc,
5254 referrer: ""
5255 },
5256 screen: {
5257 width: 0,
5258 height: 0
5259 },
5260 location: loc,
5261 addEventListener: function() {},
5262 removeEventListener: function() {}
5263 };
5264 } else win = window;
5265 function _array_like_to_array(arr, len) {
5266 if (len == null || len > arr.length) len = arr.length;
5267 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
5268 return arr2;
5269 }
5270 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
5271 try {
5272 var info = gen[key](arg);
5273 var value = info.value;
5274 } catch (error) {
5275 reject(error);
5276 return;
5277 }
5278 if (info.done) resolve(value);
5279 else Promise.resolve(value).then(_next, _throw);
5280 }
5281 function _async_to_generator(fn) {
5282 return function() {
5283 var self = this;
5284 var args = arguments;
5285 return new Promise(function(resolve, reject) {
5286 var gen = fn.apply(self, args);
5287 function _next(value) {
5288 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
5289 }
5290 function _throw(err) {
5291 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
5292 }
5293 _next(void 0);
5294 });
5295 };
5296 }
5297 function _construct(Parent, args, Class) {
5298 if (_is_native_reflect_construct()) _construct = Reflect.construct;
5299 else _construct = function construct(Parent, args, Class) {
5300 var a = [null];
5301 a.push.apply(a, args);
5302 var instance = new (Function.bind.apply(Parent, a))();
5303 if (Class) _set_prototype_of(instance, Class.prototype);
5304 return instance;
5305 };
5306 return _construct.apply(null, arguments);
5307 }
5308 function _defineProperties(target, props) {
5309 for (var i = 0; i < props.length; i++) {
5310 var descriptor = props[i];
5311 descriptor.enumerable = descriptor.enumerable || false;
5312 descriptor.configurable = true;
5313 if ("value" in descriptor) descriptor.writable = true;
5314 Object.defineProperty(target, descriptor.key, descriptor);
5315 }
5316 }
5317 function _create_class(Constructor, protoProps, staticProps) {
5318 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
5319 return Constructor;
5320 }
5321 function _extends() {
5322 _extends = Object.assign || function(target) {
5323 for (var i = 1; i < arguments.length; i++) {
5324 var source = arguments[i];
5325 for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
5326 }
5327 return target;
5328 };
5329 return _extends.apply(this, arguments);
5330 }
5331 function _get_prototype_of(o) {
5332 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
5333 return o.__proto__ || Object.getPrototypeOf(o);
5334 };
5335 return _get_prototype_of(o);
5336 }
5337 function _inherits(subClass, superClass) {
5338 if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function");
5339 subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: {
5340 value: subClass,
5341 writable: true,
5342 configurable: true
5343 } });
5344 if (superClass) _set_prototype_of(subClass, superClass);
5345 }
5346 function _instanceof(left, right) {
5347 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);
5348 else return left instanceof right;
5349 }
5350 function _is_native_function(fn) {
5351 return Function.toString.call(fn).indexOf("[native code]") !== -1;
5352 }
5353 function _object_without_properties_loose(source, excluded) {
5354 if (source == null) return {};
5355 var target = {};
5356 var sourceKeys = Object.keys(source);
5357 var key;
5358 var i;
5359 for (i = 0; i < sourceKeys.length; i++) {
5360 key = sourceKeys[i];
5361 if (excluded.indexOf(key) >= 0) continue;
5362 target[key] = source[key];
5363 }
5364 return target;
5365 }
5366 function _set_prototype_of(o, p) {
5367 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
5368 o.__proto__ = p;
5369 return o;
5370 };
5371 return _set_prototype_of(o, p);
5372 }
5373 function _type_of(obj) {
5374 "@swc/helpers - typeof";
5375 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
5376 }
5377 function _unsupported_iterable_to_array(o, minLen) {
5378 if (!o) return;
5379 if (typeof o === "string") return _array_like_to_array(o, minLen);
5380 var n = Object.prototype.toString.call(o).slice(8, -1);
5381 if (n === "Object" && o.constructor) n = o.constructor.name;
5382 if (n === "Map" || n === "Set") return Array.from(n);
5383 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
5384 }
5385 function _wrap_native_super(Class) {
5386 var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0;
5387 _wrap_native_super = function wrapNativeSuper(Class) {
5388 if (Class === null || !_is_native_function(Class)) return Class;
5389 if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
5390 if (typeof _cache !== "undefined") {
5391 if (_cache.has(Class)) return _cache.get(Class);
5392 _cache.set(Class, Wrapper);
5393 }
5394 function Wrapper() {
5395 return _construct(Class, arguments, _get_prototype_of(this).constructor);
5396 }
5397 Wrapper.prototype = Object.create(Class.prototype, { constructor: {
5398 value: Wrapper,
5399 enumerable: false,
5400 writable: true,
5401 configurable: true
5402 } });
5403 return _set_prototype_of(Wrapper, Class);
5404 };
5405 return _wrap_native_super(Class);
5406 }
5407 function _is_native_reflect_construct() {
5408 try {
5409 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
5410 } catch (_) {}
5411 return (_is_native_reflect_construct = function() {
5412 return !!result;
5413 })();
5414 }
5415 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
5416 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
5417 if (it) return (it = it.call(o)).next.bind(it);
5418 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
5419 if (it) o = it;
5420 var i = 0;
5421 return function() {
5422 if (i >= o.length) return { done: true };
5423 return {
5424 done: false,
5425 value: o[i++]
5426 };
5427 };
5428 }
5429 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
5430 }
5431 function _ts_generator(thisArg, body) {
5432 var f;
5433 var y;
5434 var t;
5435 var g;
5436 var _ = {
5437 label: 0,
5438 sent: function() {
5439 if (t[0] & 1) throw t[1];
5440 return t[1];
5441 },
5442 trys: [],
5443 ops: []
5444 };
5445 return g = {
5446 next: verb(0),
5447 "throw": verb(1),
5448 "return": verb(2)
5449 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
5450 return this;
5451 }), g;
5452 function verb(n) {
5453 return function(v) {
5454 return step([n, v]);
5455 };
5456 }
5457 function step(op) {
5458 if (f) throw new TypeError("Generator is already executing.");
5459 while (_) try {
5460 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;
5461 if (y = 0, t) op = [op[0] & 2, t.value];
5462 switch (op[0]) {
5463 case 0:
5464 case 1:
5465 t = op;
5466 break;
5467 case 4:
5468 _.label++;
5469 return {
5470 value: op[1],
5471 done: false
5472 };
5473 case 5:
5474 _.label++;
5475 y = op[1];
5476 op = [0];
5477 continue;
5478 case 7:
5479 op = _.ops.pop();
5480 _.trys.pop();
5481 continue;
5482 default:
5483 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
5484 _ = 0;
5485 continue;
5486 }
5487 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
5488 _.label = op[1];
5489 break;
5490 }
5491 if (op[0] === 6 && _.label < t[1]) {
5492 _.label = t[1];
5493 t = op;
5494 break;
5495 }
5496 if (t && _.label < t[2]) {
5497 _.label = t[2];
5498 _.ops.push(op);
5499 break;
5500 }
5501 if (t[2]) _.ops.pop();
5502 _.trys.pop();
5503 continue;
5504 }
5505 op = body.call(thisArg, _);
5506 } catch (e) {
5507 op = [6, e];
5508 y = 0;
5509 } finally {
5510 f = t = 0;
5511 }
5512 if (op[0] & 5) throw op[1];
5513 return {
5514 value: op[0] ? op[1] : void 0,
5515 done: true
5516 };
5517 }
5518 }
5519 function _ts_values(o) {
5520 var s = typeof Symbol === "function" && Symbol.iterator;
5521 var m = s && o[s];
5522 var i = 0;
5523 if (m) return m.call(o);
5524 if (o && typeof o.length === "number") return { next: function() {
5525 if (o && i >= o.length) o = void 0;
5526 return {
5527 value: o && o[i++],
5528 done: !o
5529 };
5530 } };
5531 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
5532 }
5533 var __defProp = Object.defineProperty;
5534 var __defNormalProp = function(obj, key, value) {
5535 return key in obj ? __defProp(obj, key, {
5536 enumerable: true,
5537 configurable: true,
5538 writable: true,
5539 value
5540 }) : obj[key] = value;
5541 };
5542 var __publicField = function(obj, key, value) {
5543 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
5544 };
5545 var _a;
5546 var __defProp$1 = Object.defineProperty;
5547 var __defNormalProp$1 = function(obj, key, value) {
5548 return key in obj ? __defProp$1(obj, key, {
5549 enumerable: true,
5550 configurable: true,
5551 writable: true,
5552 value
5553 }) : obj[key] = value;
5554 };
5555 var __publicField$1 = function(obj, key, value) {
5556 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
5557 };
5558 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
5559 NodeType2[NodeType2["Document"] = 0] = "Document";
5560 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
5561 NodeType2[NodeType2["Element"] = 2] = "Element";
5562 NodeType2[NodeType2["Text"] = 3] = "Text";
5563 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
5564 NodeType2[NodeType2["Comment"] = 5] = "Comment";
5565 return NodeType2;
5566 }(NodeType$3 || {});
5567 var testableAccessors$1 = {
5568 Node: [
5569 "childNodes",
5570 "parentNode",
5571 "parentElement",
5572 "textContent"
5573 ],
5574 ShadowRoot: ["host", "styleSheets"],
5575 Element: [
5576 "shadowRoot",
5577 "querySelector",
5578 "querySelectorAll"
5579 ],
5580 MutationObserver: []
5581 };
5582 var testableMethods$1 = {
5583 Node: ["contains", "getRootNode"],
5584 ShadowRoot: ["getSelection"],
5585 Element: [],
5586 MutationObserver: ["constructor"]
5587 };
5588 var untaintedBasePrototype$1 = {};
5589 var isAngularZonePresent$1 = function() {
5590 return !!globalThis.Zone;
5591 };
5592 function getUntaintedPrototype$1(key) {
5593 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
5594 var defaultObj = globalThis[key];
5595 var defaultPrototype = defaultObj.prototype;
5596 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
5597 var isUntaintedAccessors = Boolean(accessorNames && accessorNames.every(function(accessor) {
5598 var _a2;
5599 var _b;
5600 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
5601 }));
5602 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
5603 var isUntaintedMethods = Boolean(methodNames && methodNames.every(function(method) {
5604 var _a2;
5605 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
5606 }));
5607 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
5608 untaintedBasePrototype$1[key] = defaultObj.prototype;
5609 return defaultObj.prototype;
5610 }
5611 try {
5612 var iframeEl = document.createElement("iframe");
5613 document.body.appendChild(iframeEl);
5614 var win = iframeEl.contentWindow;
5615 if (!win) return defaultObj.prototype;
5616 var untaintedObject = win[key].prototype;
5617 document.body.removeChild(iframeEl);
5618 if (!untaintedObject) return defaultPrototype;
5619 return untaintedBasePrototype$1[key] = untaintedObject;
5620 } catch (e) {
5621 return defaultPrototype;
5622 }
5623 }
5624 var untaintedAccessorCache$1 = {};
5625 function getUntaintedAccessor$1(key, instance, accessor) {
5626 var _a2;
5627 var cacheKey = key + "." + String(accessor);
5628 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
5629 var untaintedPrototype = getUntaintedPrototype$1(key);
5630 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
5631 if (!untaintedAccessor) return instance[accessor];
5632 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
5633 return untaintedAccessor.call(instance);
5634 }
5635 var untaintedMethodCache$1 = {};
5636 function getUntaintedMethod$1(key, instance, method) {
5637 var cacheKey = key + "." + String(method);
5638 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
5639 var untaintedMethod = getUntaintedPrototype$1(key)[method];
5640 if (typeof untaintedMethod !== "function") return instance[method];
5641 untaintedMethodCache$1[cacheKey] = untaintedMethod;
5642 return untaintedMethod.bind(instance);
5643 }
5644 function childNodes$1(n2) {
5645 return getUntaintedAccessor$1("Node", n2, "childNodes");
5646 }
5647 function parentNode$1(n2) {
5648 return getUntaintedAccessor$1("Node", n2, "parentNode");
5649 }
5650 function parentElement$1(n2) {
5651 return getUntaintedAccessor$1("Node", n2, "parentElement");
5652 }
5653 function textContent$1(n2) {
5654 return getUntaintedAccessor$1("Node", n2, "textContent");
5655 }
5656 function contains$1(n2, other) {
5657 return getUntaintedMethod$1("Node", n2, "contains")(other);
5658 }
5659 function getRootNode$1(n2) {
5660 return getUntaintedMethod$1("Node", n2, "getRootNode")();
5661 }
5662 function host$1(n2) {
5663 if (!n2 || !("host" in n2)) return null;
5664 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
5665 }
5666 function styleSheets$1(n2) {
5667 return n2.styleSheets;
5668 }
5669 function shadowRoot$1(n2) {
5670 if (!n2 || !("shadowRoot" in n2)) return null;
5671 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
5672 }
5673 function querySelector$1(n2, selectors) {
5674 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
5675 }
5676 function querySelectorAll$1(n2, selectors) {
5677 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
5678 }
5679 function mutationObserverCtor$1() {
5680 return getUntaintedPrototype$1("MutationObserver").constructor;
5681 }
5682 function patch$1(source, name, replacement) {
5683 try {
5684 if (!(name in source)) return function() {};
5685 var original = source[name];
5686 var wrapped = replacement(original);
5687 if (typeof wrapped === "function") {
5688 wrapped.prototype = wrapped.prototype || {};
5689 Object.defineProperties(wrapped, { __rrweb_original__: {
5690 enumerable: false,
5691 value: original
5692 } });
5693 }
5694 source[name] = wrapped;
5695 return function() {
5696 source[name] = original;
5697 };
5698 } catch (e) {
5699 return function() {};
5700 }
5701 }
5702 var index$1 = {
5703 childNodes: childNodes$1,
5704 parentNode: parentNode$1,
5705 parentElement: parentElement$1,
5706 textContent: textContent$1,
5707 contains: contains$1,
5708 getRootNode: getRootNode$1,
5709 host: host$1,
5710 styleSheets: styleSheets$1,
5711 shadowRoot: shadowRoot$1,
5712 querySelector: querySelector$1,
5713 querySelectorAll: querySelectorAll$1,
5714 mutationObserver: mutationObserverCtor$1,
5715 patch: patch$1
5716 };
5717 function isElement(n2) {
5718 return n2.nodeType === n2.ELEMENT_NODE;
5719 }
5720 function isShadowRoot(n2) {
5721 var hostEl = n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
5722 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
5723 }
5724 function isNativeShadowDom(shadowRoot2) {
5725 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
5726 }
5727 function fixBrowserCompatibilityIssuesInCSS(cssText) {
5728 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
5729 return cssText;
5730 }
5731 function escapeImportStatement(rule2) {
5732 var cssText = rule2.cssText;
5733 if (cssText.split("\"").length < 3) return cssText;
5734 var statement = ["@import", "url(" + JSON.stringify(rule2.href) + ")"];
5735 if (rule2.layerName === "") statement.push("layer");
5736 else if (rule2.layerName) statement.push("layer(" + rule2.layerName + ")");
5737 if (rule2.supportsText) statement.push("supports(" + rule2.supportsText + ")");
5738 if (rule2.media.length) statement.push(rule2.media.mediaText);
5739 return statement.join(" ") + ";";
5740 }
5741 function stringifyStylesheet(s2) {
5742 try {
5743 var rules2 = s2.rules || s2.cssRules;
5744 if (!rules2) return null;
5745 var sheetHref = s2.href;
5746 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) sheetHref = s2.ownerNode.ownerDocument.location.href;
5747 return fixBrowserCompatibilityIssuesInCSS(Array.from(rules2, function(rule2) {
5748 return stringifyRule(rule2, sheetHref);
5749 }).join(""));
5750 } catch (error) {
5751 return null;
5752 }
5753 }
5754 function stringifyRule(rule2, sheetHref) {
5755 if (isCSSImportRule(rule2)) {
5756 var importStringified;
5757 try {
5758 importStringified = stringifyStylesheet(rule2.styleSheet) || escapeImportStatement(rule2);
5759 } catch (error) {
5760 importStringified = rule2.cssText;
5761 }
5762 if (rule2.styleSheet.href) return absolutifyURLs(importStringified, rule2.styleSheet.href);
5763 return importStringified;
5764 } else {
5765 var ruleStringified = rule2.cssText;
5766 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) ruleStringified = fixSafariColons(ruleStringified);
5767 if (sheetHref) return absolutifyURLs(ruleStringified, sheetHref);
5768 return ruleStringified;
5769 }
5770 }
5771 function fixSafariColons(cssStringified) {
5772 return cssStringified.replace(/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm, "$1\\$2");
5773 }
5774 function isCSSImportRule(rule2) {
5775 return "styleSheet" in rule2;
5776 }
5777 function isCSSStyleRule(rule2) {
5778 return "selectorText" in rule2;
5779 }
5780 var Mirror = /*#__PURE__*/ function() {
5781 function Mirror() {
5782 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
5783 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
5784 }
5785 var _proto = Mirror.prototype;
5786 _proto.getId = function getId(n2) {
5787 var _a2;
5788 if (!n2) return -1;
5789 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
5790 return id != null ? id : -1;
5791 };
5792 _proto.getNode = function getNode(id) {
5793 return this.idNodeMap.get(id) || null;
5794 };
5795 _proto.getIds = function getIds() {
5796 return Array.from(this.idNodeMap.keys());
5797 };
5798 _proto.getMeta = function getMeta(n2) {
5799 return this.nodeMetaMap.get(n2) || null;
5800 };
5801 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
5802 var _this = this;
5803 var id = this.getId(n2);
5804 this.idNodeMap.delete(id);
5805 if (n2.childNodes) n2.childNodes.forEach(function(childNode) {
5806 return _this.removeNodeFromMap(childNode);
5807 });
5808 };
5809 _proto.has = function has(id) {
5810 return this.idNodeMap.has(id);
5811 };
5812 _proto.hasNode = function hasNode(node2) {
5813 return this.nodeMetaMap.has(node2);
5814 };
5815 _proto.add = function add(n2, meta) {
5816 var id = meta.id;
5817 this.idNodeMap.set(id, n2);
5818 this.nodeMetaMap.set(n2, meta);
5819 };
5820 _proto.replace = function replace(id, n2) {
5821 var oldNode = this.getNode(id);
5822 if (oldNode) {
5823 var meta = this.nodeMetaMap.get(oldNode);
5824 if (meta) this.nodeMetaMap.set(n2, meta);
5825 }
5826 this.idNodeMap.set(id, n2);
5827 };
5828 _proto.reset = function reset() {
5829 this.idNodeMap = /* @__PURE__ */ new Map();
5830 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
5831 };
5832 return Mirror;
5833 }();
5834 function createMirror$2() {
5835 return new Mirror();
5836 }
5837 function maskInputValue(param) {
5838 var element = param.element;
5839 var maskInputOptions = param.maskInputOptions;
5840 var tagName = param.tagName;
5841 var type = param.type;
5842 var value = param.value;
5843 var maskInputFn = param.maskInputFn;
5844 var text = value || "";
5845 var actualType = type && toLowerCase(type);
5846 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) if (maskInputFn) text = maskInputFn(text, element);
5847 else text = "*".repeat(text.length);
5848 return text;
5849 }
5850 function toLowerCase(str) {
5851 return str.toLowerCase();
5852 }
5853 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
5854 function is2DCanvasBlank(canvas) {
5855 var ctx = canvas.getContext("2d");
5856 if (!ctx) return true;
5857 var chunkSize = 50;
5858 for (var x2 = 0; x2 < canvas.width; x2 += chunkSize) for (var y = 0; y < canvas.height; y += chunkSize) {
5859 var getImageData = ctx.getImageData;
5860 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
5861 if (new Uint32Array(originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer).some(function(pixel) {
5862 return pixel !== 0;
5863 })) return false;
5864 }
5865 return true;
5866 }
5867 function getInputType(element) {
5868 var type = element.type;
5869 return element.hasAttribute("data-rr-is-password") ? "password" : type ? toLowerCase(type) : null;
5870 }
5871 function extractFileExtension(path, baseURL) {
5872 var url;
5873 try {
5874 url = new URL(path, baseURL != null ? baseURL : window.location.href);
5875 } catch (err) {
5876 return null;
5877 }
5878 var match = url.pathname.match(/\.([0-9a-z]+)(?:$)/i);
5879 var _ref;
5880 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
5881 }
5882 function extractOrigin(url) {
5883 var origin = "";
5884 if (url.indexOf("//") > -1) origin = url.split("/").slice(0, 3).join("/");
5885 else origin = url.split("/")[0];
5886 origin = origin.split("?")[0];
5887 return origin;
5888 }
5889 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
5890 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
5891 var URL_WWW_MATCH = /^www\..*/i;
5892 var DATA_URI = /^(data:)([^,]*),(.*)/i;
5893 function absolutifyURLs(cssText, href) {
5894 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
5895 var filePath = path1 || path2 || path3;
5896 var maybeQuote = quote1 || quote2 || "";
5897 if (!filePath) return origin;
5898 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) return "url(" + maybeQuote + filePath + maybeQuote + ")";
5899 if (DATA_URI.test(filePath)) return "url(" + maybeQuote + filePath + maybeQuote + ")";
5900 if (filePath[0] === "/") return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
5901 var stack = href.split("/");
5902 var parts = filePath.split("/");
5903 stack.pop();
5904 for (var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;) {
5905 var part = _step.value;
5906 if (part === ".") continue;
5907 else if (part === "..") stack.pop();
5908 else stack.push(part);
5909 }
5910 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
5911 });
5912 }
5913 function normalizeCssString(cssText, _testNoPxNorm) {
5914 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
5915 if (_testNoPxNorm) return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
5916 else return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
5917 }
5918 function splitCssText(cssText, style, _testNoPxNorm) {
5919 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
5920 var childNodes2 = Array.from(style.childNodes);
5921 var splits = [];
5922 var iterCount = 0;
5923 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
5924 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
5925 var normFactor = cssTextNorm.length / cssText.length;
5926 for (var i2 = 1; i2 < childNodes2.length; i2++) if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
5927 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
5928 var jLimit = 100;
5929 var j = 3;
5930 for (; j < textContentNorm.length; j++) {
5931 if (textContentNorm[j].match(/[a-zA-Z0-9]/) || textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) continue;
5932 break;
5933 }
5934 for (; j < textContentNorm.length; j++) {
5935 var startSubstring = textContentNorm.substring(0, j);
5936 var cssNormSplits = cssTextNorm.split(startSubstring);
5937 var splitNorm = -1;
5938 if (cssNormSplits.length === 2) splitNorm = cssNormSplits[0].length;
5939 else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") splitNorm = cssTextNorm.indexOf(startSubstring, 1);
5940 else if (cssNormSplits.length === 1) {
5941 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
5942 cssNormSplits = cssTextNorm.split(startSubstring);
5943 if (cssNormSplits.length <= 1) {
5944 splits.push(cssText);
5945 return splits;
5946 }
5947 j = jLimit + 1;
5948 } else if (j === textContentNorm.length - 1) splitNorm = cssTextNorm.indexOf(startSubstring);
5949 if (cssNormSplits.length >= 2 && j > jLimit) {
5950 var prevTextContent = childNodes2[i2 - 1].textContent;
5951 if (prevTextContent && typeof prevTextContent === "string") {
5952 var prevMinLength = normalizeCssString(prevTextContent).length;
5953 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
5954 }
5955 if (splitNorm === -1) splitNorm = cssNormSplits[0].length;
5956 }
5957 if (splitNorm !== -1) {
5958 var k = Math.floor(splitNorm / normFactor);
5959 for (; k > 0 && k < cssText.length;) {
5960 iterCount += 1;
5961 if (iterCount > 50 * childNodes2.length) {
5962 splits.push(cssText);
5963 return splits;
5964 }
5965 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
5966 if (normPart.length === splitNorm) {
5967 splits.push(cssText.substring(0, k));
5968 cssText = cssText.substring(k);
5969 cssTextNorm = cssTextNorm.substring(splitNorm);
5970 break;
5971 } else if (normPart.length < splitNorm) k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
5972 else k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
5973 }
5974 break;
5975 }
5976 }
5977 }
5978 }
5979 splits.push(cssText);
5980 return splits;
5981 }
5982 function markCssSplits(cssText, style) {
5983 return splitCssText(cssText, style).join("/* rr_split */");
5984 }
5985 var _id = 1;
5986 var tagNameRegex = /* @__PURE__ */ new RegExp("[^a-z0-9-_:]");
5987 var IGNORED_NODE = -2;
5988 function genId() {
5989 return _id++;
5990 }
5991 function getValidTagName$1(element) {
5992 if (_instanceof(element, HTMLFormElement)) return "form";
5993 var processedTagName = toLowerCase(element.tagName);
5994 if (tagNameRegex.test(processedTagName)) return "div";
5995 return processedTagName;
5996 }
5997 var canvasService;
5998 var canvasCtx;
5999 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
6000 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
6001 function getAbsoluteSrcsetString(doc, attributeValue) {
6002 if (attributeValue.trim() === "") return attributeValue;
6003 var pos = 0;
6004 function collectCharacters(regEx) {
6005 var chars2;
6006 var match = regEx.exec(attributeValue.substring(pos));
6007 if (match) {
6008 chars2 = match[0];
6009 pos += chars2.length;
6010 return chars2;
6011 }
6012 return "";
6013 }
6014 var output = [];
6015 while (true) {
6016 collectCharacters(SRCSET_COMMAS_OR_SPACES);
6017 if (pos >= attributeValue.length) break;
6018 var url = collectCharacters(SRCSET_NOT_SPACES);
6019 if (url.slice(-1) === ",") {
6020 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
6021 output.push(url);
6022 } else {
6023 var descriptorsStr = "";
6024 url = absoluteToDoc(doc, url);
6025 var inParens = false;
6026 while (true) {
6027 var c2 = attributeValue.charAt(pos);
6028 if (c2 === "") {
6029 output.push((url + descriptorsStr).trim());
6030 break;
6031 } else if (!inParens) {
6032 if (c2 === ",") {
6033 pos += 1;
6034 output.push((url + descriptorsStr).trim());
6035 break;
6036 } else if (c2 === "(") inParens = true;
6037 } else if (c2 === ")") inParens = false;
6038 descriptorsStr += c2;
6039 pos += 1;
6040 }
6041 }
6042 }
6043 return output.join(", ");
6044 }
6045 var cachedDocument = /* @__PURE__ */ new WeakMap();
6046 function absoluteToDoc(doc, attributeValue) {
6047 if (!attributeValue || attributeValue.trim() === "") return attributeValue;
6048 return getHref(doc, attributeValue);
6049 }
6050 function isSVGElement(el) {
6051 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
6052 }
6053 function getHref(doc, customHref) {
6054 var a2 = cachedDocument.get(doc);
6055 if (!a2) {
6056 a2 = doc.createElement("a");
6057 cachedDocument.set(doc, a2);
6058 }
6059 if (!customHref) customHref = "";
6060 else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) return customHref;
6061 a2.setAttribute("href", customHref);
6062 return a2.href;
6063 }
6064 function transformAttribute(doc, tagName, name, value) {
6065 if (!value) return value;
6066 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) return absoluteToDoc(doc, value);
6067 else if (name === "xlink:href" && value[0] !== "#") return absoluteToDoc(doc, value);
6068 else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) return absoluteToDoc(doc, value);
6069 else if (name === "srcset") return getAbsoluteSrcsetString(doc, value);
6070 else if (name === "style") return absolutifyURLs(value, getHref(doc));
6071 else if (tagName === "object" && name === "data") return absoluteToDoc(doc, value);
6072 return value;
6073 }
6074 function ignoreAttribute(tagName, name, _value) {
6075 return (tagName === "video" || tagName === "audio") && name === "autoplay";
6076 }
6077 function _isBlockedElement(element, blockClass, blockSelector) {
6078 try {
6079 if (typeof blockClass === "string") {
6080 if (element.classList.contains(blockClass)) return true;
6081 } else for (var eIndex = element.classList.length; eIndex--;) {
6082 var className = element.classList[eIndex];
6083 if (blockClass.test(className)) return true;
6084 }
6085 if (blockSelector) return element.matches(blockSelector);
6086 } catch (e2) {}
6087 return false;
6088 }
6089 function classMatchesRegex(node2, regex, checkAncestors) {
6090 if (!node2) return false;
6091 if (node2.nodeType !== node2.ELEMENT_NODE) {
6092 if (!checkAncestors) return false;
6093 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
6094 }
6095 for (var eIndex = node2.classList.length; eIndex--;) {
6096 var className = node2.classList[eIndex];
6097 if (regex.test(className)) return true;
6098 }
6099 if (!checkAncestors) return false;
6100 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
6101 }
6102 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
6103 var el;
6104 if (isElement(node2)) {
6105 el = node2;
6106 if (!index$1.childNodes(el).length) return false;
6107 } else if (index$1.parentElement(node2) === null) return false;
6108 else el = index$1.parentElement(node2);
6109 try {
6110 if (typeof maskTextClass === "string") {
6111 if (checkAncestors) {
6112 if (el.closest("." + maskTextClass)) return true;
6113 } else if (el.classList.contains(maskTextClass)) return true;
6114 } else if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
6115 if (maskTextSelector) {
6116 if (checkAncestors) {
6117 if (el.closest(maskTextSelector)) return true;
6118 } else if (el.matches(maskTextSelector)) return true;
6119 }
6120 } catch (e2) {}
6121 return false;
6122 }
6123 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
6124 var win = iframeEl.contentWindow;
6125 if (!win) return;
6126 var fired = false;
6127 var readyState;
6128 try {
6129 readyState = win.document.readyState;
6130 } catch (error) {
6131 return;
6132 }
6133 if (readyState !== "complete") {
6134 var timer = setTimeout(function() {
6135 if (!fired) {
6136 listener();
6137 fired = true;
6138 }
6139 }, iframeLoadTimeout);
6140 iframeEl.addEventListener("load", function() {
6141 clearTimeout(timer);
6142 fired = true;
6143 listener();
6144 });
6145 return;
6146 }
6147 var blankUrl = "about:blank";
6148 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
6149 setTimeout(listener, 0);
6150 return iframeEl.addEventListener("load", listener);
6151 }
6152 iframeEl.addEventListener("load", listener);
6153 }
6154 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
6155 var fired = false;
6156 var styleSheetLoaded;
6157 try {
6158 styleSheetLoaded = link.sheet;
6159 } catch (error) {
6160 return;
6161 }
6162 if (styleSheetLoaded) return;
6163 var timer = setTimeout(function() {
6164 if (!fired) {
6165 listener();
6166 fired = true;
6167 }
6168 }, styleSheetLoadTimeout);
6169 link.addEventListener("load", function() {
6170 clearTimeout(timer);
6171 fired = true;
6172 listener();
6173 });
6174 }
6175 function serializeNode(n2, options) {
6176 var doc = options.doc;
6177 var mirror2 = options.mirror;
6178 var blockClass = options.blockClass;
6179 var blockSelector = options.blockSelector;
6180 var needsMask = options.needsMask;
6181 var inlineStylesheet = options.inlineStylesheet;
6182 var _options_maskInputOptions = options.maskInputOptions;
6183 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6184 var maskTextFn = options.maskTextFn;
6185 var maskInputFn = options.maskInputFn;
6186 var _options_dataURLOptions = options.dataURLOptions;
6187 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6188 var inlineImages = options.inlineImages;
6189 var recordCanvas = options.recordCanvas;
6190 var keepIframeSrcFn = options.keepIframeSrcFn;
6191 var _options_newlyAddedElement = options.newlyAddedElement;
6192 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6193 var _options_cssCaptured = options.cssCaptured;
6194 var cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
6195 var rootId = getRootId(doc, mirror2);
6196 switch (n2.nodeType) {
6197 case n2.DOCUMENT_NODE: if (n2.compatMode !== "CSS1Compat") return {
6198 type: NodeType$3.Document,
6199 childNodes: [],
6200 compatMode: n2.compatMode
6201 };
6202 else return {
6203 type: NodeType$3.Document,
6204 childNodes: []
6205 };
6206 case n2.DOCUMENT_TYPE_NODE: return {
6207 type: NodeType$3.DocumentType,
6208 name: n2.name,
6209 publicId: n2.publicId,
6210 systemId: n2.systemId,
6211 rootId
6212 };
6213 case n2.ELEMENT_NODE: return serializeElementNode(n2, {
6214 doc,
6215 blockClass,
6216 blockSelector,
6217 inlineStylesheet,
6218 maskInputOptions,
6219 maskInputFn,
6220 dataURLOptions,
6221 inlineImages,
6222 recordCanvas,
6223 keepIframeSrcFn,
6224 newlyAddedElement,
6225 rootId
6226 });
6227 case n2.TEXT_NODE: return serializeTextNode(n2, {
6228 doc,
6229 needsMask,
6230 maskTextFn,
6231 rootId,
6232 cssCaptured
6233 });
6234 case n2.CDATA_SECTION_NODE: return {
6235 type: NodeType$3.CDATA,
6236 textContent: "",
6237 rootId
6238 };
6239 case n2.COMMENT_NODE: return {
6240 type: NodeType$3.Comment,
6241 textContent: index$1.textContent(n2) || "",
6242 rootId
6243 };
6244 default: return false;
6245 }
6246 }
6247 function getRootId(doc, mirror2) {
6248 if (!mirror2.hasNode(doc)) return void 0;
6249 var docId = mirror2.getId(doc);
6250 return docId === 1 ? void 0 : docId;
6251 }
6252 function serializeTextNode(n2, options) {
6253 var needsMask = options.needsMask;
6254 var maskTextFn = options.maskTextFn;
6255 var rootId = options.rootId;
6256 var cssCaptured = options.cssCaptured;
6257 var parent = index$1.parentNode(n2);
6258 var parentTagName = parent && parent.tagName;
6259 var textContent2 = "";
6260 var isStyle = parentTagName === "STYLE" ? true : void 0;
6261 var isScript = parentTagName === "SCRIPT" ? true : void 0;
6262 if (isScript) textContent2 = "SCRIPT_PLACEHOLDER";
6263 else if (!cssCaptured) {
6264 textContent2 = index$1.textContent(n2);
6265 if (isStyle && textContent2) textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
6266 }
6267 if (!isStyle && !isScript && textContent2 && needsMask) textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
6268 return {
6269 type: NodeType$3.Text,
6270 textContent: textContent2 || "",
6271 rootId
6272 };
6273 }
6274 function serializeElementNode(n2, options) {
6275 var doc = options.doc;
6276 var blockClass = options.blockClass;
6277 var blockSelector = options.blockSelector;
6278 var inlineStylesheet = options.inlineStylesheet;
6279 var _options_maskInputOptions = options.maskInputOptions;
6280 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6281 var maskInputFn = options.maskInputFn;
6282 var _options_dataURLOptions = options.dataURLOptions;
6283 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6284 var inlineImages = options.inlineImages;
6285 var recordCanvas = options.recordCanvas;
6286 var keepIframeSrcFn = options.keepIframeSrcFn;
6287 var _options_newlyAddedElement = options.newlyAddedElement;
6288 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6289 var rootId = options.rootId;
6290 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
6291 var tagName = getValidTagName$1(n2);
6292 var attributes = {};
6293 var len = n2.attributes.length;
6294 for (var i2 = 0; i2 < len; i2++) {
6295 var attr = n2.attributes[i2];
6296 if (!ignoreAttribute(tagName, attr.name, attr.value)) attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
6297 }
6298 if (tagName === "link" && inlineStylesheet) {
6299 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
6300 return s2.href === n2.href;
6301 });
6302 var cssText = null;
6303 if (stylesheet) cssText = stringifyStylesheet(stylesheet);
6304 if (cssText) {
6305 delete attributes.rel;
6306 delete attributes.href;
6307 attributes._cssText = cssText;
6308 }
6309 }
6310 if (tagName === "style" && n2.sheet) {
6311 var cssText1 = stringifyStylesheet(n2.sheet);
6312 if (cssText1) {
6313 if (n2.childNodes.length > 1) cssText1 = markCssSplits(cssText1, n2);
6314 attributes._cssText = cssText1;
6315 }
6316 }
6317 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
6318 var value = n2.value;
6319 var checked = n2.checked;
6320 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) attributes.value = maskInputValue({
6321 element: n2,
6322 type: getInputType(n2),
6323 tagName,
6324 value,
6325 maskInputOptions,
6326 maskInputFn
6327 });
6328 else if (checked) attributes.checked = checked;
6329 }
6330 if (tagName === "option") if (n2.selected && !maskInputOptions["select"]) attributes.selected = true;
6331 else delete attributes.selected;
6332 if (tagName === "dialog" && n2.open) attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
6333 if (tagName === "canvas" && recordCanvas) {
6334 if (n2.__context === "2d") {
6335 if (!is2DCanvasBlank(n2)) attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6336 } else if (!("__context" in n2)) {
6337 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6338 var blankCanvas = doc.createElement("canvas");
6339 blankCanvas.width = n2.width;
6340 blankCanvas.height = n2.height;
6341 if (canvasDataURL !== blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality)) attributes.rr_dataURL = canvasDataURL;
6342 }
6343 }
6344 if (tagName === "img" && inlineImages) {
6345 if (!canvasService) {
6346 canvasService = doc.createElement("canvas");
6347 canvasCtx = canvasService.getContext("2d");
6348 }
6349 var image = n2;
6350 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
6351 var priorCrossOrigin = image.crossOrigin;
6352 var recordInlineImage = function() {
6353 image.removeEventListener("load", recordInlineImage);
6354 try {
6355 canvasService.width = image.naturalWidth;
6356 canvasService.height = image.naturalHeight;
6357 canvasCtx.drawImage(image, 0, 0);
6358 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
6359 } catch (err) {
6360 if (image.crossOrigin !== "anonymous") {
6361 image.crossOrigin = "anonymous";
6362 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
6363 else image.addEventListener("load", recordInlineImage);
6364 return;
6365 } else console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
6366 }
6367 if (image.crossOrigin === "anonymous") priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
6368 };
6369 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
6370 else image.addEventListener("load", recordInlineImage);
6371 }
6372 if (tagName === "audio" || tagName === "video") {
6373 var mediaAttributes = attributes;
6374 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
6375 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
6376 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
6377 mediaAttributes.rr_mediaMuted = n2.muted;
6378 mediaAttributes.rr_mediaLoop = n2.loop;
6379 mediaAttributes.rr_mediaVolume = n2.volume;
6380 }
6381 if (!newlyAddedElement) {
6382 if (n2.scrollLeft) attributes.rr_scrollLeft = n2.scrollLeft;
6383 if (n2.scrollTop) attributes.rr_scrollTop = n2.scrollTop;
6384 }
6385 if (needBlock) {
6386 var _n2_getBoundingClientRect = n2.getBoundingClientRect();
6387 var width = _n2_getBoundingClientRect.width;
6388 var height = _n2_getBoundingClientRect.height;
6389 attributes = {
6390 class: attributes.class,
6391 rr_width: "" + width + "px",
6392 rr_height: "" + height + "px"
6393 };
6394 }
6395 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
6396 if (!n2.contentDocument) attributes.rr_src = attributes.src;
6397 delete attributes.src;
6398 }
6399 var isCustomElement;
6400 try {
6401 if (customElements.get(tagName)) isCustomElement = true;
6402 } catch (e2) {}
6403 return {
6404 type: NodeType$3.Element,
6405 tagName,
6406 attributes,
6407 childNodes: [],
6408 isSVG: isSVGElement(n2) || void 0,
6409 needBlock,
6410 rootId,
6411 isCustom: isCustomElement
6412 };
6413 }
6414 function lowerIfExists(maybeAttr) {
6415 if (maybeAttr === void 0 || maybeAttr === null) return "";
6416 else return maybeAttr.toLowerCase();
6417 }
6418 function slimDOMExcluded(sn, slimDOMOptions) {
6419 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) return true;
6420 else if (sn.type === NodeType$3.Element) {
6421 if (slimDOMOptions.script && (sn.tagName === "script" || sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) return true;
6422 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"))) return true;
6423 else if (sn.tagName === "meta") {
6424 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) return true;
6425 else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) return true;
6426 else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) return true;
6427 else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) return true;
6428 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:/))) return true;
6429 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")) return true;
6430 }
6431 }
6432 return false;
6433 }
6434 function serializeNodeWithId(n2, options) {
6435 var doc = options.doc;
6436 var mirror2 = options.mirror;
6437 var blockClass = options.blockClass;
6438 var blockSelector = options.blockSelector;
6439 var maskTextClass = options.maskTextClass;
6440 var maskTextSelector = options.maskTextSelector;
6441 var _options_skipChild = options.skipChild;
6442 var skipChild = _options_skipChild === void 0 ? false : _options_skipChild;
6443 var _options_inlineStylesheet = options.inlineStylesheet;
6444 var inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet;
6445 var _options_maskInputOptions = options.maskInputOptions;
6446 var maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions;
6447 var maskTextFn = options.maskTextFn;
6448 var maskInputFn = options.maskInputFn;
6449 var slimDOMOptions = options.slimDOMOptions;
6450 var _options_dataURLOptions = options.dataURLOptions;
6451 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
6452 var _options_inlineImages = options.inlineImages;
6453 var inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages;
6454 var _options_recordCanvas = options.recordCanvas;
6455 var recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas;
6456 var onSerialize = options.onSerialize;
6457 var onIframeLoad = options.onIframeLoad;
6458 var _options_iframeLoadTimeout = options.iframeLoadTimeout;
6459 var iframeLoadTimeout = _options_iframeLoadTimeout === void 0 ? 5e3 : _options_iframeLoadTimeout;
6460 var onStylesheetLoad = options.onStylesheetLoad;
6461 var _options_stylesheetLoadTimeout = options.stylesheetLoadTimeout;
6462 var stylesheetLoadTimeout = _options_stylesheetLoadTimeout === void 0 ? 5e3 : _options_stylesheetLoadTimeout;
6463 var _options_keepIframeSrcFn = options.keepIframeSrcFn;
6464 var keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
6465 return false;
6466 } : _options_keepIframeSrcFn;
6467 var _options_newlyAddedElement = options.newlyAddedElement;
6468 var newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement;
6469 var _options_cssCaptured = options.cssCaptured;
6470 var cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
6471 var needsMask = options.needsMask;
6472 var _options_preserveWhiteSpace = options.preserveWhiteSpace;
6473 var preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
6474 if (!needsMask) needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, needsMask === void 0);
6475 var _serializedNode = serializeNode(n2, {
6476 doc,
6477 mirror: mirror2,
6478 blockClass,
6479 blockSelector,
6480 needsMask,
6481 inlineStylesheet,
6482 maskInputOptions,
6483 maskTextFn,
6484 maskInputFn,
6485 dataURLOptions,
6486 inlineImages,
6487 recordCanvas,
6488 keepIframeSrcFn,
6489 newlyAddedElement,
6490 cssCaptured
6491 });
6492 if (!_serializedNode) {
6493 console.warn(n2, "not serialized");
6494 return null;
6495 }
6496 var id;
6497 if (mirror2.hasNode(n2)) id = mirror2.getId(n2);
6498 else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) id = IGNORED_NODE;
6499 else id = genId();
6500 var serializedNode = Object.assign(_serializedNode, { id });
6501 mirror2.add(n2, serializedNode);
6502 if (id === IGNORED_NODE) return null;
6503 if (onSerialize) onSerialize(n2);
6504 var recordChild = !skipChild;
6505 if (serializedNode.type === NodeType$3.Element) {
6506 recordChild = recordChild && !serializedNode.needBlock;
6507 delete serializedNode.needBlock;
6508 var shadowRootEl = index$1.shadowRoot(n2);
6509 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
6510 }
6511 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
6512 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") preserveWhiteSpace = false;
6513 var bypassOptions = {
6514 doc,
6515 mirror: mirror2,
6516 blockClass,
6517 blockSelector,
6518 needsMask,
6519 maskTextClass,
6520 maskTextSelector,
6521 skipChild,
6522 inlineStylesheet,
6523 maskInputOptions,
6524 maskTextFn,
6525 maskInputFn,
6526 slimDOMOptions,
6527 dataURLOptions,
6528 inlineImages,
6529 recordCanvas,
6530 preserveWhiteSpace,
6531 onSerialize,
6532 onIframeLoad,
6533 iframeLoadTimeout,
6534 onStylesheetLoad,
6535 stylesheetLoadTimeout,
6536 keepIframeSrcFn,
6537 cssCaptured: false
6538 };
6539 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0);
6540 else {
6541 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") bypassOptions.cssCaptured = true;
6542 for (var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;) {
6543 var childN = _step.value;
6544 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
6545 if (serializedChildNode) serializedNode.childNodes.push(serializedChildNode);
6546 }
6547 }
6548 var shadowRootEl1 = null;
6549 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) for (var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;) {
6550 var childN1 = _step1.value;
6551 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
6552 if (serializedChildNode1) {
6553 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
6554 serializedNode.childNodes.push(serializedChildNode1);
6555 }
6556 }
6557 }
6558 var parent = index$1.parentNode(n2);
6559 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) serializedNode.isShadow = true;
6560 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") onceIframeLoaded(n2, function() {
6561 var iframeDoc = n2.contentDocument;
6562 if (iframeDoc && onIframeLoad) {
6563 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
6564 doc: iframeDoc,
6565 mirror: mirror2,
6566 blockClass,
6567 blockSelector,
6568 needsMask,
6569 maskTextClass,
6570 maskTextSelector,
6571 skipChild: false,
6572 inlineStylesheet,
6573 maskInputOptions,
6574 maskTextFn,
6575 maskInputFn,
6576 slimDOMOptions,
6577 dataURLOptions,
6578 inlineImages,
6579 recordCanvas,
6580 preserveWhiteSpace,
6581 onSerialize,
6582 onIframeLoad,
6583 iframeLoadTimeout,
6584 onStylesheetLoad,
6585 stylesheetLoadTimeout,
6586 keepIframeSrcFn
6587 });
6588 if (serializedIframeNode) onIframeLoad(n2, serializedIframeNode);
6589 }
6590 }, iframeLoadTimeout);
6591 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")) onceStylesheetLoaded(n2, function() {
6592 if (onStylesheetLoad) {
6593 var serializedLinkNode = serializeNodeWithId(n2, {
6594 doc,
6595 mirror: mirror2,
6596 blockClass,
6597 blockSelector,
6598 needsMask,
6599 maskTextClass,
6600 maskTextSelector,
6601 skipChild: false,
6602 inlineStylesheet,
6603 maskInputOptions,
6604 maskTextFn,
6605 maskInputFn,
6606 slimDOMOptions,
6607 dataURLOptions,
6608 inlineImages,
6609 recordCanvas,
6610 preserveWhiteSpace,
6611 onSerialize,
6612 onIframeLoad,
6613 iframeLoadTimeout,
6614 onStylesheetLoad,
6615 stylesheetLoadTimeout,
6616 keepIframeSrcFn
6617 });
6618 if (serializedLinkNode) onStylesheetLoad(n2, serializedLinkNode);
6619 }
6620 }, stylesheetLoadTimeout);
6621 return serializedNode;
6622 }
6623 function snapshot(n2, options) {
6624 var _ref = options || {};
6625 var tmp = _ref.mirror;
6626 var mirror2 = tmp === void 0 ? new Mirror() : tmp;
6627 var _ref_blockClass = _ref.blockClass;
6628 var blockClass = _ref_blockClass === void 0 ? "rr-block" : _ref_blockClass;
6629 var _ref_blockSelector = _ref.blockSelector;
6630 var blockSelector = _ref_blockSelector === void 0 ? null : _ref_blockSelector;
6631 var _ref_maskTextClass = _ref.maskTextClass;
6632 var maskTextClass = _ref_maskTextClass === void 0 ? "rr-mask" : _ref_maskTextClass;
6633 var _ref_maskTextSelector = _ref.maskTextSelector;
6634 var maskTextSelector = _ref_maskTextSelector === void 0 ? null : _ref_maskTextSelector;
6635 var _ref_inlineStylesheet = _ref.inlineStylesheet;
6636 var inlineStylesheet = _ref_inlineStylesheet === void 0 ? true : _ref_inlineStylesheet;
6637 var _ref_inlineImages = _ref.inlineImages;
6638 var inlineImages = _ref_inlineImages === void 0 ? false : _ref_inlineImages;
6639 var _ref_recordCanvas = _ref.recordCanvas;
6640 var recordCanvas = _ref_recordCanvas === void 0 ? false : _ref_recordCanvas;
6641 var _ref_maskAllInputs = _ref.maskAllInputs;
6642 var maskAllInputs = _ref_maskAllInputs === void 0 ? false : _ref_maskAllInputs;
6643 var maskTextFn = _ref.maskTextFn;
6644 var maskInputFn = _ref.maskInputFn;
6645 var _ref_slimDOM = _ref.slimDOM;
6646 var slimDOM = _ref_slimDOM === void 0 ? false : _ref_slimDOM;
6647 var dataURLOptions = _ref.dataURLOptions;
6648 var preserveWhiteSpace = _ref.preserveWhiteSpace;
6649 var onSerialize = _ref.onSerialize;
6650 var onIframeLoad = _ref.onIframeLoad;
6651 var iframeLoadTimeout = _ref.iframeLoadTimeout;
6652 var onStylesheetLoad = _ref.onStylesheetLoad;
6653 var stylesheetLoadTimeout = _ref.stylesheetLoadTimeout;
6654 var _ref_keepIframeSrcFn = _ref.keepIframeSrcFn;
6655 return serializeNodeWithId(n2, {
6656 doc: n2,
6657 mirror: mirror2,
6658 blockClass,
6659 blockSelector,
6660 maskTextClass,
6661 maskTextSelector,
6662 skipChild: false,
6663 inlineStylesheet,
6664 maskInputOptions: maskAllInputs === true ? {
6665 color: true,
6666 date: true,
6667 "datetime-local": true,
6668 email: true,
6669 month: true,
6670 number: true,
6671 range: true,
6672 search: true,
6673 tel: true,
6674 text: true,
6675 time: true,
6676 url: true,
6677 week: true,
6678 textarea: true,
6679 select: true,
6680 password: true,
6681 hidden: true
6682 } : maskAllInputs === false ? { password: true } : maskAllInputs,
6683 maskTextFn,
6684 maskInputFn,
6685 slimDOMOptions: slimDOM === true || slimDOM === "all" ? {
6686 script: true,
6687 comment: true,
6688 headFavicon: true,
6689 headWhitespace: true,
6690 headMetaDescKeywords: slimDOM === "all",
6691 headMetaSocial: true,
6692 headMetaRobots: true,
6693 headMetaHttpEquiv: true,
6694 headMetaAuthorship: true,
6695 headMetaVerification: true
6696 } : slimDOM === false ? {} : slimDOM,
6697 dataURLOptions,
6698 inlineImages,
6699 recordCanvas,
6700 preserveWhiteSpace,
6701 onSerialize,
6702 onIframeLoad,
6703 iframeLoadTimeout,
6704 onStylesheetLoad,
6705 stylesheetLoadTimeout,
6706 keepIframeSrcFn: _ref_keepIframeSrcFn === void 0 ? function() {
6707 return false;
6708 } : _ref_keepIframeSrcFn,
6709 newlyAddedElement: false
6710 });
6711 }
6712 function getDefaultExportFromCjs$1(x2) {
6713 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
6714 }
6715 function getAugmentedNamespace$1(n2) {
6716 if (n2.__esModule) return n2;
6717 var f2 = n2.default;
6718 if (typeof f2 == "function") {
6719 var a2 = function a22() {
6720 if (_instanceof(this, a22)) return Reflect.construct(f2, arguments, this.constructor);
6721 return f2.apply(this, arguments);
6722 };
6723 a2.prototype = f2.prototype;
6724 } else a2 = {};
6725 Object.defineProperty(a2, "__esModule", { value: true });
6726 Object.keys(n2).forEach(function(k) {
6727 var d = Object.getOwnPropertyDescriptor(n2, k);
6728 Object.defineProperty(a2, k, d.get ? d : {
6729 enumerable: true,
6730 get: function get() {
6731 return n2[k];
6732 }
6733 });
6734 });
6735 return a2;
6736 }
6737 var picocolors_browser$1 = { exports: {} };
6738 var x$1 = String;
6739 var create$1 = function create$1() {
6740 return {
6741 isColorSupported: false,
6742 reset: x$1,
6743 bold: x$1,
6744 dim: x$1,
6745 italic: x$1,
6746 underline: x$1,
6747 inverse: x$1,
6748 hidden: x$1,
6749 strikethrough: x$1,
6750 black: x$1,
6751 red: x$1,
6752 green: x$1,
6753 yellow: x$1,
6754 blue: x$1,
6755 magenta: x$1,
6756 cyan: x$1,
6757 white: x$1,
6758 gray: x$1,
6759 bgBlack: x$1,
6760 bgRed: x$1,
6761 bgGreen: x$1,
6762 bgYellow: x$1,
6763 bgBlue: x$1,
6764 bgMagenta: x$1,
6765 bgCyan: x$1,
6766 bgWhite: x$1
6767 };
6768 };
6769 picocolors_browser$1.exports = create$1();
6770 picocolors_browser$1.exports.createColors = create$1;
6771 var picocolors_browserExports$1 = picocolors_browser$1.exports;
6772 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(/* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
6773 __proto__: null,
6774 default: {}
6775 }, Symbol.toStringTag, { value: "Module" })));
6776 var pico$1 = picocolors_browserExports$1;
6777 var terminalHighlight$1$1 = require$$2$1;
6778 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
6779 _inherits(CssSyntaxError, Error1);
6780 function CssSyntaxError(message, line, column, source, file, plugin22) {
6781 var _this = Error1.call(this, message) || this;
6782 _this.name = "CssSyntaxError";
6783 _this.reason = message;
6784 if (file) _this.file = file;
6785 if (source) _this.source = source;
6786 if (plugin22) _this.plugin = plugin22;
6787 if (typeof line !== "undefined" && typeof column !== "undefined") if (typeof line === "number") {
6788 _this.line = line;
6789 _this.column = column;
6790 } else {
6791 _this.line = line.line;
6792 _this.column = line.column;
6793 _this.endLine = column.line;
6794 _this.endColumn = column.column;
6795 }
6796 _this.setMessage();
6797 if (Error.captureStackTrace) Error.captureStackTrace(_this, CssSyntaxError);
6798 return _this;
6799 }
6800 var _proto = CssSyntaxError.prototype;
6801 _proto.setMessage = function setMessage() {
6802 this.message = this.plugin ? this.plugin + ": " : "";
6803 this.message += this.file ? this.file : "<css input>";
6804 if (typeof this.line !== "undefined") this.message += ":" + this.line + ":" + this.column;
6805 this.message += ": " + this.reason;
6806 };
6807 _proto.showSourceCode = function showSourceCode(color) {
6808 var _this = this;
6809 if (!this.source) return "";
6810 var css = this.source;
6811 if (color == null) color = pico$1.isColorSupported;
6812 if (terminalHighlight$1$1) {
6813 if (color) css = terminalHighlight$1$1(css);
6814 }
6815 var lines = css.split(/\r?\n/);
6816 var start = Math.max(this.line - 3, 0);
6817 var end = Math.min(this.line + 2, lines.length);
6818 var maxWidth = String(end).length;
6819 var mark;
6820 var aside;
6821 if (color) {
6822 var _pico$1_createColors = pico$1.createColors(true);
6823 var bold = _pico$1_createColors.bold;
6824 var gray = _pico$1_createColors.gray;
6825 var red = _pico$1_createColors.red;
6826 mark = function(text) {
6827 return bold(red(text));
6828 };
6829 aside = function(text) {
6830 return gray(text);
6831 };
6832 } else mark = aside = function(str) {
6833 return str;
6834 };
6835 return lines.slice(start, end).map(function(line, index2) {
6836 var number = start + 1 + index2;
6837 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
6838 if (number === _this.line) {
6839 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
6840 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
6841 }
6842 return " " + aside(gutter) + line;
6843 }).join("\n");
6844 };
6845 _proto.toString = function toString() {
6846 var code = this.showSourceCode();
6847 if (code) code = "\n\n" + code + "\n";
6848 return this.name + ": " + this.message + code;
6849 };
6850 return CssSyntaxError;
6851 }(_wrap_native_super(Error));
6852 var cssSyntaxError$1 = CssSyntaxError$3$1;
6853 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
6854 var symbols$1 = {};
6855 symbols$1.isClean = Symbol("isClean");
6856 symbols$1.my = Symbol("my");
6857 var DEFAULT_RAW$1 = {
6858 after: "\n",
6859 beforeClose: "\n",
6860 beforeComment: "\n",
6861 beforeDecl: "\n",
6862 beforeOpen: " ",
6863 beforeRule: "\n",
6864 colon: ": ",
6865 commentLeft: " ",
6866 commentRight: " ",
6867 emptyBody: "",
6868 indent: " ",
6869 semicolon: false
6870 };
6871 function capitalize$1(str) {
6872 return str[0].toUpperCase() + str.slice(1);
6873 }
6874 var Stringifier$2$1 = /*#__PURE__*/ function() {
6875 function Stringifier(builder) {
6876 this.builder = builder;
6877 }
6878 var _proto = Stringifier.prototype;
6879 _proto.atrule = function atrule(node2, semicolon) {
6880 var name = "@" + node2.name;
6881 var params = node2.params ? this.rawValue(node2, "params") : "";
6882 if (typeof node2.raws.afterName !== "undefined") name += node2.raws.afterName;
6883 else if (params) name += " ";
6884 if (node2.nodes) this.block(node2, name + params);
6885 else {
6886 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
6887 this.builder(name + params + end, node2);
6888 }
6889 };
6890 _proto.beforeAfter = function beforeAfter(node2, detect) {
6891 var value;
6892 if (node2.type === "decl") value = this.raw(node2, null, "beforeDecl");
6893 else if (node2.type === "comment") value = this.raw(node2, null, "beforeComment");
6894 else if (detect === "before") value = this.raw(node2, null, "beforeRule");
6895 else value = this.raw(node2, null, "beforeClose");
6896 var buf = node2.parent;
6897 var depth = 0;
6898 while (buf && buf.type !== "root") {
6899 depth += 1;
6900 buf = buf.parent;
6901 }
6902 if (value.includes("\n")) {
6903 var indent = this.raw(node2, null, "indent");
6904 if (indent.length) for (var step = 0; step < depth; step++) value += indent;
6905 }
6906 return value;
6907 };
6908 _proto.block = function block(node2, start) {
6909 var between = this.raw(node2, "between", "beforeOpen");
6910 this.builder(start + between + "{", node2, "start");
6911 var after;
6912 if (node2.nodes && node2.nodes.length) {
6913 this.body(node2);
6914 after = this.raw(node2, "after");
6915 } else after = this.raw(node2, "after", "emptyBody");
6916 if (after) this.builder(after);
6917 this.builder("}", node2, "end");
6918 };
6919 _proto.body = function body(node2) {
6920 var last = node2.nodes.length - 1;
6921 while (last > 0) {
6922 if (node2.nodes[last].type !== "comment") break;
6923 last -= 1;
6924 }
6925 var semicolon = this.raw(node2, "semicolon");
6926 for (var i2 = 0; i2 < node2.nodes.length; i2++) {
6927 var child = node2.nodes[i2];
6928 var before = this.raw(child, "before");
6929 if (before) this.builder(before);
6930 this.stringify(child, last !== i2 || semicolon);
6931 }
6932 };
6933 _proto.comment = function comment(node2) {
6934 var left = this.raw(node2, "left", "commentLeft");
6935 var right = this.raw(node2, "right", "commentRight");
6936 this.builder("/*" + left + node2.text + right + "*/", node2);
6937 };
6938 _proto.decl = function decl(node2, semicolon) {
6939 var between = this.raw(node2, "between", "colon");
6940 var string = node2.prop + between + this.rawValue(node2, "value");
6941 if (node2.important) string += node2.raws.important || " !important";
6942 if (semicolon) string += ";";
6943 this.builder(string, node2);
6944 };
6945 _proto.document = function document1(node2) {
6946 this.body(node2);
6947 };
6948 _proto.raw = function raw(node2, own, detect) {
6949 var value;
6950 if (!detect) detect = own;
6951 if (own) {
6952 value = node2.raws[own];
6953 if (typeof value !== "undefined") return value;
6954 }
6955 var parent = node2.parent;
6956 if (detect === "before") {
6957 if (!parent || parent.type === "root" && parent.first === node2) return "";
6958 if (parent && parent.type === "document") return "";
6959 }
6960 if (!parent) return DEFAULT_RAW$1[detect];
6961 var root2 = node2.root();
6962 if (!root2.rawCache) root2.rawCache = {};
6963 if (typeof root2.rawCache[detect] !== "undefined") return root2.rawCache[detect];
6964 if (detect === "before" || detect === "after") return this.beforeAfter(node2, detect);
6965 else {
6966 var method = "raw" + capitalize$1(detect);
6967 if (this[method]) value = this[method](root2, node2);
6968 else root2.walk(function(i2) {
6969 value = i2.raws[own];
6970 if (typeof value !== "undefined") return false;
6971 });
6972 }
6973 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
6974 root2.rawCache[detect] = value;
6975 return value;
6976 };
6977 _proto.rawBeforeClose = function rawBeforeClose(root2) {
6978 var value;
6979 root2.walk(function(i2) {
6980 if (i2.nodes && i2.nodes.length > 0) {
6981 if (typeof i2.raws.after !== "undefined") {
6982 value = i2.raws.after;
6983 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
6984 return false;
6985 }
6986 }
6987 });
6988 if (value) value = value.replace(/\S/g, "");
6989 return value;
6990 };
6991 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
6992 var value;
6993 root2.walkComments(function(i2) {
6994 if (typeof i2.raws.before !== "undefined") {
6995 value = i2.raws.before;
6996 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
6997 return false;
6998 }
6999 });
7000 if (typeof value === "undefined") value = this.raw(node2, null, "beforeDecl");
7001 else if (value) value = value.replace(/\S/g, "");
7002 return value;
7003 };
7004 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
7005 var value;
7006 root2.walkDecls(function(i2) {
7007 if (typeof i2.raws.before !== "undefined") {
7008 value = i2.raws.before;
7009 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7010 return false;
7011 }
7012 });
7013 if (typeof value === "undefined") value = this.raw(node2, null, "beforeRule");
7014 else if (value) value = value.replace(/\S/g, "");
7015 return value;
7016 };
7017 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
7018 var value;
7019 root2.walk(function(i2) {
7020 if (i2.type !== "decl") {
7021 value = i2.raws.between;
7022 if (typeof value !== "undefined") return false;
7023 }
7024 });
7025 return value;
7026 };
7027 _proto.rawBeforeRule = function rawBeforeRule(root2) {
7028 var value;
7029 root2.walk(function(i2) {
7030 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
7031 if (typeof i2.raws.before !== "undefined") {
7032 value = i2.raws.before;
7033 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
7034 return false;
7035 }
7036 }
7037 });
7038 if (value) value = value.replace(/\S/g, "");
7039 return value;
7040 };
7041 _proto.rawColon = function rawColon(root2) {
7042 var value;
7043 root2.walkDecls(function(i2) {
7044 if (typeof i2.raws.between !== "undefined") {
7045 value = i2.raws.between.replace(/[^\s:]/g, "");
7046 return false;
7047 }
7048 });
7049 return value;
7050 };
7051 _proto.rawEmptyBody = function rawEmptyBody(root2) {
7052 var value;
7053 root2.walk(function(i2) {
7054 if (i2.nodes && i2.nodes.length === 0) {
7055 value = i2.raws.after;
7056 if (typeof value !== "undefined") return false;
7057 }
7058 });
7059 return value;
7060 };
7061 _proto.rawIndent = function rawIndent(root2) {
7062 if (root2.raws.indent) return root2.raws.indent;
7063 var value;
7064 root2.walk(function(i2) {
7065 var p = i2.parent;
7066 if (p && p !== root2 && p.parent && p.parent === root2) {
7067 if (typeof i2.raws.before !== "undefined") {
7068 var parts = i2.raws.before.split("\n");
7069 value = parts[parts.length - 1];
7070 value = value.replace(/\S/g, "");
7071 return false;
7072 }
7073 }
7074 });
7075 return value;
7076 };
7077 _proto.rawSemicolon = function rawSemicolon(root2) {
7078 var value;
7079 root2.walk(function(i2) {
7080 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
7081 value = i2.raws.semicolon;
7082 if (typeof value !== "undefined") return false;
7083 }
7084 });
7085 return value;
7086 };
7087 _proto.rawValue = function rawValue(node2, prop) {
7088 var value = node2[prop];
7089 var raw = node2.raws[prop];
7090 if (raw && raw.value === value) return raw.raw;
7091 return value;
7092 };
7093 _proto.root = function root(node2) {
7094 this.body(node2);
7095 if (node2.raws.after) this.builder(node2.raws.after);
7096 };
7097 _proto.rule = function rule(node2) {
7098 this.block(node2, this.rawValue(node2, "selector"));
7099 if (node2.raws.ownSemicolon) this.builder(node2.raws.ownSemicolon, node2, "end");
7100 };
7101 _proto.stringify = function stringify(node2, semicolon) {
7102 if (!this[node2.type]) throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
7103 this[node2.type](node2, semicolon);
7104 };
7105 return Stringifier;
7106 }();
7107 var stringifier$1 = Stringifier$2$1;
7108 Stringifier$2$1.default = Stringifier$2$1;
7109 var Stringifier$1$1 = stringifier$1;
7110 function stringify$4$1(node2, builder) {
7111 new Stringifier$1$1(builder).stringify(node2);
7112 }
7113 var stringify_1$1 = stringify$4$1;
7114 stringify$4$1.default = stringify$4$1;
7115 var isClean$2$1 = symbols$1.isClean;
7116 var my$2$1 = symbols$1.my;
7117 var CssSyntaxError$2$1 = cssSyntaxError$1;
7118 var Stringifier2$1 = stringifier$1;
7119 var stringify$3$1 = stringify_1$1;
7120 function cloneNode$1(obj, parent) {
7121 var cloned = new obj.constructor();
7122 for (var i2 in obj) {
7123 if (!Object.prototype.hasOwnProperty.call(obj, i2)) continue;
7124 if (i2 === "proxyCache") continue;
7125 var value = obj[i2];
7126 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
7127 if (i2 === "parent" && type === "object") {
7128 if (parent) cloned[i2] = parent;
7129 } else if (i2 === "source") cloned[i2] = value;
7130 else if (Array.isArray(value)) cloned[i2] = value.map(function(j) {
7131 return cloneNode$1(j, cloned);
7132 });
7133 else {
7134 if (type === "object" && value !== null) value = cloneNode$1(value);
7135 cloned[i2] = value;
7136 }
7137 }
7138 return cloned;
7139 }
7140 var Node$4$1 = /*#__PURE__*/ function() {
7141 function Node2(defaults) {
7142 if (defaults === void 0) defaults = {};
7143 this.raws = {};
7144 this[isClean$2$1] = false;
7145 this[my$2$1] = true;
7146 for (var name in defaults) if (name === "nodes") {
7147 this.nodes = [];
7148 for (var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;) {
7149 var node2 = _step.value;
7150 if (typeof node2.clone === "function") this.append(node2.clone());
7151 else this.append(node2);
7152 }
7153 } else this[name] = defaults[name];
7154 }
7155 var _proto = Node2.prototype;
7156 _proto.addToError = function addToError(error) {
7157 error.postcssNode = this;
7158 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
7159 var s2 = this.source;
7160 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
7161 }
7162 return error;
7163 };
7164 _proto.after = function after(add) {
7165 this.parent.insertAfter(this, add);
7166 return this;
7167 };
7168 _proto.assign = function assign(overrides) {
7169 if (overrides === void 0) overrides = {};
7170 for (var name in overrides) this[name] = overrides[name];
7171 return this;
7172 };
7173 _proto.before = function before(add) {
7174 this.parent.insertBefore(this, add);
7175 return this;
7176 };
7177 _proto.cleanRaws = function cleanRaws(keepBetween) {
7178 delete this.raws.before;
7179 delete this.raws.after;
7180 if (!keepBetween) delete this.raws.between;
7181 };
7182 _proto.clone = function clone(overrides) {
7183 if (overrides === void 0) overrides = {};
7184 var cloned = cloneNode$1(this);
7185 for (var name in overrides) cloned[name] = overrides[name];
7186 return cloned;
7187 };
7188 _proto.cloneAfter = function cloneAfter(overrides) {
7189 if (overrides === void 0) overrides = {};
7190 var cloned = this.clone(overrides);
7191 this.parent.insertAfter(this, cloned);
7192 return cloned;
7193 };
7194 _proto.cloneBefore = function cloneBefore(overrides) {
7195 if (overrides === void 0) overrides = {};
7196 var cloned = this.clone(overrides);
7197 this.parent.insertBefore(this, cloned);
7198 return cloned;
7199 };
7200 _proto.error = function error(message, opts) {
7201 if (opts === void 0) opts = {};
7202 if (this.source) {
7203 var _this_rangeBy = this.rangeBy(opts);
7204 var end = _this_rangeBy.end;
7205 var start = _this_rangeBy.start;
7206 return this.source.input.error(message, {
7207 column: start.column,
7208 line: start.line
7209 }, {
7210 column: end.column,
7211 line: end.line
7212 }, opts);
7213 }
7214 return new CssSyntaxError$2$1(message);
7215 };
7216 _proto.getProxyProcessor = function getProxyProcessor() {
7217 return {
7218 get: function get(node2, prop) {
7219 if (prop === "proxyOf") return node2;
7220 else if (prop === "root") return function() {
7221 return node2.root().toProxy();
7222 };
7223 else return node2[prop];
7224 },
7225 set: function set(node2, prop, value) {
7226 if (node2[prop] === value) return true;
7227 node2[prop] = value;
7228 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || prop === "text") node2.markDirty();
7229 return true;
7230 }
7231 };
7232 };
7233 _proto.markDirty = function markDirty() {
7234 if (this[isClean$2$1]) {
7235 this[isClean$2$1] = false;
7236 var next = this;
7237 while (next = next.parent) next[isClean$2$1] = false;
7238 }
7239 };
7240 _proto.next = function next() {
7241 if (!this.parent) return void 0;
7242 var index2 = this.parent.index(this);
7243 return this.parent.nodes[index2 + 1];
7244 };
7245 _proto.positionBy = function positionBy(opts, stringRepresentation) {
7246 var pos = this.source.start;
7247 if (opts.index) pos = this.positionInside(opts.index, stringRepresentation);
7248 else if (opts.word) {
7249 stringRepresentation = this.toString();
7250 var index2 = stringRepresentation.indexOf(opts.word);
7251 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
7252 }
7253 return pos;
7254 };
7255 _proto.positionInside = function positionInside(index2, stringRepresentation) {
7256 var string = stringRepresentation || this.toString();
7257 var column = this.source.start.column;
7258 var line = this.source.start.line;
7259 for (var i2 = 0; i2 < index2; i2++) if (string[i2] === "\n") {
7260 column = 1;
7261 line += 1;
7262 } else column += 1;
7263 return {
7264 column,
7265 line
7266 };
7267 };
7268 _proto.prev = function prev() {
7269 if (!this.parent) return void 0;
7270 var index2 = this.parent.index(this);
7271 return this.parent.nodes[index2 - 1];
7272 };
7273 _proto.rangeBy = function rangeBy(opts) {
7274 var start = {
7275 column: this.source.start.column,
7276 line: this.source.start.line
7277 };
7278 var end = this.source.end ? {
7279 column: this.source.end.column + 1,
7280 line: this.source.end.line
7281 } : {
7282 column: start.column + 1,
7283 line: start.line
7284 };
7285 if (opts.word) {
7286 var stringRepresentation = this.toString();
7287 var index2 = stringRepresentation.indexOf(opts.word);
7288 if (index2 !== -1) {
7289 start = this.positionInside(index2, stringRepresentation);
7290 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
7291 }
7292 } else {
7293 if (opts.start) start = {
7294 column: opts.start.column,
7295 line: opts.start.line
7296 };
7297 else if (opts.index) start = this.positionInside(opts.index);
7298 if (opts.end) end = {
7299 column: opts.end.column,
7300 line: opts.end.line
7301 };
7302 else if (typeof opts.endIndex === "number") end = this.positionInside(opts.endIndex);
7303 else if (opts.index) end = this.positionInside(opts.index + 1);
7304 }
7305 if (end.line < start.line || end.line === start.line && end.column <= start.column) end = {
7306 column: start.column + 1,
7307 line: start.line
7308 };
7309 return {
7310 end,
7311 start
7312 };
7313 };
7314 _proto.raw = function raw(prop, defaultType) {
7315 return new Stringifier2$1().raw(this, prop, defaultType);
7316 };
7317 _proto.remove = function remove() {
7318 if (this.parent) this.parent.removeChild(this);
7319 this.parent = void 0;
7320 return this;
7321 };
7322 _proto.replaceWith = function replaceWith() {
7323 for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) nodes[_key] = arguments[_key];
7324 if (this.parent) {
7325 var bookmark = this;
7326 var foundSelf = false;
7327 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
7328 var node2 = _step.value;
7329 if (node2 === this) foundSelf = true;
7330 else if (foundSelf) {
7331 this.parent.insertAfter(bookmark, node2);
7332 bookmark = node2;
7333 } else this.parent.insertBefore(bookmark, node2);
7334 }
7335 if (!foundSelf) this.remove();
7336 }
7337 return this;
7338 };
7339 _proto.root = function root() {
7340 var result2 = this;
7341 while (result2.parent && result2.parent.type !== "document") result2 = result2.parent;
7342 return result2;
7343 };
7344 _proto.toJSON = function toJSON(_, inputs) {
7345 var fixed = {};
7346 var emitInputs = inputs == null;
7347 inputs = inputs || /* @__PURE__ */ new Map();
7348 var inputsNextIndex = 0;
7349 for (var name in this) {
7350 if (!Object.prototype.hasOwnProperty.call(this, name)) continue;
7351 if (name === "parent" || name === "proxyCache") continue;
7352 var value = this[name];
7353 if (Array.isArray(value)) fixed[name] = value.map(function(i2) {
7354 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) return i2.toJSON(null, inputs);
7355 else return i2;
7356 });
7357 else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) fixed[name] = value.toJSON(null, inputs);
7358 else if (name === "source") {
7359 var inputId = inputs.get(value.input);
7360 if (inputId == null) {
7361 inputId = inputsNextIndex;
7362 inputs.set(value.input, inputsNextIndex);
7363 inputsNextIndex++;
7364 }
7365 fixed[name] = {
7366 end: value.end,
7367 inputId,
7368 start: value.start
7369 };
7370 } else fixed[name] = value;
7371 }
7372 if (emitInputs) fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
7373 return input2.toJSON();
7374 });
7375 return fixed;
7376 };
7377 _proto.toProxy = function toProxy() {
7378 if (!this.proxyCache) this.proxyCache = new Proxy(this, this.getProxyProcessor());
7379 return this.proxyCache;
7380 };
7381 _proto.toString = function toString(stringifier2) {
7382 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
7383 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
7384 var result2 = "";
7385 stringifier2(this, function(i2) {
7386 result2 += i2;
7387 });
7388 return result2;
7389 };
7390 _proto.warn = function warn(result2, text, opts) {
7391 var data = { node: this };
7392 for (var i2 in opts) data[i2] = opts[i2];
7393 return result2.warn(text, data);
7394 };
7395 _create_class(Node2, [{
7396 key: "proxyOf",
7397 get: function get() {
7398 return this;
7399 }
7400 }]);
7401 return Node2;
7402 }();
7403 var node$1 = Node$4$1;
7404 Node$4$1.default = Node$4$1;
7405 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
7406 _inherits(Declaration, Node$3$1);
7407 function Declaration(defaults) {
7408 var _this;
7409 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") defaults = _extends({}, defaults, { value: String(defaults.value) });
7410 _this = Node$3$1.call(this, defaults) || this;
7411 _this.type = "decl";
7412 return _this;
7413 }
7414 _create_class(Declaration, [{
7415 key: "variable",
7416 get: function get() {
7417 return this.prop.startsWith("--") || this.prop[0] === "$";
7418 }
7419 }]);
7420 return Declaration;
7421 }(node$1);
7422 var declaration$1 = Declaration$4$1;
7423 Declaration$4$1.default = Declaration$4$1;
7424 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
7425 var nanoid$1$1 = function(size) {
7426 if (size === void 0) size = 21;
7427 var id = "";
7428 var i2 = size;
7429 while (i2--) id += urlAlphabet$1[Math.random() * 64 | 0];
7430 return id;
7431 };
7432 var nonSecure$1 = { nanoid: nanoid$1$1 };
7433 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer;
7434 var SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
7435 var existsSync$1 = require$$2$1.existsSync;
7436 var readFileSync$1 = require$$2$1.readFileSync;
7437 var dirname$1$1 = require$$2$1.dirname;
7438 var join$1 = require$$2$1.join;
7439 function fromBase64$1(str) {
7440 if (Buffer) return Buffer.from(str, "base64").toString();
7441 else return window.atob(str);
7442 }
7443 var PreviousMap$2$1 = /*#__PURE__*/ function() {
7444 function PreviousMap(css, opts) {
7445 if (opts.map === false) return;
7446 this.loadAnnotation(css);
7447 this.inline = this.startWith(this.annotation, "data:");
7448 var prev = opts.map ? opts.map.prev : void 0;
7449 var text = this.loadMap(opts.from, prev);
7450 if (!this.mapFile && opts.from) this.mapFile = opts.from;
7451 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
7452 if (text) this.text = text;
7453 }
7454 var _proto = PreviousMap.prototype;
7455 _proto.consumer = function consumer() {
7456 if (!this.consumerCache) this.consumerCache = new SourceMapConsumer$2$1(this.text);
7457 return this.consumerCache;
7458 };
7459 _proto.decodeInline = function decodeInline(text) {
7460 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
7461 var baseUri = /^data:application\/json;base64,/;
7462 if (/^data:application\/json;charset=utf-?8,/.test(text) || /^data:application\/json,/.test(text)) return decodeURIComponent(text.substr(RegExp.lastMatch.length));
7463 if (baseCharsetUri.test(text) || baseUri.test(text)) return fromBase64$1(text.substr(RegExp.lastMatch.length));
7464 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
7465 throw new Error("Unsupported source map encoding " + encoding);
7466 };
7467 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
7468 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
7469 };
7470 _proto.isMap = function isMap(map) {
7471 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
7472 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
7473 };
7474 _proto.loadAnnotation = function loadAnnotation(css) {
7475 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
7476 if (!comments) return;
7477 var start = css.lastIndexOf(comments.pop());
7478 var end = css.indexOf("*/", start);
7479 if (start > -1 && end > -1) this.annotation = this.getAnnotationURL(css.substring(start, end));
7480 };
7481 _proto.loadFile = function loadFile(path) {
7482 this.root = dirname$1$1(path);
7483 if (existsSync$1(path)) {
7484 this.mapFile = path;
7485 return readFileSync$1(path, "utf-8").toString().trim();
7486 }
7487 };
7488 _proto.loadMap = function loadMap(file, prev) {
7489 if (prev === false) return false;
7490 if (prev) if (typeof prev === "string") return prev;
7491 else if (typeof prev === "function") {
7492 var prevPath = prev(file);
7493 if (prevPath) {
7494 var map = this.loadFile(prevPath);
7495 if (!map) throw new Error("Unable to load previous source map: " + prevPath.toString());
7496 return map;
7497 }
7498 } else if (_instanceof(prev, SourceMapConsumer$2$1)) return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
7499 else if (_instanceof(prev, SourceMapGenerator$2$1)) return prev.toString();
7500 else if (this.isMap(prev)) return JSON.stringify(prev);
7501 else throw new Error("Unsupported previous source map format: " + prev.toString());
7502 else if (this.inline) return this.decodeInline(this.annotation);
7503 else if (this.annotation) {
7504 var map1 = this.annotation;
7505 if (file) map1 = join$1(dirname$1$1(file), map1);
7506 return this.loadFile(map1);
7507 }
7508 };
7509 _proto.startWith = function startWith(string, start) {
7510 if (!string) return false;
7511 return string.substr(0, start.length) === start;
7512 };
7513 _proto.withContent = function withContent() {
7514 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
7515 };
7516 return PreviousMap;
7517 }();
7518 var previousMap$1 = PreviousMap$2$1;
7519 PreviousMap$2$1.default = PreviousMap$2$1;
7520 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer;
7521 var SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
7522 var fileURLToPath$1 = require$$2$1.fileURLToPath;
7523 var pathToFileURL$1$1 = require$$2$1.pathToFileURL;
7524 var isAbsolute$1 = require$$2$1.isAbsolute;
7525 var resolve$1$1 = require$$2$1.resolve;
7526 var nanoid$2 = nonSecure$1.nanoid;
7527 var terminalHighlight$2 = require$$2$1;
7528 var CssSyntaxError$1$1 = cssSyntaxError$1;
7529 var PreviousMap$1$1 = previousMap$1;
7530 var fromOffsetCache$1 = Symbol("fromOffsetCache");
7531 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
7532 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
7533 var Input$4$1 = /*#__PURE__*/ function() {
7534 function Input(css, opts) {
7535 if (opts === void 0) opts = {};
7536 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) throw new Error("PostCSS received " + css + " instead of CSS string");
7537 this.css = css.toString();
7538 if (this.css[0] === "" || this.css[0] === "￾") {
7539 this.hasBOM = true;
7540 this.css = this.css.slice(1);
7541 } else this.hasBOM = false;
7542 if (opts.from) if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) this.file = opts.from;
7543 else this.file = resolve$1$1(opts.from);
7544 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
7545 var map = new PreviousMap$1$1(this.css, opts);
7546 if (map.text) {
7547 this.map = map;
7548 var file = map.consumer().file;
7549 if (!this.file && file) this.file = this.mapResolve(file);
7550 }
7551 }
7552 if (!this.file) this.id = "<input css " + nanoid$2(6) + ">";
7553 if (this.map) this.map.file = this.from;
7554 }
7555 var _proto = Input.prototype;
7556 _proto.error = function error(message, line, column, opts) {
7557 if (opts === void 0) opts = {};
7558 var result2;
7559 var endLine;
7560 var endColumn;
7561 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
7562 var start = line;
7563 var end = column;
7564 if (typeof start.offset === "number") {
7565 var pos = this.fromOffset(start.offset);
7566 line = pos.line;
7567 column = pos.col;
7568 } else {
7569 line = start.line;
7570 column = start.column;
7571 }
7572 if (typeof end.offset === "number") {
7573 var pos1 = this.fromOffset(end.offset);
7574 endLine = pos1.line;
7575 endColumn = pos1.col;
7576 } else {
7577 endLine = end.line;
7578 endColumn = end.column;
7579 }
7580 } else if (!column) {
7581 var pos2 = this.fromOffset(line);
7582 line = pos2.line;
7583 column = pos2.col;
7584 }
7585 var origin = this.origin(line, column, endLine, endColumn);
7586 if (origin) result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
7587 column: origin.column,
7588 line: origin.line
7589 }, origin.endLine === void 0 ? origin.column : {
7590 column: origin.endColumn,
7591 line: origin.endLine
7592 }, origin.source, origin.file, opts.plugin);
7593 else result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
7594 column,
7595 line
7596 }, endLine === void 0 ? column : {
7597 column: endColumn,
7598 line: endLine
7599 }, this.css, this.file, opts.plugin);
7600 result2.input = {
7601 column,
7602 endColumn,
7603 endLine,
7604 line,
7605 source: this.css
7606 };
7607 if (this.file) {
7608 if (pathToFileURL$1$1) result2.input.url = pathToFileURL$1$1(this.file).toString();
7609 result2.input.file = this.file;
7610 }
7611 return result2;
7612 };
7613 _proto.fromOffset = function fromOffset(offset) {
7614 var lastLine;
7615 var lineToIndex;
7616 if (!this[fromOffsetCache$1]) {
7617 var lines = this.css.split("\n");
7618 lineToIndex = new Array(lines.length);
7619 var prevIndex = 0;
7620 for (var i2 = 0, l2 = lines.length; i2 < l2; i2++) {
7621 lineToIndex[i2] = prevIndex;
7622 prevIndex += lines[i2].length + 1;
7623 }
7624 this[fromOffsetCache$1] = lineToIndex;
7625 } else lineToIndex = this[fromOffsetCache$1];
7626 lastLine = lineToIndex[lineToIndex.length - 1];
7627 var min = 0;
7628 if (offset >= lastLine) min = lineToIndex.length - 1;
7629 else {
7630 var max = lineToIndex.length - 2;
7631 var mid;
7632 while (min < max) {
7633 mid = min + (max - min >> 1);
7634 if (offset < lineToIndex[mid]) max = mid - 1;
7635 else if (offset >= lineToIndex[mid + 1]) min = mid + 1;
7636 else {
7637 min = mid;
7638 break;
7639 }
7640 }
7641 }
7642 return {
7643 col: offset - lineToIndex[min] + 1,
7644 line: min + 1
7645 };
7646 };
7647 _proto.mapResolve = function mapResolve(file) {
7648 if (/^\w+:\/\//.test(file)) return file;
7649 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
7650 };
7651 _proto.origin = function origin(line, column, endLine, endColumn) {
7652 if (!this.map) return false;
7653 var consumer = this.map.consumer();
7654 var from = consumer.originalPositionFor({
7655 column,
7656 line
7657 });
7658 if (!from.source) return false;
7659 var to;
7660 if (typeof endLine === "number") to = consumer.originalPositionFor({
7661 column: endColumn,
7662 line: endLine
7663 });
7664 var fromUrl;
7665 if (isAbsolute$1(from.source)) fromUrl = pathToFileURL$1$1(from.source);
7666 else fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
7667 var result2 = {
7668 column: from.column,
7669 endColumn: to && to.column,
7670 endLine: to && to.line,
7671 line: from.line,
7672 url: fromUrl.toString()
7673 };
7674 if (fromUrl.protocol === "file:") if (fileURLToPath$1) result2.file = fileURLToPath$1(fromUrl);
7675 else throw new Error("file: protocol is not available in this PostCSS build");
7676 var source = consumer.sourceContentFor(from.source);
7677 if (source) result2.source = source;
7678 return result2;
7679 };
7680 _proto.toJSON = function toJSON() {
7681 var json = {};
7682 for (var _i = 0, _iter = [
7683 "hasBOM",
7684 "css",
7685 "file",
7686 "id"
7687 ]; _i < _iter.length; _i++) {
7688 var name = _iter[_i];
7689 if (this[name] != null) json[name] = this[name];
7690 }
7691 if (this.map) {
7692 json.map = _extends({}, this.map);
7693 if (json.map.consumerCache) json.map.consumerCache = void 0;
7694 }
7695 return json;
7696 };
7697 _create_class(Input, [{
7698 key: "from",
7699 get: function get() {
7700 return this.file || this.id;
7701 }
7702 }]);
7703 return Input;
7704 }();
7705 var input$1 = Input$4$1;
7706 Input$4$1.default = Input$4$1;
7707 if (terminalHighlight$2 && terminalHighlight$2.registerInput) terminalHighlight$2.registerInput(Input$4$1);
7708 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer;
7709 var SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
7710 var dirname$2 = require$$2$1.dirname;
7711 var relative$1 = require$$2$1.relative;
7712 var resolve$2 = require$$2$1.resolve;
7713 var sep$1 = require$$2$1.sep;
7714 var pathToFileURL$2 = require$$2$1.pathToFileURL;
7715 var Input$3$1 = input$1;
7716 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
7717 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
7718 var mapGenerator$1 = /* @__PURE__ */ function() {
7719 function MapGenerator(stringify2, root2, opts, cssString) {
7720 this.stringify = stringify2;
7721 this.mapOpts = opts.map || {};
7722 this.root = root2;
7723 this.opts = opts;
7724 this.css = cssString;
7725 this.originalCSS = cssString;
7726 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
7727 this.memoizedFileURLs = /* @__PURE__ */ new Map();
7728 this.memoizedPaths = /* @__PURE__ */ new Map();
7729 this.memoizedURLs = /* @__PURE__ */ new Map();
7730 }
7731 var _proto = MapGenerator.prototype;
7732 _proto.addAnnotation = function addAnnotation() {
7733 var content;
7734 if (this.isInline()) content = "data:application/json;base64," + this.toBase64(this.map.toString());
7735 else if (typeof this.mapOpts.annotation === "string") content = this.mapOpts.annotation;
7736 else if (typeof this.mapOpts.annotation === "function") content = this.mapOpts.annotation(this.opts.to, this.root);
7737 else content = this.outputFile() + ".map";
7738 var eol = "\n";
7739 if (this.css.includes("\r\n")) eol = "\r\n";
7740 this.css += eol + "/*# sourceMappingURL=" + content + " */";
7741 };
7742 _proto.applyPrevMaps = function applyPrevMaps() {
7743 for (var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;) {
7744 var prev = _step.value;
7745 var from = this.toUrl(this.path(prev.file));
7746 var root2 = prev.root || dirname$2(prev.file);
7747 var map = void 0;
7748 if (this.mapOpts.sourcesContent === false) {
7749 map = new SourceMapConsumer$3(prev.text);
7750 if (map.sourcesContent) map.sourcesContent = null;
7751 } else map = prev.consumer();
7752 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
7753 }
7754 };
7755 _proto.clearAnnotation = function clearAnnotation() {
7756 if (this.mapOpts.annotation === false) return;
7757 if (this.root) {
7758 var node2;
7759 for (var i2 = this.root.nodes.length - 1; i2 >= 0; i2--) {
7760 node2 = this.root.nodes[i2];
7761 if (node2.type !== "comment") continue;
7762 if (node2.text.indexOf("# sourceMappingURL=") === 0) this.root.removeChild(i2);
7763 }
7764 } else if (this.css) this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
7765 };
7766 _proto.generate = function generate() {
7767 this.clearAnnotation();
7768 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) return this.generateMap();
7769 else {
7770 var result2 = "";
7771 this.stringify(this.root, function(i2) {
7772 result2 += i2;
7773 });
7774 return [result2];
7775 }
7776 };
7777 _proto.generateMap = function generateMap() {
7778 if (this.root) this.generateString();
7779 else if (this.previous().length === 1) {
7780 var prev = this.previous()[0].consumer();
7781 prev.file = this.outputFile();
7782 this.map = SourceMapGenerator$3.fromSourceMap(prev, { ignoreInvalidMapping: true });
7783 } else {
7784 this.map = new SourceMapGenerator$3({
7785 file: this.outputFile(),
7786 ignoreInvalidMapping: true
7787 });
7788 this.map.addMapping({
7789 generated: {
7790 column: 0,
7791 line: 1
7792 },
7793 original: {
7794 column: 0,
7795 line: 1
7796 },
7797 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
7798 });
7799 }
7800 if (this.isSourcesContent()) this.setSourcesContent();
7801 if (this.root && this.previous().length > 0) this.applyPrevMaps();
7802 if (this.isAnnotation()) this.addAnnotation();
7803 if (this.isInline()) return [this.css];
7804 else return [this.css, this.map];
7805 };
7806 _proto.generateString = function generateString() {
7807 var _this = this;
7808 this.css = "";
7809 this.map = new SourceMapGenerator$3({
7810 file: this.outputFile(),
7811 ignoreInvalidMapping: true
7812 });
7813 var line = 1;
7814 var column = 1;
7815 var noSource = "<no source>";
7816 var mapping = {
7817 generated: {
7818 column: 0,
7819 line: 0
7820 },
7821 original: {
7822 column: 0,
7823 line: 0
7824 },
7825 source: ""
7826 };
7827 var lines;
7828 var last;
7829 this.stringify(this.root, function(str, node2, type) {
7830 _this.css += str;
7831 if (node2 && type !== "end") {
7832 mapping.generated.line = line;
7833 mapping.generated.column = column - 1;
7834 if (node2.source && node2.source.start) {
7835 mapping.source = _this.sourcePath(node2);
7836 mapping.original.line = node2.source.start.line;
7837 mapping.original.column = node2.source.start.column - 1;
7838 _this.map.addMapping(mapping);
7839 } else {
7840 mapping.source = noSource;
7841 mapping.original.line = 1;
7842 mapping.original.column = 0;
7843 _this.map.addMapping(mapping);
7844 }
7845 }
7846 lines = str.match(/\n/g);
7847 if (lines) {
7848 line += lines.length;
7849 last = str.lastIndexOf("\n");
7850 column = str.length - last;
7851 } else column += str.length;
7852 if (node2 && type !== "start") {
7853 var p = node2.parent || { raws: {} };
7854 if (!(node2.type === "decl" || node2.type === "atrule" && !node2.nodes) || node2 !== p.last || p.raws.semicolon) if (node2.source && node2.source.end) {
7855 mapping.source = _this.sourcePath(node2);
7856 mapping.original.line = node2.source.end.line;
7857 mapping.original.column = node2.source.end.column - 1;
7858 mapping.generated.line = line;
7859 mapping.generated.column = column - 2;
7860 _this.map.addMapping(mapping);
7861 } else {
7862 mapping.source = noSource;
7863 mapping.original.line = 1;
7864 mapping.original.column = 0;
7865 mapping.generated.line = line;
7866 mapping.generated.column = column - 1;
7867 _this.map.addMapping(mapping);
7868 }
7869 }
7870 });
7871 };
7872 _proto.isAnnotation = function isAnnotation() {
7873 if (this.isInline()) return true;
7874 if (typeof this.mapOpts.annotation !== "undefined") return this.mapOpts.annotation;
7875 if (this.previous().length) return this.previous().some(function(i2) {
7876 return i2.annotation;
7877 });
7878 return true;
7879 };
7880 _proto.isInline = function isInline() {
7881 if (typeof this.mapOpts.inline !== "undefined") return this.mapOpts.inline;
7882 var annotation = this.mapOpts.annotation;
7883 if (typeof annotation !== "undefined" && annotation !== true) return false;
7884 if (this.previous().length) return this.previous().some(function(i2) {
7885 return i2.inline;
7886 });
7887 return true;
7888 };
7889 _proto.isMap = function isMap() {
7890 if (typeof this.opts.map !== "undefined") return !!this.opts.map;
7891 return this.previous().length > 0;
7892 };
7893 _proto.isSourcesContent = function isSourcesContent() {
7894 if (typeof this.mapOpts.sourcesContent !== "undefined") return this.mapOpts.sourcesContent;
7895 if (this.previous().length) return this.previous().some(function(i2) {
7896 return i2.withContent();
7897 });
7898 return true;
7899 };
7900 _proto.outputFile = function outputFile() {
7901 if (this.opts.to) return this.path(this.opts.to);
7902 else if (this.opts.from) return this.path(this.opts.from);
7903 else return "to.css";
7904 };
7905 _proto.path = function path(file) {
7906 if (this.mapOpts.absolute) return file;
7907 if (file.charCodeAt(0) === 60) return file;
7908 if (/^\w+:\/\//.test(file)) return file;
7909 var cached = this.memoizedPaths.get(file);
7910 if (cached) return cached;
7911 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
7912 if (typeof this.mapOpts.annotation === "string") from = dirname$2(resolve$2(from, this.mapOpts.annotation));
7913 var path = relative$1(from, file);
7914 this.memoizedPaths.set(file, path);
7915 return path;
7916 };
7917 _proto.previous = function previous() {
7918 var _this = this;
7919 if (!this.previousMaps) {
7920 this.previousMaps = [];
7921 if (this.root) this.root.walk(function(node2) {
7922 if (node2.source && node2.source.input.map) {
7923 var map = node2.source.input.map;
7924 if (!_this.previousMaps.includes(map)) _this.previousMaps.push(map);
7925 }
7926 });
7927 else {
7928 var input2 = new Input$3$1(this.originalCSS, this.opts);
7929 if (input2.map) this.previousMaps.push(input2.map);
7930 }
7931 }
7932 return this.previousMaps;
7933 };
7934 _proto.setSourcesContent = function setSourcesContent() {
7935 var _this = this;
7936 var already = {};
7937 if (this.root) this.root.walk(function(node2) {
7938 if (node2.source) {
7939 var from = node2.source.input.from;
7940 if (from && !already[from]) {
7941 already[from] = true;
7942 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
7943 _this.map.setSourceContent(fromUrl, node2.source.input.css);
7944 }
7945 }
7946 });
7947 else if (this.css) {
7948 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
7949 this.map.setSourceContent(from, this.css);
7950 }
7951 };
7952 _proto.sourcePath = function sourcePath(node2) {
7953 if (this.mapOpts.from) return this.toUrl(this.mapOpts.from);
7954 else if (this.usesFileUrls) return this.toFileUrl(node2.source.input.from);
7955 else return this.toUrl(this.path(node2.source.input.from));
7956 };
7957 _proto.toBase64 = function toBase64(str) {
7958 if (Buffer) return Buffer.from(str).toString("base64");
7959 else return window.btoa(unescape(encodeURIComponent(str)));
7960 };
7961 _proto.toFileUrl = function toFileUrl(path) {
7962 var cached = this.memoizedFileURLs.get(path);
7963 if (cached) return cached;
7964 if (pathToFileURL$2) {
7965 var fileURL = pathToFileURL$2(path).toString();
7966 this.memoizedFileURLs.set(path, fileURL);
7967 return fileURL;
7968 } else throw new Error("`map.absolute` option is not available in this PostCSS build");
7969 };
7970 _proto.toUrl = function toUrl(path) {
7971 var cached = this.memoizedURLs.get(path);
7972 if (cached) return cached;
7973 if (sep$1 === "\\") path = path.replace(/\\/g, "/");
7974 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
7975 this.memoizedURLs.set(path, url);
7976 return url;
7977 };
7978 return MapGenerator;
7979 }();
7980 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
7981 _inherits(Comment, Node$2$1);
7982 function Comment(defaults) {
7983 var _this = Node$2$1.call(this, defaults) || this;
7984 _this.type = "comment";
7985 return _this;
7986 }
7987 return Comment;
7988 }(node$1);
7989 var comment$1 = Comment$4$1;
7990 Comment$4$1.default = Comment$4$1;
7991 var isClean$1$1 = symbols$1.isClean;
7992 var my$1$1 = symbols$1.my;
7993 var Declaration$3$1 = declaration$1;
7994 var Comment$3$1 = comment$1;
7995 var Node$1$1 = node$1;
7996 var parse$4$1;
7997 var Rule$4$1;
7998 var AtRule$4$1;
7999 var Root$6$1;
8000 function cleanSource$1(nodes) {
8001 return nodes.map(function(i2) {
8002 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
8003 delete i2.source;
8004 return i2;
8005 });
8006 }
8007 function markDirtyUp$1(node2) {
8008 node2[isClean$1$1] = false;
8009 if (node2.proxyOf.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
8010 var i2 = _step.value;
8011 markDirtyUp$1(i2);
8012 }
8013 }
8014 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
8015 _inherits(Container, Node$1$1);
8016 function Container() {
8017 return Node$1$1.apply(this, arguments) || this;
8018 }
8019 var _proto = Container.prototype;
8020 _proto.append = function append() {
8021 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8022 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
8023 var child = _step.value;
8024 for (var _iterator1 = _create_for_of_iterator_helper_loose(this.normalize(child, this.last)), _step1; !(_step1 = _iterator1()).done;) {
8025 var node2 = _step1.value;
8026 this.proxyOf.nodes.push(node2);
8027 }
8028 }
8029 this.markDirty();
8030 return this;
8031 };
8032 _proto.cleanRaws = function cleanRaws(keepBetween) {
8033 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
8034 if (this.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;) _step.value.cleanRaws(keepBetween);
8035 };
8036 _proto.each = function each(callback) {
8037 if (!this.proxyOf.nodes) return void 0;
8038 var iterator = this.getIterator();
8039 var index2;
8040 var result2;
8041 while (this.indexes[iterator] < this.proxyOf.nodes.length) {
8042 index2 = this.indexes[iterator];
8043 result2 = callback(this.proxyOf.nodes[index2], index2);
8044 if (result2 === false) break;
8045 this.indexes[iterator] += 1;
8046 }
8047 delete this.indexes[iterator];
8048 return result2;
8049 };
8050 _proto.every = function every(condition) {
8051 return this.nodes.every(condition);
8052 };
8053 _proto.getIterator = function getIterator() {
8054 if (!this.lastEach) this.lastEach = 0;
8055 if (!this.indexes) this.indexes = {};
8056 this.lastEach += 1;
8057 var iterator = this.lastEach;
8058 this.indexes[iterator] = 0;
8059 return iterator;
8060 };
8061 _proto.getProxyProcessor = function getProxyProcessor() {
8062 return {
8063 get: function get(node2, prop) {
8064 if (prop === "proxyOf") return node2;
8065 else if (!node2[prop]) return node2[prop];
8066 else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) return function() {
8067 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
8068 var _node2;
8069 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
8070 if (typeof i2 === "function") return function(child, index2) {
8071 return i2(child.toProxy(), index2);
8072 };
8073 else return i2;
8074 })));
8075 };
8076 else if (prop === "every" || prop === "some") return function(cb) {
8077 return node2[prop](function(child) {
8078 for (var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) other[_key - 1] = arguments[_key];
8079 return cb.apply(void 0, [].concat([child.toProxy()], other));
8080 });
8081 };
8082 else if (prop === "root") return function() {
8083 return node2.root().toProxy();
8084 };
8085 else if (prop === "nodes") return node2.nodes.map(function(i2) {
8086 return i2.toProxy();
8087 });
8088 else if (prop === "first" || prop === "last") return node2[prop].toProxy();
8089 else return node2[prop];
8090 },
8091 set: function set(node2, prop, value) {
8092 if (node2[prop] === value) return true;
8093 node2[prop] = value;
8094 if (prop === "name" || prop === "params" || prop === "selector") node2.markDirty();
8095 return true;
8096 }
8097 };
8098 };
8099 _proto.index = function index(child) {
8100 if (typeof child === "number") return child;
8101 if (child.proxyOf) child = child.proxyOf;
8102 return this.proxyOf.nodes.indexOf(child);
8103 };
8104 _proto.insertAfter = function insertAfter(exist, add) {
8105 var existIndex = this.index(exist);
8106 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
8107 existIndex = this.index(exist);
8108 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8109 var node2 = _step.value;
8110 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
8111 }
8112 var index2;
8113 for (var id in this.indexes) {
8114 index2 = this.indexes[id];
8115 if (existIndex < index2) this.indexes[id] = index2 + nodes.length;
8116 }
8117 this.markDirty();
8118 return this;
8119 };
8120 _proto.insertBefore = function insertBefore(exist, add) {
8121 var existIndex = this.index(exist);
8122 var type = existIndex === 0 ? "prepend" : false;
8123 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
8124 existIndex = this.index(exist);
8125 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8126 var node2 = _step.value;
8127 this.proxyOf.nodes.splice(existIndex, 0, node2);
8128 }
8129 var index2;
8130 for (var id in this.indexes) {
8131 index2 = this.indexes[id];
8132 if (existIndex <= index2) this.indexes[id] = index2 + nodes.length;
8133 }
8134 this.markDirty();
8135 return this;
8136 };
8137 _proto.normalize = function normalize(nodes, sample) {
8138 var _this = this;
8139 if (typeof nodes === "string") nodes = cleanSource$1(parse$4$1(nodes).nodes);
8140 else if (typeof nodes === "undefined") nodes = [];
8141 else if (Array.isArray(nodes)) {
8142 nodes = nodes.slice(0);
8143 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8144 var i2 = _step.value;
8145 if (i2.parent) i2.parent.removeChild(i2, "ignore");
8146 }
8147 } else if (nodes.type === "root" && this.type !== "document") {
8148 nodes = nodes.nodes.slice(0);
8149 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
8150 var i21 = _step1.value;
8151 if (i21.parent) i21.parent.removeChild(i21, "ignore");
8152 }
8153 } else if (nodes.type) nodes = [nodes];
8154 else if (nodes.prop) {
8155 if (typeof nodes.value === "undefined") throw new Error("Value field is missed in node creation");
8156 else if (typeof nodes.value !== "string") nodes.value = String(nodes.value);
8157 nodes = [new Declaration$3$1(nodes)];
8158 } else if (nodes.selector) nodes = [new Rule$4$1(nodes)];
8159 else if (nodes.name) nodes = [new AtRule$4$1(nodes)];
8160 else if (nodes.text) nodes = [new Comment$3$1(nodes)];
8161 else throw new Error("Unknown node type in node creation");
8162 return nodes.map(function(i2) {
8163 if (!i2[my$1$1]) Container.rebuild(i2);
8164 i2 = i2.proxyOf;
8165 if (i2.parent) i2.parent.removeChild(i2);
8166 if (i2[isClean$1$1]) markDirtyUp$1(i2);
8167 if (typeof i2.raws.before === "undefined") {
8168 if (sample && typeof sample.raws.before !== "undefined") i2.raws.before = sample.raws.before.replace(/\S/g, "");
8169 }
8170 i2.parent = _this.proxyOf;
8171 return i2;
8172 });
8173 };
8174 _proto.prepend = function prepend() {
8175 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8176 children = children.reverse();
8177 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
8178 var child = _step.value;
8179 var nodes = this.normalize(child, this.first, "prepend").reverse();
8180 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
8181 var node2 = _step1.value;
8182 this.proxyOf.nodes.unshift(node2);
8183 }
8184 for (var id in this.indexes) this.indexes[id] = this.indexes[id] + nodes.length;
8185 }
8186 this.markDirty();
8187 return this;
8188 };
8189 _proto.push = function push(child) {
8190 child.parent = this;
8191 this.proxyOf.nodes.push(child);
8192 return this;
8193 };
8194 _proto.removeAll = function removeAll() {
8195 for (var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
8196 var node2 = _step.value;
8197 node2.parent = void 0;
8198 }
8199 this.proxyOf.nodes = [];
8200 this.markDirty();
8201 return this;
8202 };
8203 _proto.removeChild = function removeChild(child) {
8204 child = this.index(child);
8205 this.proxyOf.nodes[child].parent = void 0;
8206 this.proxyOf.nodes.splice(child, 1);
8207 var index2;
8208 for (var id in this.indexes) {
8209 index2 = this.indexes[id];
8210 if (index2 >= child) this.indexes[id] = index2 - 1;
8211 }
8212 this.markDirty();
8213 return this;
8214 };
8215 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
8216 if (!callback) {
8217 callback = opts;
8218 opts = {};
8219 }
8220 this.walkDecls(function(decl) {
8221 if (opts.props && !opts.props.includes(decl.prop)) return;
8222 if (opts.fast && !decl.value.includes(opts.fast)) return;
8223 decl.value = decl.value.replace(pattern, callback);
8224 });
8225 this.markDirty();
8226 return this;
8227 };
8228 _proto.some = function some(condition) {
8229 return this.nodes.some(condition);
8230 };
8231 _proto.walk = function walk(callback) {
8232 return this.each(function(child, i2) {
8233 var result2;
8234 try {
8235 result2 = callback(child, i2);
8236 } catch (e2) {
8237 throw child.addToError(e2);
8238 }
8239 if (result2 !== false && child.walk) result2 = child.walk(callback);
8240 return result2;
8241 });
8242 };
8243 _proto.walkAtRules = function walkAtRules(name, callback) {
8244 if (!callback) {
8245 callback = name;
8246 return this.walk(function(child, i2) {
8247 if (child.type === "atrule") return callback(child, i2);
8248 });
8249 }
8250 if (_instanceof(name, RegExp)) return this.walk(function(child, i2) {
8251 if (child.type === "atrule" && name.test(child.name)) return callback(child, i2);
8252 });
8253 return this.walk(function(child, i2) {
8254 if (child.type === "atrule" && child.name === name) return callback(child, i2);
8255 });
8256 };
8257 _proto.walkComments = function walkComments(callback) {
8258 return this.walk(function(child, i2) {
8259 if (child.type === "comment") return callback(child, i2);
8260 });
8261 };
8262 _proto.walkDecls = function walkDecls(prop, callback) {
8263 if (!callback) {
8264 callback = prop;
8265 return this.walk(function(child, i2) {
8266 if (child.type === "decl") return callback(child, i2);
8267 });
8268 }
8269 if (_instanceof(prop, RegExp)) return this.walk(function(child, i2) {
8270 if (child.type === "decl" && prop.test(child.prop)) return callback(child, i2);
8271 });
8272 return this.walk(function(child, i2) {
8273 if (child.type === "decl" && child.prop === prop) return callback(child, i2);
8274 });
8275 };
8276 _proto.walkRules = function walkRules(selector, callback) {
8277 if (!callback) {
8278 callback = selector;
8279 return this.walk(function(child, i2) {
8280 if (child.type === "rule") return callback(child, i2);
8281 });
8282 }
8283 if (_instanceof(selector, RegExp)) return this.walk(function(child, i2) {
8284 if (child.type === "rule" && selector.test(child.selector)) return callback(child, i2);
8285 });
8286 return this.walk(function(child, i2) {
8287 if (child.type === "rule" && child.selector === selector) return callback(child, i2);
8288 });
8289 };
8290 _create_class(Container, [{
8291 key: "first",
8292 get: function get() {
8293 if (!this.proxyOf.nodes) return void 0;
8294 return this.proxyOf.nodes[0];
8295 }
8296 }, {
8297 key: "last",
8298 get: function get() {
8299 if (!this.proxyOf.nodes) return void 0;
8300 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
8301 }
8302 }]);
8303 return Container;
8304 }(Node$1$1);
8305 Container$7$1.registerParse = function(dependant) {
8306 parse$4$1 = dependant;
8307 };
8308 Container$7$1.registerRule = function(dependant) {
8309 Rule$4$1 = dependant;
8310 };
8311 Container$7$1.registerAtRule = function(dependant) {
8312 AtRule$4$1 = dependant;
8313 };
8314 Container$7$1.registerRoot = function(dependant) {
8315 Root$6$1 = dependant;
8316 };
8317 var container$1 = Container$7$1;
8318 Container$7$1.default = Container$7$1;
8319 Container$7$1.rebuild = function(node2) {
8320 if (node2.type === "atrule") Object.setPrototypeOf(node2, AtRule$4$1.prototype);
8321 else if (node2.type === "rule") Object.setPrototypeOf(node2, Rule$4$1.prototype);
8322 else if (node2.type === "decl") Object.setPrototypeOf(node2, Declaration$3$1.prototype);
8323 else if (node2.type === "comment") Object.setPrototypeOf(node2, Comment$3$1.prototype);
8324 else if (node2.type === "root") Object.setPrototypeOf(node2, Root$6$1.prototype);
8325 node2[my$1$1] = true;
8326 if (node2.nodes) node2.nodes.forEach(function(child) {
8327 Container$7$1.rebuild(child);
8328 });
8329 };
8330 var Container$6$1 = container$1;
8331 var LazyResult$4$1;
8332 var Processor$3$1;
8333 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
8334 _inherits(Document2, Container$6$1);
8335 function Document2(defaults) {
8336 var _this = Container$6$1.call(this, _extends({ type: "document" }, defaults)) || this;
8337 if (!_this.nodes) _this.nodes = [];
8338 return _this;
8339 }
8340 var _proto = Document2.prototype;
8341 _proto.toResult = function toResult(opts) {
8342 if (opts === void 0) opts = {};
8343 return new LazyResult$4$1(new Processor$3$1(), this, opts).stringify();
8344 };
8345 return Document2;
8346 }(Container$6$1);
8347 Document$3$1.registerLazyResult = function(dependant) {
8348 LazyResult$4$1 = dependant;
8349 };
8350 Document$3$1.registerProcessor = function(dependant) {
8351 Processor$3$1 = dependant;
8352 };
8353 var document$1$1 = Document$3$1;
8354 Document$3$1.default = Document$3$1;
8355 var printed$1 = {};
8356 var warnOnce$2$1 = function warnOnce(message) {
8357 if (printed$1[message]) return;
8358 printed$1[message] = true;
8359 if (typeof console !== "undefined" && console.warn) console.warn(message);
8360 };
8361 var Warning$2$1 = /*#__PURE__*/ function() {
8362 function Warning(text, opts) {
8363 if (opts === void 0) opts = {};
8364 this.type = "warning";
8365 this.text = text;
8366 if (opts.node && opts.node.source) {
8367 var range = opts.node.rangeBy(opts);
8368 this.line = range.start.line;
8369 this.column = range.start.column;
8370 this.endLine = range.end.line;
8371 this.endColumn = range.end.column;
8372 }
8373 for (var opt in opts) this[opt] = opts[opt];
8374 }
8375 var _proto = Warning.prototype;
8376 _proto.toString = function toString() {
8377 if (this.node) return this.node.error(this.text, {
8378 index: this.index,
8379 plugin: this.plugin,
8380 word: this.word
8381 }).message;
8382 if (this.plugin) return this.plugin + ": " + this.text;
8383 return this.text;
8384 };
8385 return Warning;
8386 }();
8387 var warning$1 = Warning$2$1;
8388 Warning$2$1.default = Warning$2$1;
8389 var Warning$1$1 = warning$1;
8390 var Result$3$1 = /*#__PURE__*/ function() {
8391 function Result(processor2, root2, opts) {
8392 this.processor = processor2;
8393 this.messages = [];
8394 this.root = root2;
8395 this.opts = opts;
8396 this.css = void 0;
8397 this.map = void 0;
8398 }
8399 var _proto = Result.prototype;
8400 _proto.toString = function toString() {
8401 return this.css;
8402 };
8403 _proto.warn = function warn(text, opts) {
8404 if (opts === void 0) opts = {};
8405 if (!opts.plugin) {
8406 if (this.lastPlugin && this.lastPlugin.postcssPlugin) opts.plugin = this.lastPlugin.postcssPlugin;
8407 }
8408 var warning2 = new Warning$1$1(text, opts);
8409 this.messages.push(warning2);
8410 return warning2;
8411 };
8412 _proto.warnings = function warnings() {
8413 return this.messages.filter(function(i2) {
8414 return i2.type === "warning";
8415 });
8416 };
8417 _create_class(Result, [{
8418 key: "content",
8419 get: function get() {
8420 return this.css;
8421 }
8422 }]);
8423 return Result;
8424 }();
8425 var result$1 = Result$3$1;
8426 Result$3$1.default = Result$3$1;
8427 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
8428 var DOUBLE_QUOTE$1 = "\"".charCodeAt(0);
8429 var BACKSLASH$1 = "\\".charCodeAt(0);
8430 var SLASH$1 = "/".charCodeAt(0);
8431 var NEWLINE$1 = "\n".charCodeAt(0);
8432 var SPACE$1 = " ".charCodeAt(0);
8433 var FEED$1 = "\f".charCodeAt(0);
8434 var TAB$1 = " ".charCodeAt(0);
8435 var CR$1 = "\r".charCodeAt(0);
8436 var OPEN_SQUARE$1 = "[".charCodeAt(0);
8437 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
8438 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
8439 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
8440 var OPEN_CURLY$1 = "{".charCodeAt(0);
8441 var CLOSE_CURLY$1 = "}".charCodeAt(0);
8442 var SEMICOLON$1 = ";".charCodeAt(0);
8443 var ASTERISK$1 = "*".charCodeAt(0);
8444 var COLON$1 = ":".charCodeAt(0);
8445 var AT$1 = "@".charCodeAt(0);
8446 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
8447 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
8448 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
8449 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
8450 var tokenize$1 = function tokenizer(input2, options) {
8451 if (options === void 0) options = {};
8452 var css = input2.css.valueOf();
8453 var ignore = options.ignoreErrors;
8454 var code;
8455 var next;
8456 var quote;
8457 var content;
8458 var escape;
8459 var escaped;
8460 var escapePos;
8461 var prev;
8462 var n2;
8463 var currentToken;
8464 var length = css.length;
8465 var pos = 0;
8466 var buffer = [];
8467 var returned = [];
8468 function position() {
8469 return pos;
8470 }
8471 function unclosed(what) {
8472 throw input2.error("Unclosed " + what, pos);
8473 }
8474 function endOfFile() {
8475 return returned.length === 0 && pos >= length;
8476 }
8477 function nextToken(opts) {
8478 if (returned.length) return returned.pop();
8479 if (pos >= length) return;
8480 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
8481 code = css.charCodeAt(pos);
8482 switch (code) {
8483 case NEWLINE$1:
8484 case SPACE$1:
8485 case TAB$1:
8486 case CR$1:
8487 case FEED$1:
8488 next = pos;
8489 do {
8490 next += 1;
8491 code = css.charCodeAt(next);
8492 } while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
8493 currentToken = ["space", css.slice(pos, next)];
8494 pos = next - 1;
8495 break;
8496 case OPEN_SQUARE$1:
8497 case CLOSE_SQUARE$1:
8498 case OPEN_CURLY$1:
8499 case CLOSE_CURLY$1:
8500 case COLON$1:
8501 case SEMICOLON$1:
8502 case CLOSE_PARENTHESES$1:
8503 var controlChar = String.fromCharCode(code);
8504 currentToken = [
8505 controlChar,
8506 controlChar,
8507 pos
8508 ];
8509 break;
8510 case OPEN_PARENTHESES$1:
8511 prev = buffer.length ? buffer.pop()[1] : "";
8512 n2 = css.charCodeAt(pos + 1);
8513 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) {
8514 next = pos;
8515 do {
8516 escaped = false;
8517 next = css.indexOf(")", next + 1);
8518 if (next === -1) if (ignore || ignoreUnclosed) {
8519 next = pos;
8520 break;
8521 } else unclosed("bracket");
8522 escapePos = next;
8523 while (css.charCodeAt(escapePos - 1) === BACKSLASH$1) {
8524 escapePos -= 1;
8525 escaped = !escaped;
8526 }
8527 } while (escaped);
8528 currentToken = [
8529 "brackets",
8530 css.slice(pos, next + 1),
8531 pos,
8532 next
8533 ];
8534 pos = next;
8535 } else {
8536 next = css.indexOf(")", pos + 1);
8537 content = css.slice(pos, next + 1);
8538 if (next === -1 || RE_BAD_BRACKET$1.test(content)) currentToken = [
8539 "(",
8540 "(",
8541 pos
8542 ];
8543 else {
8544 currentToken = [
8545 "brackets",
8546 content,
8547 pos,
8548 next
8549 ];
8550 pos = next;
8551 }
8552 }
8553 break;
8554 case SINGLE_QUOTE$1:
8555 case DOUBLE_QUOTE$1:
8556 quote = code === SINGLE_QUOTE$1 ? "'" : "\"";
8557 next = pos;
8558 do {
8559 escaped = false;
8560 next = css.indexOf(quote, next + 1);
8561 if (next === -1) if (ignore || ignoreUnclosed) {
8562 next = pos + 1;
8563 break;
8564 } else unclosed("string");
8565 escapePos = next;
8566 while (css.charCodeAt(escapePos - 1) === BACKSLASH$1) {
8567 escapePos -= 1;
8568 escaped = !escaped;
8569 }
8570 } while (escaped);
8571 currentToken = [
8572 "string",
8573 css.slice(pos, next + 1),
8574 pos,
8575 next
8576 ];
8577 pos = next;
8578 break;
8579 case AT$1:
8580 RE_AT_END$1.lastIndex = pos + 1;
8581 RE_AT_END$1.test(css);
8582 if (RE_AT_END$1.lastIndex === 0) next = css.length - 1;
8583 else next = RE_AT_END$1.lastIndex - 2;
8584 currentToken = [
8585 "at-word",
8586 css.slice(pos, next + 1),
8587 pos,
8588 next
8589 ];
8590 pos = next;
8591 break;
8592 case BACKSLASH$1:
8593 next = pos;
8594 escape = true;
8595 while (css.charCodeAt(next + 1) === BACKSLASH$1) {
8596 next += 1;
8597 escape = !escape;
8598 }
8599 code = css.charCodeAt(next + 1);
8600 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
8601 next += 1;
8602 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
8603 while (RE_HEX_ESCAPE$1.test(css.charAt(next + 1))) next += 1;
8604 if (css.charCodeAt(next + 1) === SPACE$1) next += 1;
8605 }
8606 }
8607 currentToken = [
8608 "word",
8609 css.slice(pos, next + 1),
8610 pos,
8611 next
8612 ];
8613 pos = next;
8614 break;
8615 default:
8616 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
8617 next = css.indexOf("*/", pos + 2) + 1;
8618 if (next === 0) if (ignore || ignoreUnclosed) next = css.length;
8619 else unclosed("comment");
8620 currentToken = [
8621 "comment",
8622 css.slice(pos, next + 1),
8623 pos,
8624 next
8625 ];
8626 pos = next;
8627 } else {
8628 RE_WORD_END$1.lastIndex = pos + 1;
8629 RE_WORD_END$1.test(css);
8630 if (RE_WORD_END$1.lastIndex === 0) next = css.length - 1;
8631 else next = RE_WORD_END$1.lastIndex - 2;
8632 currentToken = [
8633 "word",
8634 css.slice(pos, next + 1),
8635 pos,
8636 next
8637 ];
8638 buffer.push(currentToken);
8639 pos = next;
8640 }
8641 break;
8642 }
8643 pos++;
8644 return currentToken;
8645 }
8646 function back(token) {
8647 returned.push(token);
8648 }
8649 return {
8650 back,
8651 endOfFile,
8652 nextToken,
8653 position
8654 };
8655 };
8656 var Container$5$1 = container$1;
8657 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
8658 _inherits(AtRule, Container$5$1);
8659 function AtRule(defaults) {
8660 var _this = Container$5$1.call(this, defaults) || this;
8661 _this.type = "atrule";
8662 return _this;
8663 }
8664 var _proto = AtRule.prototype;
8665 _proto.append = function append() {
8666 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8667 var _Container$5$1_prototype_append;
8668 if (!this.proxyOf.nodes) this.nodes = [];
8669 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([this], children));
8670 };
8671 _proto.prepend = function prepend() {
8672 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
8673 var _Container$5$1_prototype_prepend;
8674 if (!this.proxyOf.nodes) this.nodes = [];
8675 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([this], children));
8676 };
8677 return AtRule;
8678 }(Container$5$1);
8679 var atRule$1 = AtRule$3$1;
8680 AtRule$3$1.default = AtRule$3$1;
8681 Container$5$1.registerAtRule(AtRule$3$1);
8682 var Container$4$1 = container$1;
8683 var LazyResult$3$1;
8684 var Processor$2$1;
8685 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
8686 _inherits(Root, Container$4$1);
8687 function Root(defaults) {
8688 var _this = Container$4$1.call(this, defaults) || this;
8689 _this.type = "root";
8690 if (!_this.nodes) _this.nodes = [];
8691 return _this;
8692 }
8693 var _proto = Root.prototype;
8694 _proto.normalize = function normalize(child, sample, type) {
8695 var nodes = Container$4$1.prototype.normalize.call(this, child);
8696 if (sample) {
8697 if (type === "prepend") if (this.nodes.length > 1) sample.raws.before = this.nodes[1].raws.before;
8698 else delete sample.raws.before;
8699 else if (this.first !== sample) for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
8700 var node2 = _step.value;
8701 node2.raws.before = sample.raws.before;
8702 }
8703 }
8704 return nodes;
8705 };
8706 _proto.removeChild = function removeChild(child, ignore) {
8707 var index2 = this.index(child);
8708 if (!ignore && index2 === 0 && this.nodes.length > 1) this.nodes[1].raws.before = this.nodes[index2].raws.before;
8709 return Container$4$1.prototype.removeChild.call(this, child);
8710 };
8711 _proto.toResult = function toResult(opts) {
8712 if (opts === void 0) opts = {};
8713 return new LazyResult$3$1(new Processor$2$1(), this, opts).stringify();
8714 };
8715 return Root;
8716 }(Container$4$1);
8717 Root$5$1.registerLazyResult = function(dependant) {
8718 LazyResult$3$1 = dependant;
8719 };
8720 Root$5$1.registerProcessor = function(dependant) {
8721 Processor$2$1 = dependant;
8722 };
8723 var root$1 = Root$5$1;
8724 Root$5$1.default = Root$5$1;
8725 Container$4$1.registerRoot(Root$5$1);
8726 var list$2$1 = {
8727 comma: function comma(string) {
8728 return list$2$1.split(string, [","], true);
8729 },
8730 space: function space(string) {
8731 return list$2$1.split(string, [
8732 " ",
8733 "\n",
8734 " "
8735 ]);
8736 },
8737 split: function split(string, separators, last) {
8738 var array = [];
8739 var current = "";
8740 var split = false;
8741 var func = 0;
8742 var inQuote = false;
8743 var prevQuote = "";
8744 var escape = false;
8745 for (var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;) {
8746 var letter = _step.value;
8747 if (escape) escape = false;
8748 else if (letter === "\\") escape = true;
8749 else if (inQuote) {
8750 if (letter === prevQuote) inQuote = false;
8751 } else if (letter === "\"" || letter === "'") {
8752 inQuote = true;
8753 prevQuote = letter;
8754 } else if (letter === "(") func += 1;
8755 else if (letter === ")") {
8756 if (func > 0) func -= 1;
8757 } else if (func === 0) {
8758 if (separators.includes(letter)) split = true;
8759 }
8760 if (split) {
8761 if (current !== "") array.push(current.trim());
8762 current = "";
8763 split = false;
8764 } else current += letter;
8765 }
8766 if (last || current !== "") array.push(current.trim());
8767 return array;
8768 }
8769 };
8770 var list_1$1 = list$2$1;
8771 list$2$1.default = list$2$1;
8772 var Container$3$1 = container$1;
8773 var list$1$1 = list_1$1;
8774 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
8775 _inherits(Rule, Container$3$1);
8776 function Rule(defaults) {
8777 var _this = Container$3$1.call(this, defaults) || this;
8778 _this.type = "rule";
8779 if (!_this.nodes) _this.nodes = [];
8780 return _this;
8781 }
8782 _create_class(Rule, [{
8783 key: "selectors",
8784 get: function get() {
8785 return list$1$1.comma(this.selector);
8786 },
8787 set: function set(values) {
8788 var match = this.selector ? this.selector.match(/,\s*/) : null;
8789 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
8790 this.selector = values.join(sep2);
8791 }
8792 }]);
8793 return Rule;
8794 }(Container$3$1);
8795 var rule$1 = Rule$3$1;
8796 Rule$3$1.default = Rule$3$1;
8797 Container$3$1.registerRule(Rule$3$1);
8798 var Declaration$2$1 = declaration$1;
8799 var tokenizer2$1 = tokenize$1;
8800 var Comment$2$1 = comment$1;
8801 var AtRule$2$1 = atRule$1;
8802 var Root$4$1 = root$1;
8803 var Rule$2$1 = rule$1;
8804 var SAFE_COMMENT_NEIGHBOR$1 = {
8805 empty: true,
8806 space: true
8807 };
8808 function findLastWithPosition$1(tokens) {
8809 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
8810 var token = tokens[i2];
8811 var pos = token[3] || token[2];
8812 if (pos) return pos;
8813 }
8814 }
8815 var parser$1 = /* @__PURE__ */ function() {
8816 function Parser(input2) {
8817 this.input = input2;
8818 this.root = new Root$4$1();
8819 this.current = this.root;
8820 this.spaces = "";
8821 this.semicolon = false;
8822 this.createTokenizer();
8823 this.root.source = {
8824 input: input2,
8825 start: {
8826 column: 1,
8827 line: 1,
8828 offset: 0
8829 }
8830 };
8831 }
8832 var _proto = Parser.prototype;
8833 _proto.atrule = function atrule(token) {
8834 var node2 = new AtRule$2$1();
8835 node2.name = token[1].slice(1);
8836 if (node2.name === "") this.unnamedAtrule(node2, token);
8837 this.init(node2, token[2]);
8838 var type;
8839 var prev;
8840 var shift;
8841 var last = false;
8842 var open = false;
8843 var params = [];
8844 var brackets = [];
8845 while (!this.tokenizer.endOfFile()) {
8846 token = this.tokenizer.nextToken();
8847 type = token[0];
8848 if (type === "(" || type === "[") brackets.push(type === "(" ? ")" : "]");
8849 else if (type === "{" && brackets.length > 0) brackets.push("}");
8850 else if (type === brackets[brackets.length - 1]) brackets.pop();
8851 if (brackets.length === 0) if (type === ";") {
8852 node2.source.end = this.getPosition(token[2]);
8853 node2.source.end.offset++;
8854 this.semicolon = true;
8855 break;
8856 } else if (type === "{") {
8857 open = true;
8858 break;
8859 } else if (type === "}") {
8860 if (params.length > 0) {
8861 shift = params.length - 1;
8862 prev = params[shift];
8863 while (prev && prev[0] === "space") prev = params[--shift];
8864 if (prev) {
8865 node2.source.end = this.getPosition(prev[3] || prev[2]);
8866 node2.source.end.offset++;
8867 }
8868 }
8869 this.end(token);
8870 break;
8871 } else params.push(token);
8872 else params.push(token);
8873 if (this.tokenizer.endOfFile()) {
8874 last = true;
8875 break;
8876 }
8877 }
8878 node2.raws.between = this.spacesAndCommentsFromEnd(params);
8879 if (params.length) {
8880 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
8881 this.raw(node2, "params", params);
8882 if (last) {
8883 token = params[params.length - 1];
8884 node2.source.end = this.getPosition(token[3] || token[2]);
8885 node2.source.end.offset++;
8886 this.spaces = node2.raws.between;
8887 node2.raws.between = "";
8888 }
8889 } else {
8890 node2.raws.afterName = "";
8891 node2.params = "";
8892 }
8893 if (open) {
8894 node2.nodes = [];
8895 this.current = node2;
8896 }
8897 };
8898 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
8899 var colon = this.colon(tokens);
8900 if (colon === false) return;
8901 var founded = 0;
8902 var token;
8903 for (var j = colon - 1; j >= 0; j--) {
8904 token = tokens[j];
8905 if (token[0] !== "space") {
8906 founded += 1;
8907 if (founded === 2) break;
8908 }
8909 }
8910 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
8911 };
8912 _proto.colon = function colon(tokens) {
8913 var brackets = 0;
8914 var token;
8915 var type;
8916 var prev;
8917 for (var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;) {
8918 var _step_value = _step.value;
8919 var i2 = _step_value[0];
8920 token = _step_value[1];
8921 type = token[0];
8922 if (type === "(") brackets += 1;
8923 if (type === ")") brackets -= 1;
8924 if (brackets === 0 && type === ":") if (!prev) this.doubleColon(token);
8925 else if (prev[0] === "word" && prev[1] === "progid") continue;
8926 else return i2;
8927 prev = token;
8928 }
8929 return false;
8930 };
8931 _proto.comment = function comment(token) {
8932 var node2 = new Comment$2$1();
8933 this.init(node2, token[2]);
8934 node2.source.end = this.getPosition(token[3] || token[2]);
8935 node2.source.end.offset++;
8936 var text = token[1].slice(2, -2);
8937 if (/^\s*$/.test(text)) {
8938 node2.text = "";
8939 node2.raws.left = text;
8940 node2.raws.right = "";
8941 } else {
8942 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
8943 node2.text = match[2];
8944 node2.raws.left = match[1];
8945 node2.raws.right = match[3];
8946 }
8947 };
8948 _proto.createTokenizer = function createTokenizer() {
8949 this.tokenizer = tokenizer2$1(this.input);
8950 };
8951 _proto.decl = function decl(tokens, customProperty) {
8952 var node2 = new Declaration$2$1();
8953 this.init(node2, tokens[0][2]);
8954 var last = tokens[tokens.length - 1];
8955 if (last[0] === ";") {
8956 this.semicolon = true;
8957 tokens.pop();
8958 }
8959 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
8960 node2.source.end.offset++;
8961 while (tokens[0][0] !== "word") {
8962 if (tokens.length === 1) this.unknownWord(tokens);
8963 node2.raws.before += tokens.shift()[1];
8964 }
8965 node2.source.start = this.getPosition(tokens[0][2]);
8966 node2.prop = "";
8967 while (tokens.length) {
8968 var type = tokens[0][0];
8969 if (type === ":" || type === "space" || type === "comment") break;
8970 node2.prop += tokens.shift()[1];
8971 }
8972 node2.raws.between = "";
8973 var token;
8974 while (tokens.length) {
8975 token = tokens.shift();
8976 if (token[0] === ":") {
8977 node2.raws.between += token[1];
8978 break;
8979 } else {
8980 if (token[0] === "word" && /\w/.test(token[1])) this.unknownWord([token]);
8981 node2.raws.between += token[1];
8982 }
8983 }
8984 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
8985 node2.raws.before += node2.prop[0];
8986 node2.prop = node2.prop.slice(1);
8987 }
8988 var firstSpaces = [];
8989 var next;
8990 while (tokens.length) {
8991 next = tokens[0][0];
8992 if (next !== "space" && next !== "comment") break;
8993 firstSpaces.push(tokens.shift());
8994 }
8995 this.precheckMissedSemicolon(tokens);
8996 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
8997 token = tokens[i2];
8998 if (token[1].toLowerCase() === "!important") {
8999 node2.important = true;
9000 var string = this.stringFrom(tokens, i2);
9001 string = this.spacesFromEnd(tokens) + string;
9002 if (string !== " !important") node2.raws.important = string;
9003 break;
9004 } else if (token[1].toLowerCase() === "important") {
9005 var cache = tokens.slice(0);
9006 var str = "";
9007 for (var j = i2; j > 0; j--) {
9008 var type1 = cache[j][0];
9009 if (str.trim().indexOf("!") === 0 && type1 !== "space") break;
9010 str = cache.pop()[1] + str;
9011 }
9012 if (str.trim().indexOf("!") === 0) {
9013 node2.important = true;
9014 node2.raws.important = str;
9015 tokens = cache;
9016 }
9017 }
9018 if (token[0] !== "space" && token[0] !== "comment") break;
9019 }
9020 if (tokens.some(function(i2) {
9021 return i2[0] !== "space" && i2[0] !== "comment";
9022 })) {
9023 node2.raws.between += firstSpaces.map(function(i2) {
9024 return i2[1];
9025 }).join("");
9026 firstSpaces = [];
9027 }
9028 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
9029 if (node2.value.includes(":") && !customProperty) this.checkMissedSemicolon(tokens);
9030 };
9031 _proto.doubleColon = function doubleColon(token) {
9032 throw this.input.error("Double colon", { offset: token[2] }, { offset: token[2] + token[1].length });
9033 };
9034 _proto.emptyRule = function emptyRule(token) {
9035 var node2 = new Rule$2$1();
9036 this.init(node2, token[2]);
9037 node2.selector = "";
9038 node2.raws.between = "";
9039 this.current = node2;
9040 };
9041 _proto.end = function end(token) {
9042 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
9043 this.semicolon = false;
9044 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
9045 this.spaces = "";
9046 if (this.current.parent) {
9047 this.current.source.end = this.getPosition(token[2]);
9048 this.current.source.end.offset++;
9049 this.current = this.current.parent;
9050 } else this.unexpectedClose(token);
9051 };
9052 _proto.endFile = function endFile() {
9053 if (this.current.parent) this.unclosedBlock();
9054 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
9055 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
9056 this.root.source.end = this.getPosition(this.tokenizer.position());
9057 };
9058 _proto.freeSemicolon = function freeSemicolon(token) {
9059 this.spaces += token[1];
9060 if (this.current.nodes) {
9061 var prev = this.current.nodes[this.current.nodes.length - 1];
9062 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
9063 prev.raws.ownSemicolon = this.spaces;
9064 this.spaces = "";
9065 }
9066 }
9067 };
9068 _proto.getPosition = function getPosition(offset) {
9069 var pos = this.input.fromOffset(offset);
9070 return {
9071 column: pos.col,
9072 line: pos.line,
9073 offset
9074 };
9075 };
9076 _proto.init = function init(node2, offset) {
9077 this.current.push(node2);
9078 node2.source = {
9079 input: this.input,
9080 start: this.getPosition(offset)
9081 };
9082 node2.raws.before = this.spaces;
9083 this.spaces = "";
9084 if (node2.type !== "comment") this.semicolon = false;
9085 };
9086 _proto.other = function other(start) {
9087 var end = false;
9088 var type = null;
9089 var colon = false;
9090 var bracket = null;
9091 var brackets = [];
9092 var customProperty = start[1].startsWith("--");
9093 var tokens = [];
9094 var token = start;
9095 while (token) {
9096 type = token[0];
9097 tokens.push(token);
9098 if (type === "(" || type === "[") {
9099 if (!bracket) bracket = token;
9100 brackets.push(type === "(" ? ")" : "]");
9101 } else if (customProperty && colon && type === "{") {
9102 if (!bracket) bracket = token;
9103 brackets.push("}");
9104 } else if (brackets.length === 0) {
9105 if (type === ";") if (colon) {
9106 this.decl(tokens, customProperty);
9107 return;
9108 } else break;
9109 else if (type === "{") {
9110 this.rule(tokens);
9111 return;
9112 } else if (type === "}") {
9113 this.tokenizer.back(tokens.pop());
9114 end = true;
9115 break;
9116 } else if (type === ":") colon = true;
9117 } else if (type === brackets[brackets.length - 1]) {
9118 brackets.pop();
9119 if (brackets.length === 0) bracket = null;
9120 }
9121 token = this.tokenizer.nextToken();
9122 }
9123 if (this.tokenizer.endOfFile()) end = true;
9124 if (brackets.length > 0) this.unclosedBracket(bracket);
9125 if (end && colon) {
9126 if (!customProperty) while (tokens.length) {
9127 token = tokens[tokens.length - 1][0];
9128 if (token !== "space" && token !== "comment") break;
9129 this.tokenizer.back(tokens.pop());
9130 }
9131 this.decl(tokens, customProperty);
9132 } else this.unknownWord(tokens);
9133 };
9134 _proto.parse = function parse() {
9135 var token;
9136 while (!this.tokenizer.endOfFile()) {
9137 token = this.tokenizer.nextToken();
9138 switch (token[0]) {
9139 case "space":
9140 this.spaces += token[1];
9141 break;
9142 case ";":
9143 this.freeSemicolon(token);
9144 break;
9145 case "}":
9146 this.end(token);
9147 break;
9148 case "comment":
9149 this.comment(token);
9150 break;
9151 case "at-word":
9152 this.atrule(token);
9153 break;
9154 case "{":
9155 this.emptyRule(token);
9156 break;
9157 default:
9158 this.other(token);
9159 break;
9160 }
9161 }
9162 this.endFile();
9163 };
9164 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
9165 _proto.raw = function raw(node2, prop, tokens, customProperty) {
9166 var token;
9167 var type;
9168 var length = tokens.length;
9169 var value = "";
9170 var clean = true;
9171 var next;
9172 var prev;
9173 for (var i2 = 0; i2 < length; i2 += 1) {
9174 token = tokens[i2];
9175 type = token[0];
9176 if (type === "space" && i2 === length - 1 && !customProperty) clean = false;
9177 else if (type === "comment") {
9178 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
9179 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
9180 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) if (value.slice(-1) === ",") clean = false;
9181 else value += token[1];
9182 else clean = false;
9183 } else value += token[1];
9184 }
9185 if (!clean) {
9186 var raw = tokens.reduce(function(all, i2) {
9187 return all + i2[1];
9188 }, "");
9189 node2.raws[prop] = {
9190 raw,
9191 value
9192 };
9193 }
9194 node2[prop] = value;
9195 };
9196 _proto.rule = function rule(tokens) {
9197 tokens.pop();
9198 var node2 = new Rule$2$1();
9199 this.init(node2, tokens[0][2]);
9200 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
9201 this.raw(node2, "selector", tokens);
9202 this.current = node2;
9203 };
9204 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
9205 var lastTokenType;
9206 var spaces = "";
9207 while (tokens.length) {
9208 lastTokenType = tokens[tokens.length - 1][0];
9209 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
9210 spaces = tokens.pop()[1] + spaces;
9211 }
9212 return spaces;
9213 };
9214 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
9215 var next;
9216 var spaces = "";
9217 while (tokens.length) {
9218 next = tokens[0][0];
9219 if (next !== "space" && next !== "comment") break;
9220 spaces += tokens.shift()[1];
9221 }
9222 return spaces;
9223 };
9224 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
9225 var lastTokenType;
9226 var spaces = "";
9227 while (tokens.length) {
9228 lastTokenType = tokens[tokens.length - 1][0];
9229 if (lastTokenType !== "space") break;
9230 spaces = tokens.pop()[1] + spaces;
9231 }
9232 return spaces;
9233 };
9234 _proto.stringFrom = function stringFrom(tokens, from) {
9235 var result2 = "";
9236 for (var i2 = from; i2 < tokens.length; i2++) result2 += tokens[i2][1];
9237 tokens.splice(from, tokens.length - from);
9238 return result2;
9239 };
9240 _proto.unclosedBlock = function unclosedBlock() {
9241 var pos = this.current.source.start;
9242 throw this.input.error("Unclosed block", pos.line, pos.column);
9243 };
9244 _proto.unclosedBracket = function unclosedBracket(bracket) {
9245 throw this.input.error("Unclosed bracket", { offset: bracket[2] }, { offset: bracket[2] + 1 });
9246 };
9247 _proto.unexpectedClose = function unexpectedClose(token) {
9248 throw this.input.error("Unexpected }", { offset: token[2] }, { offset: token[2] + 1 });
9249 };
9250 _proto.unknownWord = function unknownWord(tokens) {
9251 throw this.input.error("Unknown word", { offset: tokens[0][2] }, { offset: tokens[0][2] + tokens[0][1].length });
9252 };
9253 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
9254 throw this.input.error("At-rule without name", { offset: token[2] }, { offset: token[2] + token[1].length });
9255 };
9256 return Parser;
9257 }();
9258 var Container$2$1 = container$1;
9259 var Parser2$1 = parser$1;
9260 var Input$2$1 = input$1;
9261 function parse$3$1(css, opts) {
9262 var parser2 = new Parser2$1(new Input$2$1(css, opts));
9263 try {
9264 parser2.parse();
9265 } catch (e2) {
9266 if (e2.name === "CssSyntaxError" && opts && opts.from) {
9267 if (/\.scss$/i.test(opts.from)) e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
9268 else if (/\.sass/i.test(opts.from)) e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
9269 else if (/\.less$/i.test(opts.from)) e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
9270 }
9271 throw e2;
9272 }
9273 return parser2.root;
9274 }
9275 var parse_1$1 = parse$3$1;
9276 parse$3$1.default = parse$3$1;
9277 Container$2$1.registerParse(parse$3$1);
9278 var isClean$3 = symbols$1.isClean;
9279 var my$3 = symbols$1.my;
9280 var MapGenerator$1$1 = mapGenerator$1;
9281 var stringify$2$1 = stringify_1$1;
9282 var Container$1$1 = container$1;
9283 var Document$2$1 = document$1$1;
9284 var warnOnce$1$1 = warnOnce$2$1;
9285 var Result$2$1 = result$1;
9286 var parse$2$1 = parse_1$1;
9287 var Root$3$1 = root$1;
9288 var TYPE_TO_CLASS_NAME$1 = {
9289 atrule: "AtRule",
9290 comment: "Comment",
9291 decl: "Declaration",
9292 document: "Document",
9293 root: "Root",
9294 rule: "Rule"
9295 };
9296 var PLUGIN_PROPS$1 = {
9297 AtRule: true,
9298 AtRuleExit: true,
9299 Comment: true,
9300 CommentExit: true,
9301 Declaration: true,
9302 DeclarationExit: true,
9303 Document: true,
9304 DocumentExit: true,
9305 Once: true,
9306 OnceExit: true,
9307 postcssPlugin: true,
9308 prepare: true,
9309 Root: true,
9310 RootExit: true,
9311 Rule: true,
9312 RuleExit: true
9313 };
9314 var NOT_VISITORS$1 = {
9315 Once: true,
9316 postcssPlugin: true,
9317 prepare: true
9318 };
9319 var CHILDREN$1 = 0;
9320 function isPromise$1(obj) {
9321 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
9322 }
9323 function getEvents$1(node2) {
9324 var key = false;
9325 var type = TYPE_TO_CLASS_NAME$1[node2.type];
9326 if (node2.type === "decl") key = node2.prop.toLowerCase();
9327 else if (node2.type === "atrule") key = node2.name.toLowerCase();
9328 if (key && node2.append) return [
9329 type,
9330 type + "-" + key,
9331 CHILDREN$1,
9332 type + "Exit",
9333 type + "Exit-" + key
9334 ];
9335 else if (key) return [
9336 type,
9337 type + "-" + key,
9338 type + "Exit",
9339 type + "Exit-" + key
9340 ];
9341 else if (node2.append) return [
9342 type,
9343 CHILDREN$1,
9344 type + "Exit"
9345 ];
9346 else return [type, type + "Exit"];
9347 }
9348 function toStack$1(node2) {
9349 var events;
9350 if (node2.type === "document") events = [
9351 "Document",
9352 CHILDREN$1,
9353 "DocumentExit"
9354 ];
9355 else if (node2.type === "root") events = [
9356 "Root",
9357 CHILDREN$1,
9358 "RootExit"
9359 ];
9360 else events = getEvents$1(node2);
9361 return {
9362 eventIndex: 0,
9363 events,
9364 iterator: 0,
9365 node: node2,
9366 visitorIndex: 0,
9367 visitors: []
9368 };
9369 }
9370 function cleanMarks$1(node2) {
9371 node2[isClean$3] = false;
9372 if (node2.nodes) node2.nodes.forEach(function(i2) {
9373 return cleanMarks$1(i2);
9374 });
9375 return node2;
9376 }
9377 var postcss$2$1 = {};
9378 var LazyResult$2$1 = /*#__PURE__*/ function() {
9379 function LazyResult(processor2, css, opts) {
9380 var _this = this;
9381 this.stringified = false;
9382 this.processed = false;
9383 var root2;
9384 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) root2 = cleanMarks$1(css);
9385 else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
9386 root2 = cleanMarks$1(css.root);
9387 if (css.map) {
9388 if (typeof opts.map === "undefined") opts.map = {};
9389 if (!opts.map.inline) opts.map.inline = false;
9390 opts.map.prev = css.map;
9391 }
9392 } else {
9393 var parser2 = parse$2$1;
9394 if (opts.syntax) parser2 = opts.syntax.parse;
9395 if (opts.parser) parser2 = opts.parser;
9396 if (parser2.parse) parser2 = parser2.parse;
9397 try {
9398 root2 = parser2(css, opts);
9399 } catch (error) {
9400 this.processed = true;
9401 this.error = error;
9402 }
9403 if (root2 && !root2[my$3]) Container$1$1.rebuild(root2);
9404 }
9405 this.result = new Result$2$1(processor2, root2, opts);
9406 this.helpers = _extends({}, postcss$2$1, {
9407 postcss: postcss$2$1,
9408 result: this.result
9409 });
9410 this.plugins = this.processor.plugins.map(function(plugin22) {
9411 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) return _extends({}, plugin22, plugin22.prepare(_this.result));
9412 else return plugin22;
9413 });
9414 }
9415 var _proto = LazyResult.prototype;
9416 _proto.async = function async() {
9417 if (this.error) return Promise.reject(this.error);
9418 if (this.processed) return Promise.resolve(this.result);
9419 if (!this.processing) this.processing = this.runAsync();
9420 return this.processing;
9421 };
9422 _proto.catch = function _catch(onRejected) {
9423 return this.async().catch(onRejected);
9424 };
9425 _proto.finally = function _finally(onFinally) {
9426 return this.async().then(onFinally, onFinally);
9427 };
9428 _proto.getAsyncError = function getAsyncError() {
9429 throw new Error("Use process(css).then(cb) to work with async plugins");
9430 };
9431 _proto.handleError = function handleError(error, node2) {
9432 var plugin22 = this.result.lastPlugin;
9433 try {
9434 if (node2) node2.addToError(error);
9435 this.error = error;
9436 if (error.name === "CssSyntaxError" && !error.plugin) {
9437 error.plugin = plugin22.postcssPlugin;
9438 error.setMessage();
9439 } else if (plugin22.postcssVersion) {
9440 var pluginName = plugin22.postcssPlugin;
9441 var pluginVer = plugin22.postcssVersion;
9442 var runtimeVer = this.result.processor.version;
9443 var a2 = pluginVer.split(".");
9444 var b = runtimeVer.split(".");
9445 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) 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.");
9446 }
9447 } catch (err) {
9448 if (console && console.error) console.error(err);
9449 }
9450 return error;
9451 };
9452 _proto.prepareVisitors = function prepareVisitors() {
9453 var _this = this;
9454 this.listeners = {};
9455 var add = function(plugin22, type, cb) {
9456 if (!_this.listeners[type]) _this.listeners[type] = [];
9457 _this.listeners[type].push([plugin22, cb]);
9458 };
9459 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
9460 var plugin22 = _step.value;
9461 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") for (var event in plugin22) {
9462 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
9463 if (!NOT_VISITORS$1[event]) {
9464 if (_type_of(plugin22[event]) === "object") for (var filter in plugin22[event]) if (filter === "*") add(plugin22, event, plugin22[event][filter]);
9465 else add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
9466 else if (typeof plugin22[event] === "function") add(plugin22, event, plugin22[event]);
9467 }
9468 }
9469 }
9470 this.hasListener = Object.keys(this.listeners).length > 0;
9471 };
9472 _proto.runAsync = function runAsync() {
9473 var _this = this;
9474 return _async_to_generator(function() {
9475 var i2;
9476 var plugin22;
9477 var promise;
9478 var error;
9479 var root2;
9480 var stack;
9481 var promise1;
9482 var e2;
9483 var node2;
9484 var _loop;
9485 var _iterator;
9486 var _step;
9487 return _ts_generator(this, function(_state) {
9488 switch (_state.label) {
9489 case 0:
9490 _this.plugin = 0;
9491 i2 = 0;
9492 _state.label = 1;
9493 case 1:
9494 if (!(i2 < _this.plugins.length)) return [3, 6];
9495 plugin22 = _this.plugins[i2];
9496 promise = _this.runOnRoot(plugin22);
9497 if (!isPromise$1(promise)) return [3, 5];
9498 _state.label = 2;
9499 case 2:
9500 _state.trys.push([
9501 2,
9502 4,
9503 ,
9504 5
9505 ]);
9506 return [4, promise];
9507 case 3:
9508 _state.sent();
9509 return [3, 5];
9510 case 4:
9511 error = _state.sent();
9512 throw _this.handleError(error);
9513 case 5:
9514 i2++;
9515 return [3, 1];
9516 case 6:
9517 _this.prepareVisitors();
9518 if (!_this.hasListener) return [3, 18];
9519 root2 = _this.result.root;
9520 _state.label = 7;
9521 case 7:
9522 if (!!root2[isClean$3]) return [3, 14];
9523 root2[isClean$3] = true;
9524 stack = [toStack$1(root2)];
9525 _state.label = 8;
9526 case 8:
9527 if (!(stack.length > 0)) return [3, 13];
9528 promise1 = _this.visitTick(stack);
9529 if (!isPromise$1(promise1)) return [3, 12];
9530 _state.label = 9;
9531 case 9:
9532 _state.trys.push([
9533 9,
9534 11,
9535 ,
9536 12
9537 ]);
9538 return [4, promise1];
9539 case 10:
9540 _state.sent();
9541 return [3, 12];
9542 case 11:
9543 e2 = _state.sent();
9544 node2 = stack[stack.length - 1].node;
9545 throw _this.handleError(e2, node2);
9546 case 12: return [3, 8];
9547 case 13: return [3, 7];
9548 case 14:
9549 if (!_this.listeners.OnceExit) return [3, 18];
9550 _loop = function() {
9551 var _step_value;
9552 var plugin22;
9553 var visitor;
9554 var roots;
9555 var e2;
9556 return _ts_generator(this, function(_state) {
9557 switch (_state.label) {
9558 case 0:
9559 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
9560 _this.result.lastPlugin = plugin22;
9561 _state.label = 1;
9562 case 1:
9563 _state.trys.push([
9564 1,
9565 6,
9566 ,
9567 7
9568 ]);
9569 if (!(root2.type === "document")) return [3, 3];
9570 roots = root2.nodes.map(function(subRoot) {
9571 return visitor(subRoot, _this.helpers);
9572 });
9573 return [4, Promise.all(roots)];
9574 case 2:
9575 _state.sent();
9576 return [3, 5];
9577 case 3: return [4, visitor(root2, _this.helpers)];
9578 case 4:
9579 _state.sent();
9580 _state.label = 5;
9581 case 5: return [3, 7];
9582 case 6:
9583 e2 = _state.sent();
9584 throw _this.handleError(e2);
9585 case 7: return [2];
9586 }
9587 });
9588 };
9589 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
9590 _state.label = 15;
9591 case 15:
9592 if (!!(_step = _iterator()).done) return [3, 18];
9593 return [5, _ts_values(_loop())];
9594 case 16:
9595 _state.sent();
9596 _state.label = 17;
9597 case 17: return [3, 15];
9598 case 18:
9599 _this.processed = true;
9600 return [2, _this.stringify()];
9601 }
9602 });
9603 })();
9604 };
9605 _proto.runOnRoot = function runOnRoot(plugin22) {
9606 var _this = this;
9607 this.result.lastPlugin = plugin22;
9608 try {
9609 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
9610 if (this.result.root.type === "document") {
9611 var roots = this.result.root.nodes.map(function(root2) {
9612 return plugin22.Once(root2, _this.helpers);
9613 });
9614 if (isPromise$1(roots[0])) return Promise.all(roots);
9615 return roots;
9616 }
9617 return plugin22.Once(this.result.root, this.helpers);
9618 } else if (typeof plugin22 === "function") return plugin22(this.result.root, this.result);
9619 } catch (error) {
9620 throw this.handleError(error);
9621 }
9622 };
9623 _proto.stringify = function stringify() {
9624 if (this.error) throw this.error;
9625 if (this.stringified) return this.result;
9626 this.stringified = true;
9627 this.sync();
9628 var opts = this.result.opts;
9629 var str = stringify$2$1;
9630 if (opts.syntax) str = opts.syntax.stringify;
9631 if (opts.stringifier) str = opts.stringifier;
9632 if (str.stringify) str = str.stringify;
9633 var data = new MapGenerator$1$1(str, this.result.root, this.result.opts).generate();
9634 this.result.css = data[0];
9635 this.result.map = data[1];
9636 return this.result;
9637 };
9638 _proto.sync = function sync() {
9639 if (this.error) throw this.error;
9640 if (this.processed) return this.result;
9641 this.processed = true;
9642 if (this.processing) throw this.getAsyncError();
9643 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
9644 var plugin22 = _step.value;
9645 if (isPromise$1(this.runOnRoot(plugin22))) throw this.getAsyncError();
9646 }
9647 this.prepareVisitors();
9648 if (this.hasListener) {
9649 var root2 = this.result.root;
9650 while (!root2[isClean$3]) {
9651 root2[isClean$3] = true;
9652 this.walkSync(root2);
9653 }
9654 if (this.listeners.OnceExit) if (root2.type === "document") for (var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;) {
9655 var subRoot = _step1.value;
9656 this.visitSync(this.listeners.OnceExit, subRoot);
9657 }
9658 else this.visitSync(this.listeners.OnceExit, root2);
9659 }
9660 return this.result;
9661 };
9662 _proto.then = function then(onFulfilled, onRejected) {
9663 if (!("from" in this.opts)) 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.");
9664 return this.async().then(onFulfilled, onRejected);
9665 };
9666 _proto.toString = function toString() {
9667 return this.css;
9668 };
9669 _proto.visitSync = function visitSync(visitors, node2) {
9670 for (var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;) {
9671 var _step_value = _step.value;
9672 var plugin22 = _step_value[0];
9673 var visitor = _step_value[1];
9674 this.result.lastPlugin = plugin22;
9675 var promise = void 0;
9676 try {
9677 promise = visitor(node2, this.helpers);
9678 } catch (e2) {
9679 throw this.handleError(e2, node2.proxyOf);
9680 }
9681 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) return true;
9682 if (isPromise$1(promise)) throw this.getAsyncError();
9683 }
9684 };
9685 _proto.visitTick = function visitTick(stack) {
9686 var visit2 = stack[stack.length - 1];
9687 var node2 = visit2.node;
9688 var visitors = visit2.visitors;
9689 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
9690 stack.pop();
9691 return;
9692 }
9693 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
9694 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex];
9695 var plugin22 = _visitors_visit2_visitorIndex[0];
9696 var visitor = _visitors_visit2_visitorIndex[1];
9697 visit2.visitorIndex += 1;
9698 if (visit2.visitorIndex === visitors.length) {
9699 visit2.visitors = [];
9700 visit2.visitorIndex = 0;
9701 }
9702 this.result.lastPlugin = plugin22;
9703 try {
9704 return visitor(node2.toProxy(), this.helpers);
9705 } catch (e2) {
9706 throw this.handleError(e2, node2);
9707 }
9708 }
9709 if (visit2.iterator !== 0) {
9710 var iterator = visit2.iterator;
9711 var child;
9712 while (child = node2.nodes[node2.indexes[iterator]]) {
9713 node2.indexes[iterator] += 1;
9714 if (!child[isClean$3]) {
9715 child[isClean$3] = true;
9716 stack.push(toStack$1(child));
9717 return;
9718 }
9719 }
9720 visit2.iterator = 0;
9721 delete node2.indexes[iterator];
9722 }
9723 var events = visit2.events;
9724 while (visit2.eventIndex < events.length) {
9725 var event = events[visit2.eventIndex];
9726 visit2.eventIndex += 1;
9727 if (event === CHILDREN$1) {
9728 if (node2.nodes && node2.nodes.length) {
9729 node2[isClean$3] = true;
9730 visit2.iterator = node2.getIterator();
9731 }
9732 return;
9733 } else if (this.listeners[event]) {
9734 visit2.visitors = this.listeners[event];
9735 return;
9736 }
9737 }
9738 stack.pop();
9739 };
9740 _proto.walkSync = function walkSync(node2) {
9741 var _this = this;
9742 node2[isClean$3] = true;
9743 for (var _iterator = _create_for_of_iterator_helper_loose(getEvents$1(node2)), _step; !(_step = _iterator()).done;) {
9744 var event = _step.value;
9745 if (event === CHILDREN$1) {
9746 if (node2.nodes) node2.each(function(child) {
9747 if (!child[isClean$3]) _this.walkSync(child);
9748 });
9749 } else {
9750 var visitors = this.listeners[event];
9751 if (visitors) {
9752 if (this.visitSync(visitors, node2.toProxy())) return;
9753 }
9754 }
9755 }
9756 };
9757 _proto.warnings = function warnings() {
9758 return this.sync().warnings();
9759 };
9760 _create_class(LazyResult, [
9761 {
9762 key: "content",
9763 get: function get() {
9764 return this.stringify().content;
9765 }
9766 },
9767 {
9768 key: "css",
9769 get: function get() {
9770 return this.stringify().css;
9771 }
9772 },
9773 {
9774 key: "map",
9775 get: function get() {
9776 return this.stringify().map;
9777 }
9778 },
9779 {
9780 key: "messages",
9781 get: function get() {
9782 return this.sync().messages;
9783 }
9784 },
9785 {
9786 key: "opts",
9787 get: function get() {
9788 return this.result.opts;
9789 }
9790 },
9791 {
9792 key: "processor",
9793 get: function get() {
9794 return this.result.processor;
9795 }
9796 },
9797 {
9798 key: "root",
9799 get: function get() {
9800 return this.sync().root;
9801 }
9802 },
9803 {
9804 key: Symbol.toStringTag,
9805 get: function get() {
9806 return "LazyResult";
9807 }
9808 }
9809 ]);
9810 return LazyResult;
9811 }();
9812 LazyResult$2$1.registerPostcss = function(dependant) {
9813 postcss$2$1 = dependant;
9814 };
9815 var lazyResult$1 = LazyResult$2$1;
9816 LazyResult$2$1.default = LazyResult$2$1;
9817 Root$3$1.registerLazyResult(LazyResult$2$1);
9818 Document$2$1.registerLazyResult(LazyResult$2$1);
9819 var MapGenerator2$1 = mapGenerator$1;
9820 var stringify$1$1 = stringify_1$1;
9821 var warnOnce2$1 = warnOnce$2$1;
9822 var parse$1$1 = parse_1$1;
9823 var Result$1$1 = result$1;
9824 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
9825 function NoWorkResult(processor2, css, opts) {
9826 css = css.toString();
9827 this.stringified = false;
9828 this._processor = processor2;
9829 this._css = css;
9830 this._opts = opts;
9831 this._map = void 0;
9832 var root2;
9833 var str = stringify$1$1;
9834 this.result = new Result$1$1(this._processor, root2, this._opts);
9835 this.result.css = css;
9836 var self = this;
9837 Object.defineProperty(this.result, "root", { get: function get() {
9838 return self.root;
9839 } });
9840 var map = new MapGenerator2$1(str, root2, this._opts, css);
9841 if (map.isMap()) {
9842 var _map_generate = map.generate();
9843 var generatedCSS = _map_generate[0];
9844 var generatedMap = _map_generate[1];
9845 if (generatedCSS) this.result.css = generatedCSS;
9846 if (generatedMap) this.result.map = generatedMap;
9847 } else {
9848 map.clearAnnotation();
9849 this.result.css = map.css;
9850 }
9851 }
9852 var _proto = NoWorkResult.prototype;
9853 _proto.async = function async() {
9854 if (this.error) return Promise.reject(this.error);
9855 return Promise.resolve(this.result);
9856 };
9857 _proto.catch = function _catch(onRejected) {
9858 return this.async().catch(onRejected);
9859 };
9860 _proto.finally = function _finally(onFinally) {
9861 return this.async().then(onFinally, onFinally);
9862 };
9863 _proto.sync = function sync() {
9864 if (this.error) throw this.error;
9865 return this.result;
9866 };
9867 _proto.then = function then(onFulfilled, onRejected) {
9868 if (!("from" in this._opts)) 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.");
9869 return this.async().then(onFulfilled, onRejected);
9870 };
9871 _proto.toString = function toString() {
9872 return this._css;
9873 };
9874 _proto.warnings = function warnings() {
9875 return [];
9876 };
9877 _create_class(NoWorkResult, [
9878 {
9879 key: "content",
9880 get: function get() {
9881 return this.result.css;
9882 }
9883 },
9884 {
9885 key: "css",
9886 get: function get() {
9887 return this.result.css;
9888 }
9889 },
9890 {
9891 key: "map",
9892 get: function get() {
9893 return this.result.map;
9894 }
9895 },
9896 {
9897 key: "messages",
9898 get: function get() {
9899 return [];
9900 }
9901 },
9902 {
9903 key: "opts",
9904 get: function get() {
9905 return this.result.opts;
9906 }
9907 },
9908 {
9909 key: "processor",
9910 get: function get() {
9911 return this.result.processor;
9912 }
9913 },
9914 {
9915 key: "root",
9916 get: function get() {
9917 if (this._root) return this._root;
9918 var root2;
9919 var parser2 = parse$1$1;
9920 try {
9921 root2 = parser2(this._css, this._opts);
9922 } catch (error) {
9923 this.error = error;
9924 }
9925 if (this.error) throw this.error;
9926 else {
9927 this._root = root2;
9928 return root2;
9929 }
9930 }
9931 },
9932 {
9933 key: Symbol.toStringTag,
9934 get: function get() {
9935 return "NoWorkResult";
9936 }
9937 }
9938 ]);
9939 return NoWorkResult;
9940 }();
9941 var noWorkResult$1 = NoWorkResult$1$1;
9942 NoWorkResult$1$1.default = NoWorkResult$1$1;
9943 var NoWorkResult2$1 = noWorkResult$1;
9944 var LazyResult$1$1 = lazyResult$1;
9945 var Document$1$1 = document$1$1;
9946 var Root$2$1 = root$1;
9947 var Processor$1$1 = /*#__PURE__*/ function() {
9948 function Processor(plugins) {
9949 if (plugins === void 0) plugins = [];
9950 this.version = "8.4.38";
9951 this.plugins = this.normalize(plugins);
9952 }
9953 var _proto = Processor.prototype;
9954 _proto.normalize = function normalize(plugins) {
9955 var normalized = [];
9956 for (var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;) {
9957 var i2 = _step.value;
9958 if (i2.postcss === true) i2 = i2();
9959 else if (i2.postcss) i2 = i2.postcss;
9960 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) normalized = normalized.concat(i2.plugins);
9961 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) normalized.push(i2);
9962 else if (typeof i2 === "function") normalized.push(i2);
9963 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) 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.");
9964 else throw new Error(i2 + " is not a PostCSS plugin");
9965 }
9966 return normalized;
9967 };
9968 _proto.process = function process1(css, opts) {
9969 if (opts === void 0) opts = {};
9970 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) return new NoWorkResult2$1(this, css, opts);
9971 else return new LazyResult$1$1(this, css, opts);
9972 };
9973 _proto.use = function use(plugin22) {
9974 this.plugins = this.plugins.concat(this.normalize([plugin22]));
9975 return this;
9976 };
9977 return Processor;
9978 }();
9979 var processor$1 = Processor$1$1;
9980 Processor$1$1.default = Processor$1$1;
9981 Root$2$1.registerProcessor(Processor$1$1);
9982 Document$1$1.registerProcessor(Processor$1$1);
9983 var Declaration$1$1 = declaration$1;
9984 var PreviousMap2$1 = previousMap$1;
9985 var Comment$1$1 = comment$1;
9986 var AtRule$1$1 = atRule$1;
9987 var Input$1$1 = input$1;
9988 var Root$1$1 = root$1;
9989 var Rule$1$1 = rule$1;
9990 function fromJSON$1$1(json, inputs) {
9991 if (Array.isArray(json)) return json.map(function(n2) {
9992 return fromJSON$1$1(n2);
9993 });
9994 var ownInputs = json.inputs;
9995 var defaults = _object_without_properties_loose(json, ["inputs"]);
9996 if (ownInputs) {
9997 inputs = [];
9998 for (var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;) {
9999 var input2 = _step.value;
10000 var inputHydrated = _extends({}, input2, { __proto__: Input$1$1.prototype });
10001 if (inputHydrated.map) inputHydrated.map = _extends({}, inputHydrated.map, { __proto__: PreviousMap2$1.prototype });
10002 inputs.push(inputHydrated);
10003 }
10004 }
10005 if (defaults.nodes) defaults.nodes = json.nodes.map(function(n2) {
10006 return fromJSON$1$1(n2, inputs);
10007 });
10008 if (defaults.source) {
10009 var _defaults_source = defaults.source;
10010 var inputId = _defaults_source.inputId;
10011 defaults.source = _object_without_properties_loose(_defaults_source, ["inputId"]);
10012 if (inputId != null) defaults.source.input = inputs[inputId];
10013 }
10014 if (defaults.type === "root") return new Root$1$1(defaults);
10015 else if (defaults.type === "decl") return new Declaration$1$1(defaults);
10016 else if (defaults.type === "rule") return new Rule$1$1(defaults);
10017 else if (defaults.type === "comment") return new Comment$1$1(defaults);
10018 else if (defaults.type === "atrule") return new AtRule$1$1(defaults);
10019 else throw new Error("Unknown node type: " + json.type);
10020 }
10021 var fromJSON_1$1 = fromJSON$1$1;
10022 fromJSON$1$1.default = fromJSON$1$1;
10023 var CssSyntaxError2$1 = cssSyntaxError$1;
10024 var Declaration2$1 = declaration$1;
10025 var LazyResult2$1 = lazyResult$1;
10026 var Container2$1 = container$1;
10027 var Processor2$1 = processor$1;
10028 var stringify$5 = stringify_1$1;
10029 var fromJSON$2 = fromJSON_1$1;
10030 var Document22 = document$1$1;
10031 var Warning2$1 = warning$1;
10032 var Comment2$1 = comment$1;
10033 var AtRule2$1 = atRule$1;
10034 var Result2$1 = result$1;
10035 var Input2$1 = input$1;
10036 var parse$5 = parse_1$1;
10037 var list$3 = list_1$1;
10038 var Rule2$1 = rule$1;
10039 var Root2$1 = root$1;
10040 var Node2$1 = node$1;
10041 function postcss$3() {
10042 for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) plugins[_key] = arguments[_key];
10043 if (plugins.length === 1 && Array.isArray(plugins[0])) plugins = plugins[0];
10044 return new Processor2$1(plugins);
10045 }
10046 postcss$3.plugin = function plugin(name, initializer) {
10047 var warningPrinted = false;
10048 function creator() {
10049 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
10050 if (console && console.warn && !warningPrinted) {
10051 warningPrinted = true;
10052 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
10053 if ({}.LANG && {}.LANG.startsWith("cn")) console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
10054 }
10055 var transformer = initializer.apply(void 0, [].concat(args));
10056 transformer.postcssPlugin = name;
10057 transformer.postcssVersion = new Processor2$1().version;
10058 return transformer;
10059 }
10060 var cache;
10061 Object.defineProperty(creator, "postcss", { get: function get() {
10062 if (!cache) cache = creator();
10063 return cache;
10064 } });
10065 creator.process = function(css, processOpts, pluginOpts) {
10066 return postcss$3([creator(pluginOpts)]).process(css, processOpts);
10067 };
10068 return creator;
10069 };
10070 postcss$3.stringify = stringify$5;
10071 postcss$3.parse = parse$5;
10072 postcss$3.fromJSON = fromJSON$2;
10073 postcss$3.list = list$3;
10074 postcss$3.comment = function(defaults) {
10075 return new Comment2$1(defaults);
10076 };
10077 postcss$3.atRule = function(defaults) {
10078 return new AtRule2$1(defaults);
10079 };
10080 postcss$3.decl = function(defaults) {
10081 return new Declaration2$1(defaults);
10082 };
10083 postcss$3.rule = function(defaults) {
10084 return new Rule2$1(defaults);
10085 };
10086 postcss$3.root = function(defaults) {
10087 return new Root2$1(defaults);
10088 };
10089 postcss$3.document = function(defaults) {
10090 return new Document22(defaults);
10091 };
10092 postcss$3.CssSyntaxError = CssSyntaxError2$1;
10093 postcss$3.Declaration = Declaration2$1;
10094 postcss$3.Container = Container2$1;
10095 postcss$3.Processor = Processor2$1;
10096 postcss$3.Document = Document22;
10097 postcss$3.Comment = Comment2$1;
10098 postcss$3.Warning = Warning2$1;
10099 postcss$3.AtRule = AtRule2$1;
10100 postcss$3.Result = Result2$1;
10101 postcss$3.Input = Input2$1;
10102 postcss$3.Rule = Rule2$1;
10103 postcss$3.Root = Root2$1;
10104 postcss$3.Node = Node2$1;
10105 LazyResult2$1.registerPostcss(postcss$3);
10106 var postcss_1$1 = postcss$3;
10107 postcss$3.default = postcss$3;
10108 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
10109 postcss$1$1.stringify;
10110 postcss$1$1.fromJSON;
10111 postcss$1$1.plugin;
10112 postcss$1$1.parse;
10113 postcss$1$1.list;
10114 postcss$1$1.document;
10115 postcss$1$1.comment;
10116 postcss$1$1.atRule;
10117 postcss$1$1.rule;
10118 postcss$1$1.decl;
10119 postcss$1$1.root;
10120 postcss$1$1.CssSyntaxError;
10121 postcss$1$1.Declaration;
10122 postcss$1$1.Container;
10123 postcss$1$1.Processor;
10124 postcss$1$1.Document;
10125 postcss$1$1.Comment;
10126 postcss$1$1.Warning;
10127 postcss$1$1.AtRule;
10128 postcss$1$1.Result;
10129 postcss$1$1.Input;
10130 postcss$1$1.Rule;
10131 postcss$1$1.Root;
10132 postcss$1$1.Node;
10133 var __defProp2 = Object.defineProperty;
10134 var __defNormalProp2 = function(obj, key, value) {
10135 return key in obj ? __defProp2(obj, key, {
10136 enumerable: true,
10137 configurable: true,
10138 writable: true,
10139 value
10140 }) : obj[key] = value;
10141 };
10142 var __publicField2 = function(obj, key, value) {
10143 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
10144 };
10145 function getDefaultExportFromCjs(x2) {
10146 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
10147 }
10148 function getAugmentedNamespace(n2) {
10149 if (n2.__esModule) return n2;
10150 var f2 = n2.default;
10151 if (typeof f2 == "function") {
10152 var a2 = function a22() {
10153 if (_instanceof(this, a22)) return Reflect.construct(f2, arguments, this.constructor);
10154 return f2.apply(this, arguments);
10155 };
10156 a2.prototype = f2.prototype;
10157 } else a2 = {};
10158 Object.defineProperty(a2, "__esModule", { value: true });
10159 Object.keys(n2).forEach(function(k) {
10160 var d = Object.getOwnPropertyDescriptor(n2, k);
10161 Object.defineProperty(a2, k, d.get ? d : {
10162 enumerable: true,
10163 get: function get() {
10164 return n2[k];
10165 }
10166 });
10167 });
10168 return a2;
10169 }
10170 var picocolors_browser = { exports: {} };
10171 var x = String;
10172 var create = function create() {
10173 return {
10174 isColorSupported: false,
10175 reset: x,
10176 bold: x,
10177 dim: x,
10178 italic: x,
10179 underline: x,
10180 inverse: x,
10181 hidden: x,
10182 strikethrough: x,
10183 black: x,
10184 red: x,
10185 green: x,
10186 yellow: x,
10187 blue: x,
10188 magenta: x,
10189 cyan: x,
10190 white: x,
10191 gray: x,
10192 bgBlack: x,
10193 bgRed: x,
10194 bgGreen: x,
10195 bgYellow: x,
10196 bgBlue: x,
10197 bgMagenta: x,
10198 bgCyan: x,
10199 bgWhite: x
10200 };
10201 };
10202 picocolors_browser.exports = create();
10203 picocolors_browser.exports.createColors = create;
10204 var picocolors_browserExports = picocolors_browser.exports;
10205 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(/* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
10206 __proto__: null,
10207 default: {}
10208 }, Symbol.toStringTag, { value: "Module" })));
10209 var pico = picocolors_browserExports;
10210 var terminalHighlight$1 = require$$2;
10211 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
10212 _inherits(CssSyntaxError2, Error1);
10213 function CssSyntaxError2(message, line, column, source, file, plugin22) {
10214 var _this = Error1.call(this, message) || this;
10215 _this.name = "CssSyntaxError";
10216 _this.reason = message;
10217 if (file) _this.file = file;
10218 if (source) _this.source = source;
10219 if (plugin22) _this.plugin = plugin22;
10220 if (typeof line !== "undefined" && typeof column !== "undefined") if (typeof line === "number") {
10221 _this.line = line;
10222 _this.column = column;
10223 } else {
10224 _this.line = line.line;
10225 _this.column = line.column;
10226 _this.endLine = column.line;
10227 _this.endColumn = column.column;
10228 }
10229 _this.setMessage();
10230 if (Error.captureStackTrace) Error.captureStackTrace(_this, CssSyntaxError2);
10231 return _this;
10232 }
10233 var _proto = CssSyntaxError2.prototype;
10234 _proto.setMessage = function setMessage() {
10235 this.message = this.plugin ? this.plugin + ": " : "";
10236 this.message += this.file ? this.file : "<css input>";
10237 if (typeof this.line !== "undefined") this.message += ":" + this.line + ":" + this.column;
10238 this.message += ": " + this.reason;
10239 };
10240 _proto.showSourceCode = function showSourceCode(color) {
10241 var _this = this;
10242 if (!this.source) return "";
10243 var css = this.source;
10244 if (color == null) color = pico.isColorSupported;
10245 if (terminalHighlight$1) {
10246 if (color) css = terminalHighlight$1(css);
10247 }
10248 var lines = css.split(/\r?\n/);
10249 var start = Math.max(this.line - 3, 0);
10250 var end = Math.min(this.line + 2, lines.length);
10251 var maxWidth = String(end).length;
10252 var mark;
10253 var aside;
10254 if (color) {
10255 var _pico_createColors = pico.createColors(true);
10256 var bold = _pico_createColors.bold;
10257 var gray = _pico_createColors.gray;
10258 var red = _pico_createColors.red;
10259 mark = function(text) {
10260 return bold(red(text));
10261 };
10262 aside = function(text) {
10263 return gray(text);
10264 };
10265 } else mark = aside = function(str) {
10266 return str;
10267 };
10268 return lines.slice(start, end).map(function(line, index2) {
10269 var number = start + 1 + index2;
10270 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
10271 if (number === _this.line) {
10272 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
10273 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
10274 }
10275 return " " + aside(gutter) + line;
10276 }).join("\n");
10277 };
10278 _proto.toString = function toString() {
10279 var code = this.showSourceCode();
10280 if (code) code = "\n\n" + code + "\n";
10281 return this.name + ": " + this.message + code;
10282 };
10283 return CssSyntaxError2;
10284 }(_wrap_native_super(Error));
10285 var cssSyntaxError = CssSyntaxError$3;
10286 CssSyntaxError$3.default = CssSyntaxError$3;
10287 var symbols = {};
10288 symbols.isClean = Symbol("isClean");
10289 symbols.my = Symbol("my");
10290 var DEFAULT_RAW = {
10291 after: "\n",
10292 beforeClose: "\n",
10293 beforeComment: "\n",
10294 beforeDecl: "\n",
10295 beforeOpen: " ",
10296 beforeRule: "\n",
10297 colon: ": ",
10298 commentLeft: " ",
10299 commentRight: " ",
10300 emptyBody: "",
10301 indent: " ",
10302 semicolon: false
10303 };
10304 function capitalize(str) {
10305 return str[0].toUpperCase() + str.slice(1);
10306 }
10307 var Stringifier$2 = /*#__PURE__*/ function() {
10308 function Stringifier2(builder) {
10309 this.builder = builder;
10310 }
10311 var _proto = Stringifier2.prototype;
10312 _proto.atrule = function atrule(node2, semicolon) {
10313 var name = "@" + node2.name;
10314 var params = node2.params ? this.rawValue(node2, "params") : "";
10315 if (typeof node2.raws.afterName !== "undefined") name += node2.raws.afterName;
10316 else if (params) name += " ";
10317 if (node2.nodes) this.block(node2, name + params);
10318 else {
10319 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
10320 this.builder(name + params + end, node2);
10321 }
10322 };
10323 _proto.beforeAfter = function beforeAfter(node2, detect) {
10324 var value;
10325 if (node2.type === "decl") value = this.raw(node2, null, "beforeDecl");
10326 else if (node2.type === "comment") value = this.raw(node2, null, "beforeComment");
10327 else if (detect === "before") value = this.raw(node2, null, "beforeRule");
10328 else value = this.raw(node2, null, "beforeClose");
10329 var buf = node2.parent;
10330 var depth = 0;
10331 while (buf && buf.type !== "root") {
10332 depth += 1;
10333 buf = buf.parent;
10334 }
10335 if (value.includes("\n")) {
10336 var indent = this.raw(node2, null, "indent");
10337 if (indent.length) for (var step = 0; step < depth; step++) value += indent;
10338 }
10339 return value;
10340 };
10341 _proto.block = function block(node2, start) {
10342 var between = this.raw(node2, "between", "beforeOpen");
10343 this.builder(start + between + "{", node2, "start");
10344 var after;
10345 if (node2.nodes && node2.nodes.length) {
10346 this.body(node2);
10347 after = this.raw(node2, "after");
10348 } else after = this.raw(node2, "after", "emptyBody");
10349 if (after) this.builder(after);
10350 this.builder("}", node2, "end");
10351 };
10352 _proto.body = function body(node2) {
10353 var last = node2.nodes.length - 1;
10354 while (last > 0) {
10355 if (node2.nodes[last].type !== "comment") break;
10356 last -= 1;
10357 }
10358 var semicolon = this.raw(node2, "semicolon");
10359 for (var i2 = 0; i2 < node2.nodes.length; i2++) {
10360 var child = node2.nodes[i2];
10361 var before = this.raw(child, "before");
10362 if (before) this.builder(before);
10363 this.stringify(child, last !== i2 || semicolon);
10364 }
10365 };
10366 _proto.comment = function comment(node2) {
10367 var left = this.raw(node2, "left", "commentLeft");
10368 var right = this.raw(node2, "right", "commentRight");
10369 this.builder("/*" + left + node2.text + right + "*/", node2);
10370 };
10371 _proto.decl = function decl(node2, semicolon) {
10372 var between = this.raw(node2, "between", "colon");
10373 var string = node2.prop + between + this.rawValue(node2, "value");
10374 if (node2.important) string += node2.raws.important || " !important";
10375 if (semicolon) string += ";";
10376 this.builder(string, node2);
10377 };
10378 _proto.document = function document1(node2) {
10379 this.body(node2);
10380 };
10381 _proto.raw = function raw(node2, own, detect) {
10382 var value;
10383 if (!detect) detect = own;
10384 if (own) {
10385 value = node2.raws[own];
10386 if (typeof value !== "undefined") return value;
10387 }
10388 var parent = node2.parent;
10389 if (detect === "before") {
10390 if (!parent || parent.type === "root" && parent.first === node2) return "";
10391 if (parent && parent.type === "document") return "";
10392 }
10393 if (!parent) return DEFAULT_RAW[detect];
10394 var root2 = node2.root();
10395 if (!root2.rawCache) root2.rawCache = {};
10396 if (typeof root2.rawCache[detect] !== "undefined") return root2.rawCache[detect];
10397 if (detect === "before" || detect === "after") return this.beforeAfter(node2, detect);
10398 else {
10399 var method = "raw" + capitalize(detect);
10400 if (this[method]) value = this[method](root2, node2);
10401 else root2.walk(function(i2) {
10402 value = i2.raws[own];
10403 if (typeof value !== "undefined") return false;
10404 });
10405 }
10406 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
10407 root2.rawCache[detect] = value;
10408 return value;
10409 };
10410 _proto.rawBeforeClose = function rawBeforeClose(root2) {
10411 var value;
10412 root2.walk(function(i2) {
10413 if (i2.nodes && i2.nodes.length > 0) {
10414 if (typeof i2.raws.after !== "undefined") {
10415 value = i2.raws.after;
10416 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10417 return false;
10418 }
10419 }
10420 });
10421 if (value) value = value.replace(/\S/g, "");
10422 return value;
10423 };
10424 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
10425 var value;
10426 root2.walkComments(function(i2) {
10427 if (typeof i2.raws.before !== "undefined") {
10428 value = i2.raws.before;
10429 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10430 return false;
10431 }
10432 });
10433 if (typeof value === "undefined") value = this.raw(node2, null, "beforeDecl");
10434 else if (value) value = value.replace(/\S/g, "");
10435 return value;
10436 };
10437 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
10438 var value;
10439 root2.walkDecls(function(i2) {
10440 if (typeof i2.raws.before !== "undefined") {
10441 value = i2.raws.before;
10442 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10443 return false;
10444 }
10445 });
10446 if (typeof value === "undefined") value = this.raw(node2, null, "beforeRule");
10447 else if (value) value = value.replace(/\S/g, "");
10448 return value;
10449 };
10450 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
10451 var value;
10452 root2.walk(function(i2) {
10453 if (i2.type !== "decl") {
10454 value = i2.raws.between;
10455 if (typeof value !== "undefined") return false;
10456 }
10457 });
10458 return value;
10459 };
10460 _proto.rawBeforeRule = function rawBeforeRule(root2) {
10461 var value;
10462 root2.walk(function(i2) {
10463 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
10464 if (typeof i2.raws.before !== "undefined") {
10465 value = i2.raws.before;
10466 if (value.includes("\n")) value = value.replace(/[^\n]+$/, "");
10467 return false;
10468 }
10469 }
10470 });
10471 if (value) value = value.replace(/\S/g, "");
10472 return value;
10473 };
10474 _proto.rawColon = function rawColon(root2) {
10475 var value;
10476 root2.walkDecls(function(i2) {
10477 if (typeof i2.raws.between !== "undefined") {
10478 value = i2.raws.between.replace(/[^\s:]/g, "");
10479 return false;
10480 }
10481 });
10482 return value;
10483 };
10484 _proto.rawEmptyBody = function rawEmptyBody(root2) {
10485 var value;
10486 root2.walk(function(i2) {
10487 if (i2.nodes && i2.nodes.length === 0) {
10488 value = i2.raws.after;
10489 if (typeof value !== "undefined") return false;
10490 }
10491 });
10492 return value;
10493 };
10494 _proto.rawIndent = function rawIndent(root2) {
10495 if (root2.raws.indent) return root2.raws.indent;
10496 var value;
10497 root2.walk(function(i2) {
10498 var p = i2.parent;
10499 if (p && p !== root2 && p.parent && p.parent === root2) {
10500 if (typeof i2.raws.before !== "undefined") {
10501 var parts = i2.raws.before.split("\n");
10502 value = parts[parts.length - 1];
10503 value = value.replace(/\S/g, "");
10504 return false;
10505 }
10506 }
10507 });
10508 return value;
10509 };
10510 _proto.rawSemicolon = function rawSemicolon(root2) {
10511 var value;
10512 root2.walk(function(i2) {
10513 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
10514 value = i2.raws.semicolon;
10515 if (typeof value !== "undefined") return false;
10516 }
10517 });
10518 return value;
10519 };
10520 _proto.rawValue = function rawValue(node2, prop) {
10521 var value = node2[prop];
10522 var raw = node2.raws[prop];
10523 if (raw && raw.value === value) return raw.raw;
10524 return value;
10525 };
10526 _proto.root = function root(node2) {
10527 this.body(node2);
10528 if (node2.raws.after) this.builder(node2.raws.after);
10529 };
10530 _proto.rule = function rule(node2) {
10531 this.block(node2, this.rawValue(node2, "selector"));
10532 if (node2.raws.ownSemicolon) this.builder(node2.raws.ownSemicolon, node2, "end");
10533 };
10534 _proto.stringify = function stringify(node2, semicolon) {
10535 if (!this[node2.type]) throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
10536 this[node2.type](node2, semicolon);
10537 };
10538 return Stringifier2;
10539 }();
10540 var stringifier = Stringifier$2;
10541 Stringifier$2.default = Stringifier$2;
10542 var Stringifier$1 = stringifier;
10543 function stringify$4(node2, builder) {
10544 new Stringifier$1(builder).stringify(node2);
10545 }
10546 var stringify_1 = stringify$4;
10547 stringify$4.default = stringify$4;
10548 var isClean$2 = symbols.isClean;
10549 var my$2 = symbols.my;
10550 var CssSyntaxError$2 = cssSyntaxError;
10551 var Stringifier22 = stringifier;
10552 var stringify$3 = stringify_1;
10553 function cloneNode(obj, parent) {
10554 var cloned = new obj.constructor();
10555 for (var i2 in obj) {
10556 if (!Object.prototype.hasOwnProperty.call(obj, i2)) continue;
10557 if (i2 === "proxyCache") continue;
10558 var value = obj[i2];
10559 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
10560 if (i2 === "parent" && type === "object") {
10561 if (parent) cloned[i2] = parent;
10562 } else if (i2 === "source") cloned[i2] = value;
10563 else if (Array.isArray(value)) cloned[i2] = value.map(function(j) {
10564 return cloneNode(j, cloned);
10565 });
10566 else {
10567 if (type === "object" && value !== null) value = cloneNode(value);
10568 cloned[i2] = value;
10569 }
10570 }
10571 return cloned;
10572 }
10573 var Node$4 = /*#__PURE__*/ function() {
10574 function Node3(defaults) {
10575 if (defaults === void 0) defaults = {};
10576 this.raws = {};
10577 this[isClean$2] = false;
10578 this[my$2] = true;
10579 for (var name in defaults) if (name === "nodes") {
10580 this.nodes = [];
10581 for (var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;) {
10582 var node2 = _step.value;
10583 if (typeof node2.clone === "function") this.append(node2.clone());
10584 else this.append(node2);
10585 }
10586 } else this[name] = defaults[name];
10587 }
10588 var _proto = Node3.prototype;
10589 _proto.addToError = function addToError(error) {
10590 error.postcssNode = this;
10591 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
10592 var s2 = this.source;
10593 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
10594 }
10595 return error;
10596 };
10597 _proto.after = function after(add) {
10598 this.parent.insertAfter(this, add);
10599 return this;
10600 };
10601 _proto.assign = function assign(overrides) {
10602 if (overrides === void 0) overrides = {};
10603 for (var name in overrides) this[name] = overrides[name];
10604 return this;
10605 };
10606 _proto.before = function before(add) {
10607 this.parent.insertBefore(this, add);
10608 return this;
10609 };
10610 _proto.cleanRaws = function cleanRaws(keepBetween) {
10611 delete this.raws.before;
10612 delete this.raws.after;
10613 if (!keepBetween) delete this.raws.between;
10614 };
10615 _proto.clone = function clone(overrides) {
10616 if (overrides === void 0) overrides = {};
10617 var cloned = cloneNode(this);
10618 for (var name in overrides) cloned[name] = overrides[name];
10619 return cloned;
10620 };
10621 _proto.cloneAfter = function cloneAfter(overrides) {
10622 if (overrides === void 0) overrides = {};
10623 var cloned = this.clone(overrides);
10624 this.parent.insertAfter(this, cloned);
10625 return cloned;
10626 };
10627 _proto.cloneBefore = function cloneBefore(overrides) {
10628 if (overrides === void 0) overrides = {};
10629 var cloned = this.clone(overrides);
10630 this.parent.insertBefore(this, cloned);
10631 return cloned;
10632 };
10633 _proto.error = function error(message, opts) {
10634 if (opts === void 0) opts = {};
10635 if (this.source) {
10636 var _this_rangeBy = this.rangeBy(opts);
10637 var end = _this_rangeBy.end;
10638 var start = _this_rangeBy.start;
10639 return this.source.input.error(message, {
10640 column: start.column,
10641 line: start.line
10642 }, {
10643 column: end.column,
10644 line: end.line
10645 }, opts);
10646 }
10647 return new CssSyntaxError$2(message);
10648 };
10649 _proto.getProxyProcessor = function getProxyProcessor() {
10650 return {
10651 get: function get(node2, prop) {
10652 if (prop === "proxyOf") return node2;
10653 else if (prop === "root") return function() {
10654 return node2.root().toProxy();
10655 };
10656 else return node2[prop];
10657 },
10658 set: function set(node2, prop, value) {
10659 if (node2[prop] === value) return true;
10660 node2[prop] = value;
10661 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || prop === "text") node2.markDirty();
10662 return true;
10663 }
10664 };
10665 };
10666 _proto.markDirty = function markDirty() {
10667 if (this[isClean$2]) {
10668 this[isClean$2] = false;
10669 var next = this;
10670 while (next = next.parent) next[isClean$2] = false;
10671 }
10672 };
10673 _proto.next = function next() {
10674 if (!this.parent) return void 0;
10675 var index2 = this.parent.index(this);
10676 return this.parent.nodes[index2 + 1];
10677 };
10678 _proto.positionBy = function positionBy(opts, stringRepresentation) {
10679 var pos = this.source.start;
10680 if (opts.index) pos = this.positionInside(opts.index, stringRepresentation);
10681 else if (opts.word) {
10682 stringRepresentation = this.toString();
10683 var index2 = stringRepresentation.indexOf(opts.word);
10684 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
10685 }
10686 return pos;
10687 };
10688 _proto.positionInside = function positionInside(index2, stringRepresentation) {
10689 var string = stringRepresentation || this.toString();
10690 var column = this.source.start.column;
10691 var line = this.source.start.line;
10692 for (var i2 = 0; i2 < index2; i2++) if (string[i2] === "\n") {
10693 column = 1;
10694 line += 1;
10695 } else column += 1;
10696 return {
10697 column,
10698 line
10699 };
10700 };
10701 _proto.prev = function prev() {
10702 if (!this.parent) return void 0;
10703 var index2 = this.parent.index(this);
10704 return this.parent.nodes[index2 - 1];
10705 };
10706 _proto.rangeBy = function rangeBy(opts) {
10707 var start = {
10708 column: this.source.start.column,
10709 line: this.source.start.line
10710 };
10711 var end = this.source.end ? {
10712 column: this.source.end.column + 1,
10713 line: this.source.end.line
10714 } : {
10715 column: start.column + 1,
10716 line: start.line
10717 };
10718 if (opts.word) {
10719 var stringRepresentation = this.toString();
10720 var index2 = stringRepresentation.indexOf(opts.word);
10721 if (index2 !== -1) {
10722 start = this.positionInside(index2, stringRepresentation);
10723 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
10724 }
10725 } else {
10726 if (opts.start) start = {
10727 column: opts.start.column,
10728 line: opts.start.line
10729 };
10730 else if (opts.index) start = this.positionInside(opts.index);
10731 if (opts.end) end = {
10732 column: opts.end.column,
10733 line: opts.end.line
10734 };
10735 else if (typeof opts.endIndex === "number") end = this.positionInside(opts.endIndex);
10736 else if (opts.index) end = this.positionInside(opts.index + 1);
10737 }
10738 if (end.line < start.line || end.line === start.line && end.column <= start.column) end = {
10739 column: start.column + 1,
10740 line: start.line
10741 };
10742 return {
10743 end,
10744 start
10745 };
10746 };
10747 _proto.raw = function raw(prop, defaultType) {
10748 return new Stringifier22().raw(this, prop, defaultType);
10749 };
10750 _proto.remove = function remove() {
10751 if (this.parent) this.parent.removeChild(this);
10752 this.parent = void 0;
10753 return this;
10754 };
10755 _proto.replaceWith = function replaceWith() {
10756 for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) nodes[_key] = arguments[_key];
10757 if (this.parent) {
10758 var bookmark = this;
10759 var foundSelf = false;
10760 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
10761 var node2 = _step.value;
10762 if (node2 === this) foundSelf = true;
10763 else if (foundSelf) {
10764 this.parent.insertAfter(bookmark, node2);
10765 bookmark = node2;
10766 } else this.parent.insertBefore(bookmark, node2);
10767 }
10768 if (!foundSelf) this.remove();
10769 }
10770 return this;
10771 };
10772 _proto.root = function root() {
10773 var result2 = this;
10774 while (result2.parent && result2.parent.type !== "document") result2 = result2.parent;
10775 return result2;
10776 };
10777 _proto.toJSON = function toJSON(_, inputs) {
10778 var fixed = {};
10779 var emitInputs = inputs == null;
10780 inputs = inputs || /* @__PURE__ */ new Map();
10781 var inputsNextIndex = 0;
10782 for (var name in this) {
10783 if (!Object.prototype.hasOwnProperty.call(this, name)) continue;
10784 if (name === "parent" || name === "proxyCache") continue;
10785 var value = this[name];
10786 if (Array.isArray(value)) fixed[name] = value.map(function(i2) {
10787 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) return i2.toJSON(null, inputs);
10788 else return i2;
10789 });
10790 else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) fixed[name] = value.toJSON(null, inputs);
10791 else if (name === "source") {
10792 var inputId = inputs.get(value.input);
10793 if (inputId == null) {
10794 inputId = inputsNextIndex;
10795 inputs.set(value.input, inputsNextIndex);
10796 inputsNextIndex++;
10797 }
10798 fixed[name] = {
10799 end: value.end,
10800 inputId,
10801 start: value.start
10802 };
10803 } else fixed[name] = value;
10804 }
10805 if (emitInputs) fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
10806 return input2.toJSON();
10807 });
10808 return fixed;
10809 };
10810 _proto.toProxy = function toProxy() {
10811 if (!this.proxyCache) this.proxyCache = new Proxy(this, this.getProxyProcessor());
10812 return this.proxyCache;
10813 };
10814 _proto.toString = function toString(stringifier2) {
10815 if (stringifier2 === void 0) stringifier2 = stringify$3;
10816 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
10817 var result2 = "";
10818 stringifier2(this, function(i2) {
10819 result2 += i2;
10820 });
10821 return result2;
10822 };
10823 _proto.warn = function warn(result2, text, opts) {
10824 var data = { node: this };
10825 for (var i2 in opts) data[i2] = opts[i2];
10826 return result2.warn(text, data);
10827 };
10828 _create_class(Node3, [{
10829 key: "proxyOf",
10830 get: function get() {
10831 return this;
10832 }
10833 }]);
10834 return Node3;
10835 }();
10836 var node = Node$4;
10837 Node$4.default = Node$4;
10838 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
10839 _inherits(Declaration2, Node$3);
10840 function Declaration2(defaults) {
10841 var _this;
10842 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") defaults = _extends({}, defaults, { value: String(defaults.value) });
10843 _this = Node$3.call(this, defaults) || this;
10844 _this.type = "decl";
10845 return _this;
10846 }
10847 _create_class(Declaration2, [{
10848 key: "variable",
10849 get: function get() {
10850 return this.prop.startsWith("--") || this.prop[0] === "$";
10851 }
10852 }]);
10853 return Declaration2;
10854 }(node);
10855 var declaration = Declaration$4;
10856 Declaration$4.default = Declaration$4;
10857 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
10858 var nanoid$1 = function(size) {
10859 if (size === void 0) size = 21;
10860 var id = "";
10861 var i2 = size;
10862 while (i2--) id += urlAlphabet[Math.random() * 64 | 0];
10863 return id;
10864 };
10865 var nonSecure = { nanoid: nanoid$1 };
10866 var SourceMapConsumer$2 = require$$2.SourceMapConsumer;
10867 var SourceMapGenerator$2 = require$$2.SourceMapGenerator;
10868 var existsSync = require$$2.existsSync;
10869 var readFileSync = require$$2.readFileSync;
10870 var dirname$1 = require$$2.dirname;
10871 var join = require$$2.join;
10872 function fromBase64(str) {
10873 if (Buffer) return Buffer.from(str, "base64").toString();
10874 else return window.atob(str);
10875 }
10876 var PreviousMap$2 = /*#__PURE__*/ function() {
10877 function PreviousMap2(css, opts) {
10878 if (opts.map === false) return;
10879 this.loadAnnotation(css);
10880 this.inline = this.startWith(this.annotation, "data:");
10881 var prev = opts.map ? opts.map.prev : void 0;
10882 var text = this.loadMap(opts.from, prev);
10883 if (!this.mapFile && opts.from) this.mapFile = opts.from;
10884 if (this.mapFile) this.root = dirname$1(this.mapFile);
10885 if (text) this.text = text;
10886 }
10887 var _proto = PreviousMap2.prototype;
10888 _proto.consumer = function consumer() {
10889 if (!this.consumerCache) this.consumerCache = new SourceMapConsumer$2(this.text);
10890 return this.consumerCache;
10891 };
10892 _proto.decodeInline = function decodeInline(text) {
10893 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
10894 var baseUri = /^data:application\/json;base64,/;
10895 if (/^data:application\/json;charset=utf-?8,/.test(text) || /^data:application\/json,/.test(text)) return decodeURIComponent(text.substr(RegExp.lastMatch.length));
10896 if (baseCharsetUri.test(text) || baseUri.test(text)) return fromBase64(text.substr(RegExp.lastMatch.length));
10897 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
10898 throw new Error("Unsupported source map encoding " + encoding);
10899 };
10900 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
10901 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
10902 };
10903 _proto.isMap = function isMap(map) {
10904 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
10905 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
10906 };
10907 _proto.loadAnnotation = function loadAnnotation(css) {
10908 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
10909 if (!comments) return;
10910 var start = css.lastIndexOf(comments.pop());
10911 var end = css.indexOf("*/", start);
10912 if (start > -1 && end > -1) this.annotation = this.getAnnotationURL(css.substring(start, end));
10913 };
10914 _proto.loadFile = function loadFile(path) {
10915 this.root = dirname$1(path);
10916 if (existsSync(path)) {
10917 this.mapFile = path;
10918 return readFileSync(path, "utf-8").toString().trim();
10919 }
10920 };
10921 _proto.loadMap = function loadMap(file, prev) {
10922 if (prev === false) return false;
10923 if (prev) if (typeof prev === "string") return prev;
10924 else if (typeof prev === "function") {
10925 var prevPath = prev(file);
10926 if (prevPath) {
10927 var map = this.loadFile(prevPath);
10928 if (!map) throw new Error("Unable to load previous source map: " + prevPath.toString());
10929 return map;
10930 }
10931 } else if (_instanceof(prev, SourceMapConsumer$2)) return SourceMapGenerator$2.fromSourceMap(prev).toString();
10932 else if (_instanceof(prev, SourceMapGenerator$2)) return prev.toString();
10933 else if (this.isMap(prev)) return JSON.stringify(prev);
10934 else throw new Error("Unsupported previous source map format: " + prev.toString());
10935 else if (this.inline) return this.decodeInline(this.annotation);
10936 else if (this.annotation) {
10937 var map1 = this.annotation;
10938 if (file) map1 = join(dirname$1(file), map1);
10939 return this.loadFile(map1);
10940 }
10941 };
10942 _proto.startWith = function startWith(string, start) {
10943 if (!string) return false;
10944 return string.substr(0, start.length) === start;
10945 };
10946 _proto.withContent = function withContent() {
10947 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
10948 };
10949 return PreviousMap2;
10950 }();
10951 var previousMap = PreviousMap$2;
10952 PreviousMap$2.default = PreviousMap$2;
10953 var SourceMapConsumer$1 = require$$2.SourceMapConsumer;
10954 var SourceMapGenerator$1 = require$$2.SourceMapGenerator;
10955 var fileURLToPath = require$$2.fileURLToPath;
10956 var pathToFileURL$1 = require$$2.pathToFileURL;
10957 var isAbsolute = require$$2.isAbsolute;
10958 var resolve$1 = require$$2.resolve;
10959 var nanoid = nonSecure.nanoid;
10960 var terminalHighlight = require$$2;
10961 var CssSyntaxError$1 = cssSyntaxError;
10962 var PreviousMap$1 = previousMap;
10963 var fromOffsetCache = Symbol("fromOffsetCache");
10964 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
10965 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
10966 var Input$4 = /*#__PURE__*/ function() {
10967 function Input2(css, opts) {
10968 if (opts === void 0) opts = {};
10969 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) throw new Error("PostCSS received " + css + " instead of CSS string");
10970 this.css = css.toString();
10971 if (this.css[0] === "" || this.css[0] === "￾") {
10972 this.hasBOM = true;
10973 this.css = this.css.slice(1);
10974 } else this.hasBOM = false;
10975 if (opts.from) if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) this.file = opts.from;
10976 else this.file = resolve$1(opts.from);
10977 if (pathAvailable$1 && sourceMapAvailable$1) {
10978 var map = new PreviousMap$1(this.css, opts);
10979 if (map.text) {
10980 this.map = map;
10981 var file = map.consumer().file;
10982 if (!this.file && file) this.file = this.mapResolve(file);
10983 }
10984 }
10985 if (!this.file) this.id = "<input css " + nanoid(6) + ">";
10986 if (this.map) this.map.file = this.from;
10987 }
10988 var _proto = Input2.prototype;
10989 _proto.error = function error(message, line, column, opts) {
10990 if (opts === void 0) opts = {};
10991 var result2;
10992 var endLine;
10993 var endColumn;
10994 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
10995 var start = line;
10996 var end = column;
10997 if (typeof start.offset === "number") {
10998 var pos = this.fromOffset(start.offset);
10999 line = pos.line;
11000 column = pos.col;
11001 } else {
11002 line = start.line;
11003 column = start.column;
11004 }
11005 if (typeof end.offset === "number") {
11006 var pos1 = this.fromOffset(end.offset);
11007 endLine = pos1.line;
11008 endColumn = pos1.col;
11009 } else {
11010 endLine = end.line;
11011 endColumn = end.column;
11012 }
11013 } else if (!column) {
11014 var pos2 = this.fromOffset(line);
11015 line = pos2.line;
11016 column = pos2.col;
11017 }
11018 var origin = this.origin(line, column, endLine, endColumn);
11019 if (origin) result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
11020 column: origin.column,
11021 line: origin.line
11022 }, origin.endLine === void 0 ? origin.column : {
11023 column: origin.endColumn,
11024 line: origin.endLine
11025 }, origin.source, origin.file, opts.plugin);
11026 else result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
11027 column,
11028 line
11029 }, endLine === void 0 ? column : {
11030 column: endColumn,
11031 line: endLine
11032 }, this.css, this.file, opts.plugin);
11033 result2.input = {
11034 column,
11035 endColumn,
11036 endLine,
11037 line,
11038 source: this.css
11039 };
11040 if (this.file) {
11041 if (pathToFileURL$1) result2.input.url = pathToFileURL$1(this.file).toString();
11042 result2.input.file = this.file;
11043 }
11044 return result2;
11045 };
11046 _proto.fromOffset = function fromOffset(offset) {
11047 var lastLine;
11048 var lineToIndex;
11049 if (!this[fromOffsetCache]) {
11050 var lines = this.css.split("\n");
11051 lineToIndex = new Array(lines.length);
11052 var prevIndex = 0;
11053 for (var i2 = 0, l2 = lines.length; i2 < l2; i2++) {
11054 lineToIndex[i2] = prevIndex;
11055 prevIndex += lines[i2].length + 1;
11056 }
11057 this[fromOffsetCache] = lineToIndex;
11058 } else lineToIndex = this[fromOffsetCache];
11059 lastLine = lineToIndex[lineToIndex.length - 1];
11060 var min = 0;
11061 if (offset >= lastLine) min = lineToIndex.length - 1;
11062 else {
11063 var max = lineToIndex.length - 2;
11064 var mid;
11065 while (min < max) {
11066 mid = min + (max - min >> 1);
11067 if (offset < lineToIndex[mid]) max = mid - 1;
11068 else if (offset >= lineToIndex[mid + 1]) min = mid + 1;
11069 else {
11070 min = mid;
11071 break;
11072 }
11073 }
11074 }
11075 return {
11076 col: offset - lineToIndex[min] + 1,
11077 line: min + 1
11078 };
11079 };
11080 _proto.mapResolve = function mapResolve(file) {
11081 if (/^\w+:\/\//.test(file)) return file;
11082 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
11083 };
11084 _proto.origin = function origin(line, column, endLine, endColumn) {
11085 if (!this.map) return false;
11086 var consumer = this.map.consumer();
11087 var from = consumer.originalPositionFor({
11088 column,
11089 line
11090 });
11091 if (!from.source) return false;
11092 var to;
11093 if (typeof endLine === "number") to = consumer.originalPositionFor({
11094 column: endColumn,
11095 line: endLine
11096 });
11097 var fromUrl;
11098 if (isAbsolute(from.source)) fromUrl = pathToFileURL$1(from.source);
11099 else fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
11100 var result2 = {
11101 column: from.column,
11102 endColumn: to && to.column,
11103 endLine: to && to.line,
11104 line: from.line,
11105 url: fromUrl.toString()
11106 };
11107 if (fromUrl.protocol === "file:") if (fileURLToPath) result2.file = fileURLToPath(fromUrl);
11108 else throw new Error("file: protocol is not available in this PostCSS build");
11109 var source = consumer.sourceContentFor(from.source);
11110 if (source) result2.source = source;
11111 return result2;
11112 };
11113 _proto.toJSON = function toJSON() {
11114 var json = {};
11115 for (var _i = 0, _iter = [
11116 "hasBOM",
11117 "css",
11118 "file",
11119 "id"
11120 ]; _i < _iter.length; _i++) {
11121 var name = _iter[_i];
11122 if (this[name] != null) json[name] = this[name];
11123 }
11124 if (this.map) {
11125 json.map = _extends({}, this.map);
11126 if (json.map.consumerCache) json.map.consumerCache = void 0;
11127 }
11128 return json;
11129 };
11130 _create_class(Input2, [{
11131 key: "from",
11132 get: function get() {
11133 return this.file || this.id;
11134 }
11135 }]);
11136 return Input2;
11137 }();
11138 var input = Input$4;
11139 Input$4.default = Input$4;
11140 if (terminalHighlight && terminalHighlight.registerInput) terminalHighlight.registerInput(Input$4);
11141 var SourceMapConsumer = require$$2.SourceMapConsumer;
11142 var SourceMapGenerator = require$$2.SourceMapGenerator;
11143 var dirname = require$$2.dirname;
11144 var relative = require$$2.relative;
11145 var resolve$3 = require$$2.resolve;
11146 var sep = require$$2.sep;
11147 var pathToFileURL = require$$2.pathToFileURL;
11148 var Input$3 = input;
11149 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
11150 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
11151 var mapGenerator = /* @__PURE__ */ function() {
11152 function MapGenerator2(stringify2, root2, opts, cssString) {
11153 this.stringify = stringify2;
11154 this.mapOpts = opts.map || {};
11155 this.root = root2;
11156 this.opts = opts;
11157 this.css = cssString;
11158 this.originalCSS = cssString;
11159 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
11160 this.memoizedFileURLs = /* @__PURE__ */ new Map();
11161 this.memoizedPaths = /* @__PURE__ */ new Map();
11162 this.memoizedURLs = /* @__PURE__ */ new Map();
11163 }
11164 var _proto = MapGenerator2.prototype;
11165 _proto.addAnnotation = function addAnnotation() {
11166 var content;
11167 if (this.isInline()) content = "data:application/json;base64," + this.toBase64(this.map.toString());
11168 else if (typeof this.mapOpts.annotation === "string") content = this.mapOpts.annotation;
11169 else if (typeof this.mapOpts.annotation === "function") content = this.mapOpts.annotation(this.opts.to, this.root);
11170 else content = this.outputFile() + ".map";
11171 var eol = "\n";
11172 if (this.css.includes("\r\n")) eol = "\r\n";
11173 this.css += eol + "/*# sourceMappingURL=" + content + " */";
11174 };
11175 _proto.applyPrevMaps = function applyPrevMaps() {
11176 for (var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;) {
11177 var prev = _step.value;
11178 var from = this.toUrl(this.path(prev.file));
11179 var root2 = prev.root || dirname(prev.file);
11180 var map = void 0;
11181 if (this.mapOpts.sourcesContent === false) {
11182 map = new SourceMapConsumer(prev.text);
11183 if (map.sourcesContent) map.sourcesContent = null;
11184 } else map = prev.consumer();
11185 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
11186 }
11187 };
11188 _proto.clearAnnotation = function clearAnnotation() {
11189 if (this.mapOpts.annotation === false) return;
11190 if (this.root) {
11191 var node2;
11192 for (var i2 = this.root.nodes.length - 1; i2 >= 0; i2--) {
11193 node2 = this.root.nodes[i2];
11194 if (node2.type !== "comment") continue;
11195 if (node2.text.indexOf("# sourceMappingURL=") === 0) this.root.removeChild(i2);
11196 }
11197 } else if (this.css) this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
11198 };
11199 _proto.generate = function generate() {
11200 this.clearAnnotation();
11201 if (pathAvailable && sourceMapAvailable && this.isMap()) return this.generateMap();
11202 else {
11203 var result2 = "";
11204 this.stringify(this.root, function(i2) {
11205 result2 += i2;
11206 });
11207 return [result2];
11208 }
11209 };
11210 _proto.generateMap = function generateMap() {
11211 if (this.root) this.generateString();
11212 else if (this.previous().length === 1) {
11213 var prev = this.previous()[0].consumer();
11214 prev.file = this.outputFile();
11215 this.map = SourceMapGenerator.fromSourceMap(prev, { ignoreInvalidMapping: true });
11216 } else {
11217 this.map = new SourceMapGenerator({
11218 file: this.outputFile(),
11219 ignoreInvalidMapping: true
11220 });
11221 this.map.addMapping({
11222 generated: {
11223 column: 0,
11224 line: 1
11225 },
11226 original: {
11227 column: 0,
11228 line: 1
11229 },
11230 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
11231 });
11232 }
11233 if (this.isSourcesContent()) this.setSourcesContent();
11234 if (this.root && this.previous().length > 0) this.applyPrevMaps();
11235 if (this.isAnnotation()) this.addAnnotation();
11236 if (this.isInline()) return [this.css];
11237 else return [this.css, this.map];
11238 };
11239 _proto.generateString = function generateString() {
11240 var _this = this;
11241 this.css = "";
11242 this.map = new SourceMapGenerator({
11243 file: this.outputFile(),
11244 ignoreInvalidMapping: true
11245 });
11246 var line = 1;
11247 var column = 1;
11248 var noSource = "<no source>";
11249 var mapping = {
11250 generated: {
11251 column: 0,
11252 line: 0
11253 },
11254 original: {
11255 column: 0,
11256 line: 0
11257 },
11258 source: ""
11259 };
11260 var lines;
11261 var last;
11262 this.stringify(this.root, function(str, node2, type) {
11263 _this.css += str;
11264 if (node2 && type !== "end") {
11265 mapping.generated.line = line;
11266 mapping.generated.column = column - 1;
11267 if (node2.source && node2.source.start) {
11268 mapping.source = _this.sourcePath(node2);
11269 mapping.original.line = node2.source.start.line;
11270 mapping.original.column = node2.source.start.column - 1;
11271 _this.map.addMapping(mapping);
11272 } else {
11273 mapping.source = noSource;
11274 mapping.original.line = 1;
11275 mapping.original.column = 0;
11276 _this.map.addMapping(mapping);
11277 }
11278 }
11279 lines = str.match(/\n/g);
11280 if (lines) {
11281 line += lines.length;
11282 last = str.lastIndexOf("\n");
11283 column = str.length - last;
11284 } else column += str.length;
11285 if (node2 && type !== "start") {
11286 var p = node2.parent || { raws: {} };
11287 if (!(node2.type === "decl" || node2.type === "atrule" && !node2.nodes) || node2 !== p.last || p.raws.semicolon) if (node2.source && node2.source.end) {
11288 mapping.source = _this.sourcePath(node2);
11289 mapping.original.line = node2.source.end.line;
11290 mapping.original.column = node2.source.end.column - 1;
11291 mapping.generated.line = line;
11292 mapping.generated.column = column - 2;
11293 _this.map.addMapping(mapping);
11294 } else {
11295 mapping.source = noSource;
11296 mapping.original.line = 1;
11297 mapping.original.column = 0;
11298 mapping.generated.line = line;
11299 mapping.generated.column = column - 1;
11300 _this.map.addMapping(mapping);
11301 }
11302 }
11303 });
11304 };
11305 _proto.isAnnotation = function isAnnotation() {
11306 if (this.isInline()) return true;
11307 if (typeof this.mapOpts.annotation !== "undefined") return this.mapOpts.annotation;
11308 if (this.previous().length) return this.previous().some(function(i2) {
11309 return i2.annotation;
11310 });
11311 return true;
11312 };
11313 _proto.isInline = function isInline() {
11314 if (typeof this.mapOpts.inline !== "undefined") return this.mapOpts.inline;
11315 var annotation = this.mapOpts.annotation;
11316 if (typeof annotation !== "undefined" && annotation !== true) return false;
11317 if (this.previous().length) return this.previous().some(function(i2) {
11318 return i2.inline;
11319 });
11320 return true;
11321 };
11322 _proto.isMap = function isMap() {
11323 if (typeof this.opts.map !== "undefined") return !!this.opts.map;
11324 return this.previous().length > 0;
11325 };
11326 _proto.isSourcesContent = function isSourcesContent() {
11327 if (typeof this.mapOpts.sourcesContent !== "undefined") return this.mapOpts.sourcesContent;
11328 if (this.previous().length) return this.previous().some(function(i2) {
11329 return i2.withContent();
11330 });
11331 return true;
11332 };
11333 _proto.outputFile = function outputFile() {
11334 if (this.opts.to) return this.path(this.opts.to);
11335 else if (this.opts.from) return this.path(this.opts.from);
11336 else return "to.css";
11337 };
11338 _proto.path = function path(file) {
11339 if (this.mapOpts.absolute) return file;
11340 if (file.charCodeAt(0) === 60) return file;
11341 if (/^\w+:\/\//.test(file)) return file;
11342 var cached = this.memoizedPaths.get(file);
11343 if (cached) return cached;
11344 var from = this.opts.to ? dirname(this.opts.to) : ".";
11345 if (typeof this.mapOpts.annotation === "string") from = dirname(resolve$3(from, this.mapOpts.annotation));
11346 var path = relative(from, file);
11347 this.memoizedPaths.set(file, path);
11348 return path;
11349 };
11350 _proto.previous = function previous() {
11351 var _this = this;
11352 if (!this.previousMaps) {
11353 this.previousMaps = [];
11354 if (this.root) this.root.walk(function(node2) {
11355 if (node2.source && node2.source.input.map) {
11356 var map = node2.source.input.map;
11357 if (!_this.previousMaps.includes(map)) _this.previousMaps.push(map);
11358 }
11359 });
11360 else {
11361 var input2 = new Input$3(this.originalCSS, this.opts);
11362 if (input2.map) this.previousMaps.push(input2.map);
11363 }
11364 }
11365 return this.previousMaps;
11366 };
11367 _proto.setSourcesContent = function setSourcesContent() {
11368 var _this = this;
11369 var already = {};
11370 if (this.root) this.root.walk(function(node2) {
11371 if (node2.source) {
11372 var from = node2.source.input.from;
11373 if (from && !already[from]) {
11374 already[from] = true;
11375 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
11376 _this.map.setSourceContent(fromUrl, node2.source.input.css);
11377 }
11378 }
11379 });
11380 else if (this.css) {
11381 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
11382 this.map.setSourceContent(from, this.css);
11383 }
11384 };
11385 _proto.sourcePath = function sourcePath(node2) {
11386 if (this.mapOpts.from) return this.toUrl(this.mapOpts.from);
11387 else if (this.usesFileUrls) return this.toFileUrl(node2.source.input.from);
11388 else return this.toUrl(this.path(node2.source.input.from));
11389 };
11390 _proto.toBase64 = function toBase64(str) {
11391 if (Buffer) return Buffer.from(str).toString("base64");
11392 else return window.btoa(unescape(encodeURIComponent(str)));
11393 };
11394 _proto.toFileUrl = function toFileUrl(path) {
11395 var cached = this.memoizedFileURLs.get(path);
11396 if (cached) return cached;
11397 if (pathToFileURL) {
11398 var fileURL = pathToFileURL(path).toString();
11399 this.memoizedFileURLs.set(path, fileURL);
11400 return fileURL;
11401 } else throw new Error("`map.absolute` option is not available in this PostCSS build");
11402 };
11403 _proto.toUrl = function toUrl(path) {
11404 var cached = this.memoizedURLs.get(path);
11405 if (cached) return cached;
11406 if (sep === "\\") path = path.replace(/\\/g, "/");
11407 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
11408 this.memoizedURLs.set(path, url);
11409 return url;
11410 };
11411 return MapGenerator2;
11412 }();
11413 var Comment$4 = /*#__PURE__*/ function(Node$2) {
11414 _inherits(Comment2, Node$2);
11415 function Comment2(defaults) {
11416 var _this = Node$2.call(this, defaults) || this;
11417 _this.type = "comment";
11418 return _this;
11419 }
11420 return Comment2;
11421 }(node);
11422 var comment = Comment$4;
11423 Comment$4.default = Comment$4;
11424 var isClean$1 = symbols.isClean;
11425 var my$1 = symbols.my;
11426 var Declaration$3 = declaration;
11427 var Comment$3 = comment;
11428 var Node$1 = node;
11429 var parse$4;
11430 var Rule$4;
11431 var AtRule$4;
11432 var Root$6;
11433 function cleanSource(nodes) {
11434 return nodes.map(function(i2) {
11435 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
11436 delete i2.source;
11437 return i2;
11438 });
11439 }
11440 function markDirtyUp(node2) {
11441 node2[isClean$1] = false;
11442 if (node2.proxyOf.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
11443 var i2 = _step.value;
11444 markDirtyUp(i2);
11445 }
11446 }
11447 var Container$7 = /*#__PURE__*/ function(Node$1) {
11448 _inherits(Container2, Node$1);
11449 function Container2() {
11450 return Node$1.apply(this, arguments) || this;
11451 }
11452 var _proto = Container2.prototype;
11453 _proto.append = function append() {
11454 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
11455 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
11456 var child = _step.value;
11457 for (var _iterator1 = _create_for_of_iterator_helper_loose(this.normalize(child, this.last)), _step1; !(_step1 = _iterator1()).done;) {
11458 var node2 = _step1.value;
11459 this.proxyOf.nodes.push(node2);
11460 }
11461 }
11462 this.markDirty();
11463 return this;
11464 };
11465 _proto.cleanRaws = function cleanRaws(keepBetween) {
11466 Node$1.prototype.cleanRaws.call(this, keepBetween);
11467 if (this.nodes) for (var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;) _step.value.cleanRaws(keepBetween);
11468 };
11469 _proto.each = function each(callback) {
11470 if (!this.proxyOf.nodes) return void 0;
11471 var iterator = this.getIterator();
11472 var index2;
11473 var result2;
11474 while (this.indexes[iterator] < this.proxyOf.nodes.length) {
11475 index2 = this.indexes[iterator];
11476 result2 = callback(this.proxyOf.nodes[index2], index2);
11477 if (result2 === false) break;
11478 this.indexes[iterator] += 1;
11479 }
11480 delete this.indexes[iterator];
11481 return result2;
11482 };
11483 _proto.every = function every(condition) {
11484 return this.nodes.every(condition);
11485 };
11486 _proto.getIterator = function getIterator() {
11487 if (!this.lastEach) this.lastEach = 0;
11488 if (!this.indexes) this.indexes = {};
11489 this.lastEach += 1;
11490 var iterator = this.lastEach;
11491 this.indexes[iterator] = 0;
11492 return iterator;
11493 };
11494 _proto.getProxyProcessor = function getProxyProcessor() {
11495 return {
11496 get: function get(node2, prop) {
11497 if (prop === "proxyOf") return node2;
11498 else if (!node2[prop]) return node2[prop];
11499 else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) return function() {
11500 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
11501 var _node2;
11502 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
11503 if (typeof i2 === "function") return function(child, index2) {
11504 return i2(child.toProxy(), index2);
11505 };
11506 else return i2;
11507 })));
11508 };
11509 else if (prop === "every" || prop === "some") return function(cb) {
11510 return node2[prop](function(child) {
11511 for (var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) other[_key - 1] = arguments[_key];
11512 return cb.apply(void 0, [].concat([child.toProxy()], other));
11513 });
11514 };
11515 else if (prop === "root") return function() {
11516 return node2.root().toProxy();
11517 };
11518 else if (prop === "nodes") return node2.nodes.map(function(i2) {
11519 return i2.toProxy();
11520 });
11521 else if (prop === "first" || prop === "last") return node2[prop].toProxy();
11522 else return node2[prop];
11523 },
11524 set: function set(node2, prop, value) {
11525 if (node2[prop] === value) return true;
11526 node2[prop] = value;
11527 if (prop === "name" || prop === "params" || prop === "selector") node2.markDirty();
11528 return true;
11529 }
11530 };
11531 };
11532 _proto.index = function index(child) {
11533 if (typeof child === "number") return child;
11534 if (child.proxyOf) child = child.proxyOf;
11535 return this.proxyOf.nodes.indexOf(child);
11536 };
11537 _proto.insertAfter = function insertAfter(exist, add) {
11538 var existIndex = this.index(exist);
11539 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
11540 existIndex = this.index(exist);
11541 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11542 var node2 = _step.value;
11543 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
11544 }
11545 var index2;
11546 for (var id in this.indexes) {
11547 index2 = this.indexes[id];
11548 if (existIndex < index2) this.indexes[id] = index2 + nodes.length;
11549 }
11550 this.markDirty();
11551 return this;
11552 };
11553 _proto.insertBefore = function insertBefore(exist, add) {
11554 var existIndex = this.index(exist);
11555 var type = existIndex === 0 ? "prepend" : false;
11556 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
11557 existIndex = this.index(exist);
11558 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11559 var node2 = _step.value;
11560 this.proxyOf.nodes.splice(existIndex, 0, node2);
11561 }
11562 var index2;
11563 for (var id in this.indexes) {
11564 index2 = this.indexes[id];
11565 if (existIndex <= index2) this.indexes[id] = index2 + nodes.length;
11566 }
11567 this.markDirty();
11568 return this;
11569 };
11570 _proto.normalize = function normalize(nodes, sample) {
11571 var _this = this;
11572 if (typeof nodes === "string") nodes = cleanSource(parse$4(nodes).nodes);
11573 else if (typeof nodes === "undefined") nodes = [];
11574 else if (Array.isArray(nodes)) {
11575 nodes = nodes.slice(0);
11576 for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
11577 var i2 = _step.value;
11578 if (i2.parent) i2.parent.removeChild(i2, "ignore");
11579 }
11580 } else if (nodes.type === "root" && this.type !== "document") {
11581 nodes = nodes.nodes.slice(0);
11582 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
11583 var i21 = _step1.value;
11584 if (i21.parent) i21.parent.removeChild(i21, "ignore");
11585 }
11586 } else if (nodes.type) nodes = [nodes];
11587 else if (nodes.prop) {
11588 if (typeof nodes.value === "undefined") throw new Error("Value field is missed in node creation");
11589 else if (typeof nodes.value !== "string") nodes.value = String(nodes.value);
11590 nodes = [new Declaration$3(nodes)];
11591 } else if (nodes.selector) nodes = [new Rule$4(nodes)];
11592 else if (nodes.name) nodes = [new AtRule$4(nodes)];
11593 else if (nodes.text) nodes = [new Comment$3(nodes)];
11594 else throw new Error("Unknown node type in node creation");
11595 return nodes.map(function(i2) {
11596 if (!i2[my$1]) Container2.rebuild(i2);
11597 i2 = i2.proxyOf;
11598 if (i2.parent) i2.parent.removeChild(i2);
11599 if (i2[isClean$1]) markDirtyUp(i2);
11600 if (typeof i2.raws.before === "undefined") {
11601 if (sample && typeof sample.raws.before !== "undefined") i2.raws.before = sample.raws.before.replace(/\S/g, "");
11602 }
11603 i2.parent = _this.proxyOf;
11604 return i2;
11605 });
11606 };
11607 _proto.prepend = function prepend() {
11608 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
11609 children = children.reverse();
11610 for (var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;) {
11611 var child = _step.value;
11612 var nodes = this.normalize(child, this.first, "prepend").reverse();
11613 for (var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;) {
11614 var node2 = _step1.value;
11615 this.proxyOf.nodes.unshift(node2);
11616 }
11617 for (var id in this.indexes) this.indexes[id] = this.indexes[id] + nodes.length;
11618 }
11619 this.markDirty();
11620 return this;
11621 };
11622 _proto.push = function push(child) {
11623 child.parent = this;
11624 this.proxyOf.nodes.push(child);
11625 return this;
11626 };
11627 _proto.removeAll = function removeAll() {
11628 for (var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;) {
11629 var node2 = _step.value;
11630 node2.parent = void 0;
11631 }
11632 this.proxyOf.nodes = [];
11633 this.markDirty();
11634 return this;
11635 };
11636 _proto.removeChild = function removeChild(child) {
11637 child = this.index(child);
11638 this.proxyOf.nodes[child].parent = void 0;
11639 this.proxyOf.nodes.splice(child, 1);
11640 var index2;
11641 for (var id in this.indexes) {
11642 index2 = this.indexes[id];
11643 if (index2 >= child) this.indexes[id] = index2 - 1;
11644 }
11645 this.markDirty();
11646 return this;
11647 };
11648 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
11649 if (!callback) {
11650 callback = opts;
11651 opts = {};
11652 }
11653 this.walkDecls(function(decl) {
11654 if (opts.props && !opts.props.includes(decl.prop)) return;
11655 if (opts.fast && !decl.value.includes(opts.fast)) return;
11656 decl.value = decl.value.replace(pattern, callback);
11657 });
11658 this.markDirty();
11659 return this;
11660 };
11661 _proto.some = function some(condition) {
11662 return this.nodes.some(condition);
11663 };
11664 _proto.walk = function walk(callback) {
11665 return this.each(function(child, i2) {
11666 var result2;
11667 try {
11668 result2 = callback(child, i2);
11669 } catch (e2) {
11670 throw child.addToError(e2);
11671 }
11672 if (result2 !== false && child.walk) result2 = child.walk(callback);
11673 return result2;
11674 });
11675 };
11676 _proto.walkAtRules = function walkAtRules(name, callback) {
11677 if (!callback) {
11678 callback = name;
11679 return this.walk(function(child, i2) {
11680 if (child.type === "atrule") return callback(child, i2);
11681 });
11682 }
11683 if (_instanceof(name, RegExp)) return this.walk(function(child, i2) {
11684 if (child.type === "atrule" && name.test(child.name)) return callback(child, i2);
11685 });
11686 return this.walk(function(child, i2) {
11687 if (child.type === "atrule" && child.name === name) return callback(child, i2);
11688 });
11689 };
11690 _proto.walkComments = function walkComments(callback) {
11691 return this.walk(function(child, i2) {
11692 if (child.type === "comment") return callback(child, i2);
11693 });
11694 };
11695 _proto.walkDecls = function walkDecls(prop, callback) {
11696 if (!callback) {
11697 callback = prop;
11698 return this.walk(function(child, i2) {
11699 if (child.type === "decl") return callback(child, i2);
11700 });
11701 }
11702 if (_instanceof(prop, RegExp)) return this.walk(function(child, i2) {
11703 if (child.type === "decl" && prop.test(child.prop)) return callback(child, i2);
11704 });
11705 return this.walk(function(child, i2) {
11706 if (child.type === "decl" && child.prop === prop) return callback(child, i2);
11707 });
11708 };
11709 _proto.walkRules = function walkRules(selector, callback) {
11710 if (!callback) {
11711 callback = selector;
11712 return this.walk(function(child, i2) {
11713 if (child.type === "rule") return callback(child, i2);
11714 });
11715 }
11716 if (_instanceof(selector, RegExp)) return this.walk(function(child, i2) {
11717 if (child.type === "rule" && selector.test(child.selector)) return callback(child, i2);
11718 });
11719 return this.walk(function(child, i2) {
11720 if (child.type === "rule" && child.selector === selector) return callback(child, i2);
11721 });
11722 };
11723 _create_class(Container2, [{
11724 key: "first",
11725 get: function get() {
11726 if (!this.proxyOf.nodes) return void 0;
11727 return this.proxyOf.nodes[0];
11728 }
11729 }, {
11730 key: "last",
11731 get: function get() {
11732 if (!this.proxyOf.nodes) return void 0;
11733 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
11734 }
11735 }]);
11736 return Container2;
11737 }(Node$1);
11738 Container$7.registerParse = function(dependant) {
11739 parse$4 = dependant;
11740 };
11741 Container$7.registerRule = function(dependant) {
11742 Rule$4 = dependant;
11743 };
11744 Container$7.registerAtRule = function(dependant) {
11745 AtRule$4 = dependant;
11746 };
11747 Container$7.registerRoot = function(dependant) {
11748 Root$6 = dependant;
11749 };
11750 var container = Container$7;
11751 Container$7.default = Container$7;
11752 Container$7.rebuild = function(node2) {
11753 if (node2.type === "atrule") Object.setPrototypeOf(node2, AtRule$4.prototype);
11754 else if (node2.type === "rule") Object.setPrototypeOf(node2, Rule$4.prototype);
11755 else if (node2.type === "decl") Object.setPrototypeOf(node2, Declaration$3.prototype);
11756 else if (node2.type === "comment") Object.setPrototypeOf(node2, Comment$3.prototype);
11757 else if (node2.type === "root") Object.setPrototypeOf(node2, Root$6.prototype);
11758 node2[my$1] = true;
11759 if (node2.nodes) node2.nodes.forEach(function(child) {
11760 Container$7.rebuild(child);
11761 });
11762 };
11763 var Container$6 = container;
11764 var LazyResult$4;
11765 var Processor$3;
11766 var Document$3 = /*#__PURE__*/ function(Container$6) {
11767 _inherits(Document23, Container$6);
11768 function Document23(defaults) {
11769 var _this = Container$6.call(this, _extends({ type: "document" }, defaults)) || this;
11770 if (!_this.nodes) _this.nodes = [];
11771 return _this;
11772 }
11773 var _proto = Document23.prototype;
11774 _proto.toResult = function toResult(opts) {
11775 if (opts === void 0) opts = {};
11776 return new LazyResult$4(new Processor$3(), this, opts).stringify();
11777 };
11778 return Document23;
11779 }(Container$6);
11780 Document$3.registerLazyResult = function(dependant) {
11781 LazyResult$4 = dependant;
11782 };
11783 Document$3.registerProcessor = function(dependant) {
11784 Processor$3 = dependant;
11785 };
11786 var document$1$2 = Document$3;
11787 Document$3.default = Document$3;
11788 var printed = {};
11789 var warnOnce$2 = function warnOnce2(message) {
11790 if (printed[message]) return;
11791 printed[message] = true;
11792 if (typeof console !== "undefined" && console.warn) console.warn(message);
11793 };
11794 var Warning$2 = /*#__PURE__*/ function() {
11795 function Warning2(text, opts) {
11796 if (opts === void 0) opts = {};
11797 this.type = "warning";
11798 this.text = text;
11799 if (opts.node && opts.node.source) {
11800 var range = opts.node.rangeBy(opts);
11801 this.line = range.start.line;
11802 this.column = range.start.column;
11803 this.endLine = range.end.line;
11804 this.endColumn = range.end.column;
11805 }
11806 for (var opt in opts) this[opt] = opts[opt];
11807 }
11808 var _proto = Warning2.prototype;
11809 _proto.toString = function toString() {
11810 if (this.node) return this.node.error(this.text, {
11811 index: this.index,
11812 plugin: this.plugin,
11813 word: this.word
11814 }).message;
11815 if (this.plugin) return this.plugin + ": " + this.text;
11816 return this.text;
11817 };
11818 return Warning2;
11819 }();
11820 var warning = Warning$2;
11821 Warning$2.default = Warning$2;
11822 var Warning$1 = warning;
11823 var Result$3 = /*#__PURE__*/ function() {
11824 function Result2(processor2, root2, opts) {
11825 this.processor = processor2;
11826 this.messages = [];
11827 this.root = root2;
11828 this.opts = opts;
11829 this.css = void 0;
11830 this.map = void 0;
11831 }
11832 var _proto = Result2.prototype;
11833 _proto.toString = function toString() {
11834 return this.css;
11835 };
11836 _proto.warn = function warn(text, opts) {
11837 if (opts === void 0) opts = {};
11838 if (!opts.plugin) {
11839 if (this.lastPlugin && this.lastPlugin.postcssPlugin) opts.plugin = this.lastPlugin.postcssPlugin;
11840 }
11841 var warning2 = new Warning$1(text, opts);
11842 this.messages.push(warning2);
11843 return warning2;
11844 };
11845 _proto.warnings = function warnings() {
11846 return this.messages.filter(function(i2) {
11847 return i2.type === "warning";
11848 });
11849 };
11850 _create_class(Result2, [{
11851 key: "content",
11852 get: function get() {
11853 return this.css;
11854 }
11855 }]);
11856 return Result2;
11857 }();
11858 var result = Result$3;
11859 Result$3.default = Result$3;
11860 var SINGLE_QUOTE = "'".charCodeAt(0);
11861 var DOUBLE_QUOTE = "\"".charCodeAt(0);
11862 var BACKSLASH = "\\".charCodeAt(0);
11863 var SLASH = "/".charCodeAt(0);
11864 var NEWLINE = "\n".charCodeAt(0);
11865 var SPACE = " ".charCodeAt(0);
11866 var FEED = "\f".charCodeAt(0);
11867 var TAB = " ".charCodeAt(0);
11868 var CR = "\r".charCodeAt(0);
11869 var OPEN_SQUARE = "[".charCodeAt(0);
11870 var CLOSE_SQUARE = "]".charCodeAt(0);
11871 var OPEN_PARENTHESES = "(".charCodeAt(0);
11872 var CLOSE_PARENTHESES = ")".charCodeAt(0);
11873 var OPEN_CURLY = "{".charCodeAt(0);
11874 var CLOSE_CURLY = "}".charCodeAt(0);
11875 var SEMICOLON = ";".charCodeAt(0);
11876 var ASTERISK = "*".charCodeAt(0);
11877 var COLON = ":".charCodeAt(0);
11878 var AT = "@".charCodeAt(0);
11879 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
11880 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
11881 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
11882 var RE_HEX_ESCAPE = /[\da-f]/i;
11883 var tokenize = function tokenizer2(input2, options) {
11884 if (options === void 0) options = {};
11885 var css = input2.css.valueOf();
11886 var ignore = options.ignoreErrors;
11887 var code;
11888 var next;
11889 var quote;
11890 var content;
11891 var escape;
11892 var escaped;
11893 var escapePos;
11894 var prev;
11895 var n2;
11896 var currentToken;
11897 var length = css.length;
11898 var pos = 0;
11899 var buffer = [];
11900 var returned = [];
11901 function position() {
11902 return pos;
11903 }
11904 function unclosed(what) {
11905 throw input2.error("Unclosed " + what, pos);
11906 }
11907 function endOfFile() {
11908 return returned.length === 0 && pos >= length;
11909 }
11910 function nextToken(opts) {
11911 if (returned.length) return returned.pop();
11912 if (pos >= length) return;
11913 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
11914 code = css.charCodeAt(pos);
11915 switch (code) {
11916 case NEWLINE:
11917 case SPACE:
11918 case TAB:
11919 case CR:
11920 case FEED:
11921 next = pos;
11922 do {
11923 next += 1;
11924 code = css.charCodeAt(next);
11925 } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
11926 currentToken = ["space", css.slice(pos, next)];
11927 pos = next - 1;
11928 break;
11929 case OPEN_SQUARE:
11930 case CLOSE_SQUARE:
11931 case OPEN_CURLY:
11932 case CLOSE_CURLY:
11933 case COLON:
11934 case SEMICOLON:
11935 case CLOSE_PARENTHESES:
11936 var controlChar = String.fromCharCode(code);
11937 currentToken = [
11938 controlChar,
11939 controlChar,
11940 pos
11941 ];
11942 break;
11943 case OPEN_PARENTHESES:
11944 prev = buffer.length ? buffer.pop()[1] : "";
11945 n2 = css.charCodeAt(pos + 1);
11946 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
11947 next = pos;
11948 do {
11949 escaped = false;
11950 next = css.indexOf(")", next + 1);
11951 if (next === -1) if (ignore || ignoreUnclosed) {
11952 next = pos;
11953 break;
11954 } else unclosed("bracket");
11955 escapePos = next;
11956 while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
11957 escapePos -= 1;
11958 escaped = !escaped;
11959 }
11960 } while (escaped);
11961 currentToken = [
11962 "brackets",
11963 css.slice(pos, next + 1),
11964 pos,
11965 next
11966 ];
11967 pos = next;
11968 } else {
11969 next = css.indexOf(")", pos + 1);
11970 content = css.slice(pos, next + 1);
11971 if (next === -1 || RE_BAD_BRACKET.test(content)) currentToken = [
11972 "(",
11973 "(",
11974 pos
11975 ];
11976 else {
11977 currentToken = [
11978 "brackets",
11979 content,
11980 pos,
11981 next
11982 ];
11983 pos = next;
11984 }
11985 }
11986 break;
11987 case SINGLE_QUOTE:
11988 case DOUBLE_QUOTE:
11989 quote = code === SINGLE_QUOTE ? "'" : "\"";
11990 next = pos;
11991 do {
11992 escaped = false;
11993 next = css.indexOf(quote, next + 1);
11994 if (next === -1) if (ignore || ignoreUnclosed) {
11995 next = pos + 1;
11996 break;
11997 } else unclosed("string");
11998 escapePos = next;
11999 while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
12000 escapePos -= 1;
12001 escaped = !escaped;
12002 }
12003 } while (escaped);
12004 currentToken = [
12005 "string",
12006 css.slice(pos, next + 1),
12007 pos,
12008 next
12009 ];
12010 pos = next;
12011 break;
12012 case AT:
12013 RE_AT_END.lastIndex = pos + 1;
12014 RE_AT_END.test(css);
12015 if (RE_AT_END.lastIndex === 0) next = css.length - 1;
12016 else next = RE_AT_END.lastIndex - 2;
12017 currentToken = [
12018 "at-word",
12019 css.slice(pos, next + 1),
12020 pos,
12021 next
12022 ];
12023 pos = next;
12024 break;
12025 case BACKSLASH:
12026 next = pos;
12027 escape = true;
12028 while (css.charCodeAt(next + 1) === BACKSLASH) {
12029 next += 1;
12030 escape = !escape;
12031 }
12032 code = css.charCodeAt(next + 1);
12033 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
12034 next += 1;
12035 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
12036 while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) next += 1;
12037 if (css.charCodeAt(next + 1) === SPACE) next += 1;
12038 }
12039 }
12040 currentToken = [
12041 "word",
12042 css.slice(pos, next + 1),
12043 pos,
12044 next
12045 ];
12046 pos = next;
12047 break;
12048 default:
12049 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
12050 next = css.indexOf("*/", pos + 2) + 1;
12051 if (next === 0) if (ignore || ignoreUnclosed) next = css.length;
12052 else unclosed("comment");
12053 currentToken = [
12054 "comment",
12055 css.slice(pos, next + 1),
12056 pos,
12057 next
12058 ];
12059 pos = next;
12060 } else {
12061 RE_WORD_END.lastIndex = pos + 1;
12062 RE_WORD_END.test(css);
12063 if (RE_WORD_END.lastIndex === 0) next = css.length - 1;
12064 else next = RE_WORD_END.lastIndex - 2;
12065 currentToken = [
12066 "word",
12067 css.slice(pos, next + 1),
12068 pos,
12069 next
12070 ];
12071 buffer.push(currentToken);
12072 pos = next;
12073 }
12074 break;
12075 }
12076 pos++;
12077 return currentToken;
12078 }
12079 function back(token) {
12080 returned.push(token);
12081 }
12082 return {
12083 back,
12084 endOfFile,
12085 nextToken,
12086 position
12087 };
12088 };
12089 var Container$5 = container;
12090 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
12091 _inherits(AtRule2, Container$5);
12092 function AtRule2(defaults) {
12093 var _this = Container$5.call(this, defaults) || this;
12094 _this.type = "atrule";
12095 return _this;
12096 }
12097 var _proto = AtRule2.prototype;
12098 _proto.append = function append() {
12099 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
12100 var _Container$5_prototype_append;
12101 if (!this.proxyOf.nodes) this.nodes = [];
12102 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([this], children));
12103 };
12104 _proto.prepend = function prepend() {
12105 for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) children[_key] = arguments[_key];
12106 var _Container$5_prototype_prepend;
12107 if (!this.proxyOf.nodes) this.nodes = [];
12108 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([this], children));
12109 };
12110 return AtRule2;
12111 }(Container$5);
12112 var atRule = AtRule$3;
12113 AtRule$3.default = AtRule$3;
12114 Container$5.registerAtRule(AtRule$3);
12115 var Container$4 = container;
12116 var LazyResult$3;
12117 var Processor$2;
12118 var Root$5 = /*#__PURE__*/ function(Container$4) {
12119 _inherits(Root2, Container$4);
12120 function Root2(defaults) {
12121 var _this = Container$4.call(this, defaults) || this;
12122 _this.type = "root";
12123 if (!_this.nodes) _this.nodes = [];
12124 return _this;
12125 }
12126 var _proto = Root2.prototype;
12127 _proto.normalize = function normalize(child, sample, type) {
12128 var nodes = Container$4.prototype.normalize.call(this, child);
12129 if (sample) {
12130 if (type === "prepend") if (this.nodes.length > 1) sample.raws.before = this.nodes[1].raws.before;
12131 else delete sample.raws.before;
12132 else if (this.first !== sample) for (var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;) {
12133 var node2 = _step.value;
12134 node2.raws.before = sample.raws.before;
12135 }
12136 }
12137 return nodes;
12138 };
12139 _proto.removeChild = function removeChild(child, ignore) {
12140 var index2 = this.index(child);
12141 if (!ignore && index2 === 0 && this.nodes.length > 1) this.nodes[1].raws.before = this.nodes[index2].raws.before;
12142 return Container$4.prototype.removeChild.call(this, child);
12143 };
12144 _proto.toResult = function toResult(opts) {
12145 if (opts === void 0) opts = {};
12146 return new LazyResult$3(new Processor$2(), this, opts).stringify();
12147 };
12148 return Root2;
12149 }(Container$4);
12150 Root$5.registerLazyResult = function(dependant) {
12151 LazyResult$3 = dependant;
12152 };
12153 Root$5.registerProcessor = function(dependant) {
12154 Processor$2 = dependant;
12155 };
12156 var root = Root$5;
12157 Root$5.default = Root$5;
12158 Container$4.registerRoot(Root$5);
12159 var list$2 = {
12160 comma: function comma(string) {
12161 return list$2.split(string, [","], true);
12162 },
12163 space: function space(string) {
12164 return list$2.split(string, [
12165 " ",
12166 "\n",
12167 " "
12168 ]);
12169 },
12170 split: function split(string, separators, last) {
12171 var array = [];
12172 var current = "";
12173 var split = false;
12174 var func = 0;
12175 var inQuote = false;
12176 var prevQuote = "";
12177 var escape = false;
12178 for (var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;) {
12179 var letter = _step.value;
12180 if (escape) escape = false;
12181 else if (letter === "\\") escape = true;
12182 else if (inQuote) {
12183 if (letter === prevQuote) inQuote = false;
12184 } else if (letter === "\"" || letter === "'") {
12185 inQuote = true;
12186 prevQuote = letter;
12187 } else if (letter === "(") func += 1;
12188 else if (letter === ")") {
12189 if (func > 0) func -= 1;
12190 } else if (func === 0) {
12191 if (separators.includes(letter)) split = true;
12192 }
12193 if (split) {
12194 if (current !== "") array.push(current.trim());
12195 current = "";
12196 split = false;
12197 } else current += letter;
12198 }
12199 if (last || current !== "") array.push(current.trim());
12200 return array;
12201 }
12202 };
12203 var list_1 = list$2;
12204 list$2.default = list$2;
12205 var Container$3 = container;
12206 var list$1 = list_1;
12207 var Rule$3 = /*#__PURE__*/ function(Container$3) {
12208 _inherits(Rule2, Container$3);
12209 function Rule2(defaults) {
12210 var _this = Container$3.call(this, defaults) || this;
12211 _this.type = "rule";
12212 if (!_this.nodes) _this.nodes = [];
12213 return _this;
12214 }
12215 _create_class(Rule2, [{
12216 key: "selectors",
12217 get: function get() {
12218 return list$1.comma(this.selector);
12219 },
12220 set: function set(values) {
12221 var match = this.selector ? this.selector.match(/,\s*/) : null;
12222 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
12223 this.selector = values.join(sep2);
12224 }
12225 }]);
12226 return Rule2;
12227 }(Container$3);
12228 var rule = Rule$3;
12229 Rule$3.default = Rule$3;
12230 Container$3.registerRule(Rule$3);
12231 var Declaration$2 = declaration;
12232 var tokenizer22 = tokenize;
12233 var Comment$2 = comment;
12234 var AtRule$2 = atRule;
12235 var Root$4 = root;
12236 var Rule$2 = rule;
12237 var SAFE_COMMENT_NEIGHBOR = {
12238 empty: true,
12239 space: true
12240 };
12241 function findLastWithPosition(tokens) {
12242 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
12243 var token = tokens[i2];
12244 var pos = token[3] || token[2];
12245 if (pos) return pos;
12246 }
12247 }
12248 var parser = /* @__PURE__ */ function() {
12249 function Parser2(input2) {
12250 this.input = input2;
12251 this.root = new Root$4();
12252 this.current = this.root;
12253 this.spaces = "";
12254 this.semicolon = false;
12255 this.createTokenizer();
12256 this.root.source = {
12257 input: input2,
12258 start: {
12259 column: 1,
12260 line: 1,
12261 offset: 0
12262 }
12263 };
12264 }
12265 var _proto = Parser2.prototype;
12266 _proto.atrule = function atrule(token) {
12267 var node2 = new AtRule$2();
12268 node2.name = token[1].slice(1);
12269 if (node2.name === "") this.unnamedAtrule(node2, token);
12270 this.init(node2, token[2]);
12271 var type;
12272 var prev;
12273 var shift;
12274 var last = false;
12275 var open = false;
12276 var params = [];
12277 var brackets = [];
12278 while (!this.tokenizer.endOfFile()) {
12279 token = this.tokenizer.nextToken();
12280 type = token[0];
12281 if (type === "(" || type === "[") brackets.push(type === "(" ? ")" : "]");
12282 else if (type === "{" && brackets.length > 0) brackets.push("}");
12283 else if (type === brackets[brackets.length - 1]) brackets.pop();
12284 if (brackets.length === 0) if (type === ";") {
12285 node2.source.end = this.getPosition(token[2]);
12286 node2.source.end.offset++;
12287 this.semicolon = true;
12288 break;
12289 } else if (type === "{") {
12290 open = true;
12291 break;
12292 } else if (type === "}") {
12293 if (params.length > 0) {
12294 shift = params.length - 1;
12295 prev = params[shift];
12296 while (prev && prev[0] === "space") prev = params[--shift];
12297 if (prev) {
12298 node2.source.end = this.getPosition(prev[3] || prev[2]);
12299 node2.source.end.offset++;
12300 }
12301 }
12302 this.end(token);
12303 break;
12304 } else params.push(token);
12305 else params.push(token);
12306 if (this.tokenizer.endOfFile()) {
12307 last = true;
12308 break;
12309 }
12310 }
12311 node2.raws.between = this.spacesAndCommentsFromEnd(params);
12312 if (params.length) {
12313 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
12314 this.raw(node2, "params", params);
12315 if (last) {
12316 token = params[params.length - 1];
12317 node2.source.end = this.getPosition(token[3] || token[2]);
12318 node2.source.end.offset++;
12319 this.spaces = node2.raws.between;
12320 node2.raws.between = "";
12321 }
12322 } else {
12323 node2.raws.afterName = "";
12324 node2.params = "";
12325 }
12326 if (open) {
12327 node2.nodes = [];
12328 this.current = node2;
12329 }
12330 };
12331 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
12332 var colon = this.colon(tokens);
12333 if (colon === false) return;
12334 var founded = 0;
12335 var token;
12336 for (var j = colon - 1; j >= 0; j--) {
12337 token = tokens[j];
12338 if (token[0] !== "space") {
12339 founded += 1;
12340 if (founded === 2) break;
12341 }
12342 }
12343 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
12344 };
12345 _proto.colon = function colon(tokens) {
12346 var brackets = 0;
12347 var token;
12348 var type;
12349 var prev;
12350 for (var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;) {
12351 var _step_value = _step.value;
12352 var i2 = _step_value[0];
12353 token = _step_value[1];
12354 type = token[0];
12355 if (type === "(") brackets += 1;
12356 if (type === ")") brackets -= 1;
12357 if (brackets === 0 && type === ":") if (!prev) this.doubleColon(token);
12358 else if (prev[0] === "word" && prev[1] === "progid") continue;
12359 else return i2;
12360 prev = token;
12361 }
12362 return false;
12363 };
12364 _proto.comment = function comment(token) {
12365 var node2 = new Comment$2();
12366 this.init(node2, token[2]);
12367 node2.source.end = this.getPosition(token[3] || token[2]);
12368 node2.source.end.offset++;
12369 var text = token[1].slice(2, -2);
12370 if (/^\s*$/.test(text)) {
12371 node2.text = "";
12372 node2.raws.left = text;
12373 node2.raws.right = "";
12374 } else {
12375 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
12376 node2.text = match[2];
12377 node2.raws.left = match[1];
12378 node2.raws.right = match[3];
12379 }
12380 };
12381 _proto.createTokenizer = function createTokenizer() {
12382 this.tokenizer = tokenizer22(this.input);
12383 };
12384 _proto.decl = function decl(tokens, customProperty) {
12385 var node2 = new Declaration$2();
12386 this.init(node2, tokens[0][2]);
12387 var last = tokens[tokens.length - 1];
12388 if (last[0] === ";") {
12389 this.semicolon = true;
12390 tokens.pop();
12391 }
12392 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
12393 node2.source.end.offset++;
12394 while (tokens[0][0] !== "word") {
12395 if (tokens.length === 1) this.unknownWord(tokens);
12396 node2.raws.before += tokens.shift()[1];
12397 }
12398 node2.source.start = this.getPosition(tokens[0][2]);
12399 node2.prop = "";
12400 while (tokens.length) {
12401 var type = tokens[0][0];
12402 if (type === ":" || type === "space" || type === "comment") break;
12403 node2.prop += tokens.shift()[1];
12404 }
12405 node2.raws.between = "";
12406 var token;
12407 while (tokens.length) {
12408 token = tokens.shift();
12409 if (token[0] === ":") {
12410 node2.raws.between += token[1];
12411 break;
12412 } else {
12413 if (token[0] === "word" && /\w/.test(token[1])) this.unknownWord([token]);
12414 node2.raws.between += token[1];
12415 }
12416 }
12417 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
12418 node2.raws.before += node2.prop[0];
12419 node2.prop = node2.prop.slice(1);
12420 }
12421 var firstSpaces = [];
12422 var next;
12423 while (tokens.length) {
12424 next = tokens[0][0];
12425 if (next !== "space" && next !== "comment") break;
12426 firstSpaces.push(tokens.shift());
12427 }
12428 this.precheckMissedSemicolon(tokens);
12429 for (var i2 = tokens.length - 1; i2 >= 0; i2--) {
12430 token = tokens[i2];
12431 if (token[1].toLowerCase() === "!important") {
12432 node2.important = true;
12433 var string = this.stringFrom(tokens, i2);
12434 string = this.spacesFromEnd(tokens) + string;
12435 if (string !== " !important") node2.raws.important = string;
12436 break;
12437 } else if (token[1].toLowerCase() === "important") {
12438 var cache = tokens.slice(0);
12439 var str = "";
12440 for (var j = i2; j > 0; j--) {
12441 var type1 = cache[j][0];
12442 if (str.trim().indexOf("!") === 0 && type1 !== "space") break;
12443 str = cache.pop()[1] + str;
12444 }
12445 if (str.trim().indexOf("!") === 0) {
12446 node2.important = true;
12447 node2.raws.important = str;
12448 tokens = cache;
12449 }
12450 }
12451 if (token[0] !== "space" && token[0] !== "comment") break;
12452 }
12453 if (tokens.some(function(i2) {
12454 return i2[0] !== "space" && i2[0] !== "comment";
12455 })) {
12456 node2.raws.between += firstSpaces.map(function(i2) {
12457 return i2[1];
12458 }).join("");
12459 firstSpaces = [];
12460 }
12461 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
12462 if (node2.value.includes(":") && !customProperty) this.checkMissedSemicolon(tokens);
12463 };
12464 _proto.doubleColon = function doubleColon(token) {
12465 throw this.input.error("Double colon", { offset: token[2] }, { offset: token[2] + token[1].length });
12466 };
12467 _proto.emptyRule = function emptyRule(token) {
12468 var node2 = new Rule$2();
12469 this.init(node2, token[2]);
12470 node2.selector = "";
12471 node2.raws.between = "";
12472 this.current = node2;
12473 };
12474 _proto.end = function end(token) {
12475 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
12476 this.semicolon = false;
12477 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
12478 this.spaces = "";
12479 if (this.current.parent) {
12480 this.current.source.end = this.getPosition(token[2]);
12481 this.current.source.end.offset++;
12482 this.current = this.current.parent;
12483 } else this.unexpectedClose(token);
12484 };
12485 _proto.endFile = function endFile() {
12486 if (this.current.parent) this.unclosedBlock();
12487 if (this.current.nodes && this.current.nodes.length) this.current.raws.semicolon = this.semicolon;
12488 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
12489 this.root.source.end = this.getPosition(this.tokenizer.position());
12490 };
12491 _proto.freeSemicolon = function freeSemicolon(token) {
12492 this.spaces += token[1];
12493 if (this.current.nodes) {
12494 var prev = this.current.nodes[this.current.nodes.length - 1];
12495 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
12496 prev.raws.ownSemicolon = this.spaces;
12497 this.spaces = "";
12498 }
12499 }
12500 };
12501 _proto.getPosition = function getPosition(offset) {
12502 var pos = this.input.fromOffset(offset);
12503 return {
12504 column: pos.col,
12505 line: pos.line,
12506 offset
12507 };
12508 };
12509 _proto.init = function init(node2, offset) {
12510 this.current.push(node2);
12511 node2.source = {
12512 input: this.input,
12513 start: this.getPosition(offset)
12514 };
12515 node2.raws.before = this.spaces;
12516 this.spaces = "";
12517 if (node2.type !== "comment") this.semicolon = false;
12518 };
12519 _proto.other = function other(start) {
12520 var end = false;
12521 var type = null;
12522 var colon = false;
12523 var bracket = null;
12524 var brackets = [];
12525 var customProperty = start[1].startsWith("--");
12526 var tokens = [];
12527 var token = start;
12528 while (token) {
12529 type = token[0];
12530 tokens.push(token);
12531 if (type === "(" || type === "[") {
12532 if (!bracket) bracket = token;
12533 brackets.push(type === "(" ? ")" : "]");
12534 } else if (customProperty && colon && type === "{") {
12535 if (!bracket) bracket = token;
12536 brackets.push("}");
12537 } else if (brackets.length === 0) {
12538 if (type === ";") if (colon) {
12539 this.decl(tokens, customProperty);
12540 return;
12541 } else break;
12542 else if (type === "{") {
12543 this.rule(tokens);
12544 return;
12545 } else if (type === "}") {
12546 this.tokenizer.back(tokens.pop());
12547 end = true;
12548 break;
12549 } else if (type === ":") colon = true;
12550 } else if (type === brackets[brackets.length - 1]) {
12551 brackets.pop();
12552 if (brackets.length === 0) bracket = null;
12553 }
12554 token = this.tokenizer.nextToken();
12555 }
12556 if (this.tokenizer.endOfFile()) end = true;
12557 if (brackets.length > 0) this.unclosedBracket(bracket);
12558 if (end && colon) {
12559 if (!customProperty) while (tokens.length) {
12560 token = tokens[tokens.length - 1][0];
12561 if (token !== "space" && token !== "comment") break;
12562 this.tokenizer.back(tokens.pop());
12563 }
12564 this.decl(tokens, customProperty);
12565 } else this.unknownWord(tokens);
12566 };
12567 _proto.parse = function parse() {
12568 var token;
12569 while (!this.tokenizer.endOfFile()) {
12570 token = this.tokenizer.nextToken();
12571 switch (token[0]) {
12572 case "space":
12573 this.spaces += token[1];
12574 break;
12575 case ";":
12576 this.freeSemicolon(token);
12577 break;
12578 case "}":
12579 this.end(token);
12580 break;
12581 case "comment":
12582 this.comment(token);
12583 break;
12584 case "at-word":
12585 this.atrule(token);
12586 break;
12587 case "{":
12588 this.emptyRule(token);
12589 break;
12590 default:
12591 this.other(token);
12592 break;
12593 }
12594 }
12595 this.endFile();
12596 };
12597 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
12598 _proto.raw = function raw(node2, prop, tokens, customProperty) {
12599 var token;
12600 var type;
12601 var length = tokens.length;
12602 var value = "";
12603 var clean = true;
12604 var next;
12605 var prev;
12606 for (var i2 = 0; i2 < length; i2 += 1) {
12607 token = tokens[i2];
12608 type = token[0];
12609 if (type === "space" && i2 === length - 1 && !customProperty) clean = false;
12610 else if (type === "comment") {
12611 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
12612 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
12613 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) if (value.slice(-1) === ",") clean = false;
12614 else value += token[1];
12615 else clean = false;
12616 } else value += token[1];
12617 }
12618 if (!clean) {
12619 var raw = tokens.reduce(function(all, i2) {
12620 return all + i2[1];
12621 }, "");
12622 node2.raws[prop] = {
12623 raw,
12624 value
12625 };
12626 }
12627 node2[prop] = value;
12628 };
12629 _proto.rule = function rule(tokens) {
12630 tokens.pop();
12631 var node2 = new Rule$2();
12632 this.init(node2, tokens[0][2]);
12633 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
12634 this.raw(node2, "selector", tokens);
12635 this.current = node2;
12636 };
12637 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
12638 var lastTokenType;
12639 var spaces = "";
12640 while (tokens.length) {
12641 lastTokenType = tokens[tokens.length - 1][0];
12642 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
12643 spaces = tokens.pop()[1] + spaces;
12644 }
12645 return spaces;
12646 };
12647 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
12648 var next;
12649 var spaces = "";
12650 while (tokens.length) {
12651 next = tokens[0][0];
12652 if (next !== "space" && next !== "comment") break;
12653 spaces += tokens.shift()[1];
12654 }
12655 return spaces;
12656 };
12657 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
12658 var lastTokenType;
12659 var spaces = "";
12660 while (tokens.length) {
12661 lastTokenType = tokens[tokens.length - 1][0];
12662 if (lastTokenType !== "space") break;
12663 spaces = tokens.pop()[1] + spaces;
12664 }
12665 return spaces;
12666 };
12667 _proto.stringFrom = function stringFrom(tokens, from) {
12668 var result2 = "";
12669 for (var i2 = from; i2 < tokens.length; i2++) result2 += tokens[i2][1];
12670 tokens.splice(from, tokens.length - from);
12671 return result2;
12672 };
12673 _proto.unclosedBlock = function unclosedBlock() {
12674 var pos = this.current.source.start;
12675 throw this.input.error("Unclosed block", pos.line, pos.column);
12676 };
12677 _proto.unclosedBracket = function unclosedBracket(bracket) {
12678 throw this.input.error("Unclosed bracket", { offset: bracket[2] }, { offset: bracket[2] + 1 });
12679 };
12680 _proto.unexpectedClose = function unexpectedClose(token) {
12681 throw this.input.error("Unexpected }", { offset: token[2] }, { offset: token[2] + 1 });
12682 };
12683 _proto.unknownWord = function unknownWord(tokens) {
12684 throw this.input.error("Unknown word", { offset: tokens[0][2] }, { offset: tokens[0][2] + tokens[0][1].length });
12685 };
12686 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
12687 throw this.input.error("At-rule without name", { offset: token[2] }, { offset: token[2] + token[1].length });
12688 };
12689 return Parser2;
12690 }();
12691 var Container$2 = container;
12692 var Parser22 = parser;
12693 var Input$2 = input;
12694 function parse$3(css, opts) {
12695 var parser2 = new Parser22(new Input$2(css, opts));
12696 try {
12697 parser2.parse();
12698 } catch (e2) {
12699 if (e2.name === "CssSyntaxError" && opts && opts.from) {
12700 if (/\.scss$/i.test(opts.from)) e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
12701 else if (/\.sass/i.test(opts.from)) e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
12702 else if (/\.less$/i.test(opts.from)) e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
12703 }
12704 throw e2;
12705 }
12706 return parser2.root;
12707 }
12708 var parse_1 = parse$3;
12709 parse$3.default = parse$3;
12710 Container$2.registerParse(parse$3);
12711 var isClean = symbols.isClean;
12712 var my = symbols.my;
12713 var MapGenerator$1 = mapGenerator;
12714 var stringify$2 = stringify_1;
12715 var Container$1 = container;
12716 var Document$2 = document$1$2;
12717 var warnOnce$1 = warnOnce$2;
12718 var Result$2 = result;
12719 var parse$2 = parse_1;
12720 var Root$3 = root;
12721 var TYPE_TO_CLASS_NAME = {
12722 atrule: "AtRule",
12723 comment: "Comment",
12724 decl: "Declaration",
12725 document: "Document",
12726 root: "Root",
12727 rule: "Rule"
12728 };
12729 var PLUGIN_PROPS = {
12730 AtRule: true,
12731 AtRuleExit: true,
12732 Comment: true,
12733 CommentExit: true,
12734 Declaration: true,
12735 DeclarationExit: true,
12736 Document: true,
12737 DocumentExit: true,
12738 Once: true,
12739 OnceExit: true,
12740 postcssPlugin: true,
12741 prepare: true,
12742 Root: true,
12743 RootExit: true,
12744 Rule: true,
12745 RuleExit: true
12746 };
12747 var NOT_VISITORS = {
12748 Once: true,
12749 postcssPlugin: true,
12750 prepare: true
12751 };
12752 var CHILDREN = 0;
12753 function isPromise(obj) {
12754 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
12755 }
12756 function getEvents(node2) {
12757 var key = false;
12758 var type = TYPE_TO_CLASS_NAME[node2.type];
12759 if (node2.type === "decl") key = node2.prop.toLowerCase();
12760 else if (node2.type === "atrule") key = node2.name.toLowerCase();
12761 if (key && node2.append) return [
12762 type,
12763 type + "-" + key,
12764 CHILDREN,
12765 type + "Exit",
12766 type + "Exit-" + key
12767 ];
12768 else if (key) return [
12769 type,
12770 type + "-" + key,
12771 type + "Exit",
12772 type + "Exit-" + key
12773 ];
12774 else if (node2.append) return [
12775 type,
12776 CHILDREN,
12777 type + "Exit"
12778 ];
12779 else return [type, type + "Exit"];
12780 }
12781 function toStack(node2) {
12782 var events;
12783 if (node2.type === "document") events = [
12784 "Document",
12785 CHILDREN,
12786 "DocumentExit"
12787 ];
12788 else if (node2.type === "root") events = [
12789 "Root",
12790 CHILDREN,
12791 "RootExit"
12792 ];
12793 else events = getEvents(node2);
12794 return {
12795 eventIndex: 0,
12796 events,
12797 iterator: 0,
12798 node: node2,
12799 visitorIndex: 0,
12800 visitors: []
12801 };
12802 }
12803 function cleanMarks(node2) {
12804 node2[isClean] = false;
12805 if (node2.nodes) node2.nodes.forEach(function(i2) {
12806 return cleanMarks(i2);
12807 });
12808 return node2;
12809 }
12810 var postcss$2 = {};
12811 var LazyResult$2 = /*#__PURE__*/ function() {
12812 function LazyResult2(processor2, css, opts) {
12813 var _this = this;
12814 this.stringified = false;
12815 this.processed = false;
12816 var root2;
12817 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) root2 = cleanMarks(css);
12818 else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
12819 root2 = cleanMarks(css.root);
12820 if (css.map) {
12821 if (typeof opts.map === "undefined") opts.map = {};
12822 if (!opts.map.inline) opts.map.inline = false;
12823 opts.map.prev = css.map;
12824 }
12825 } else {
12826 var parser2 = parse$2;
12827 if (opts.syntax) parser2 = opts.syntax.parse;
12828 if (opts.parser) parser2 = opts.parser;
12829 if (parser2.parse) parser2 = parser2.parse;
12830 try {
12831 root2 = parser2(css, opts);
12832 } catch (error) {
12833 this.processed = true;
12834 this.error = error;
12835 }
12836 if (root2 && !root2[my]) Container$1.rebuild(root2);
12837 }
12838 this.result = new Result$2(processor2, root2, opts);
12839 this.helpers = _extends({}, postcss$2, {
12840 postcss: postcss$2,
12841 result: this.result
12842 });
12843 this.plugins = this.processor.plugins.map(function(plugin22) {
12844 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) return _extends({}, plugin22, plugin22.prepare(_this.result));
12845 else return plugin22;
12846 });
12847 }
12848 var _proto = LazyResult2.prototype;
12849 _proto.async = function async() {
12850 if (this.error) return Promise.reject(this.error);
12851 if (this.processed) return Promise.resolve(this.result);
12852 if (!this.processing) this.processing = this.runAsync();
12853 return this.processing;
12854 };
12855 _proto.catch = function _catch(onRejected) {
12856 return this.async().catch(onRejected);
12857 };
12858 _proto.finally = function _finally(onFinally) {
12859 return this.async().then(onFinally, onFinally);
12860 };
12861 _proto.getAsyncError = function getAsyncError() {
12862 throw new Error("Use process(css).then(cb) to work with async plugins");
12863 };
12864 _proto.handleError = function handleError(error, node2) {
12865 var plugin22 = this.result.lastPlugin;
12866 try {
12867 if (node2) node2.addToError(error);
12868 this.error = error;
12869 if (error.name === "CssSyntaxError" && !error.plugin) {
12870 error.plugin = plugin22.postcssPlugin;
12871 error.setMessage();
12872 } else if (plugin22.postcssVersion) {
12873 var pluginName = plugin22.postcssPlugin;
12874 var pluginVer = plugin22.postcssVersion;
12875 var runtimeVer = this.result.processor.version;
12876 var a2 = pluginVer.split(".");
12877 var b = runtimeVer.split(".");
12878 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) 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.");
12879 }
12880 } catch (err) {
12881 if (console && console.error) console.error(err);
12882 }
12883 return error;
12884 };
12885 _proto.prepareVisitors = function prepareVisitors() {
12886 var _this = this;
12887 this.listeners = {};
12888 var add = function(plugin22, type, cb) {
12889 if (!_this.listeners[type]) _this.listeners[type] = [];
12890 _this.listeners[type].push([plugin22, cb]);
12891 };
12892 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
12893 var plugin22 = _step.value;
12894 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") for (var event in plugin22) {
12895 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
12896 if (!NOT_VISITORS[event]) {
12897 if (_type_of(plugin22[event]) === "object") for (var filter in plugin22[event]) if (filter === "*") add(plugin22, event, plugin22[event][filter]);
12898 else add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
12899 else if (typeof plugin22[event] === "function") add(plugin22, event, plugin22[event]);
12900 }
12901 }
12902 }
12903 this.hasListener = Object.keys(this.listeners).length > 0;
12904 };
12905 _proto.runAsync = function runAsync() {
12906 var _this = this;
12907 return _async_to_generator(function() {
12908 var i2;
12909 var plugin22;
12910 var promise;
12911 var error;
12912 var root2;
12913 var stack;
12914 var promise1;
12915 var e2;
12916 var node2;
12917 var _loop;
12918 var _iterator;
12919 var _step;
12920 return _ts_generator(this, function(_state) {
12921 switch (_state.label) {
12922 case 0:
12923 _this.plugin = 0;
12924 i2 = 0;
12925 _state.label = 1;
12926 case 1:
12927 if (!(i2 < _this.plugins.length)) return [3, 6];
12928 plugin22 = _this.plugins[i2];
12929 promise = _this.runOnRoot(plugin22);
12930 if (!isPromise(promise)) return [3, 5];
12931 _state.label = 2;
12932 case 2:
12933 _state.trys.push([
12934 2,
12935 4,
12936 ,
12937 5
12938 ]);
12939 return [4, promise];
12940 case 3:
12941 _state.sent();
12942 return [3, 5];
12943 case 4:
12944 error = _state.sent();
12945 throw _this.handleError(error);
12946 case 5:
12947 i2++;
12948 return [3, 1];
12949 case 6:
12950 _this.prepareVisitors();
12951 if (!_this.hasListener) return [3, 18];
12952 root2 = _this.result.root;
12953 _state.label = 7;
12954 case 7:
12955 if (!!root2[isClean]) return [3, 14];
12956 root2[isClean] = true;
12957 stack = [toStack(root2)];
12958 _state.label = 8;
12959 case 8:
12960 if (!(stack.length > 0)) return [3, 13];
12961 promise1 = _this.visitTick(stack);
12962 if (!isPromise(promise1)) return [3, 12];
12963 _state.label = 9;
12964 case 9:
12965 _state.trys.push([
12966 9,
12967 11,
12968 ,
12969 12
12970 ]);
12971 return [4, promise1];
12972 case 10:
12973 _state.sent();
12974 return [3, 12];
12975 case 11:
12976 e2 = _state.sent();
12977 node2 = stack[stack.length - 1].node;
12978 throw _this.handleError(e2, node2);
12979 case 12: return [3, 8];
12980 case 13: return [3, 7];
12981 case 14:
12982 if (!_this.listeners.OnceExit) return [3, 18];
12983 _loop = function() {
12984 var _step_value;
12985 var plugin22;
12986 var visitor;
12987 var roots;
12988 var e2;
12989 return _ts_generator(this, function(_state) {
12990 switch (_state.label) {
12991 case 0:
12992 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
12993 _this.result.lastPlugin = plugin22;
12994 _state.label = 1;
12995 case 1:
12996 _state.trys.push([
12997 1,
12998 6,
12999 ,
13000 7
13001 ]);
13002 if (!(root2.type === "document")) return [3, 3];
13003 roots = root2.nodes.map(function(subRoot) {
13004 return visitor(subRoot, _this.helpers);
13005 });
13006 return [4, Promise.all(roots)];
13007 case 2:
13008 _state.sent();
13009 return [3, 5];
13010 case 3: return [4, visitor(root2, _this.helpers)];
13011 case 4:
13012 _state.sent();
13013 _state.label = 5;
13014 case 5: return [3, 7];
13015 case 6:
13016 e2 = _state.sent();
13017 throw _this.handleError(e2);
13018 case 7: return [2];
13019 }
13020 });
13021 };
13022 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
13023 _state.label = 15;
13024 case 15:
13025 if (!!(_step = _iterator()).done) return [3, 18];
13026 return [5, _ts_values(_loop())];
13027 case 16:
13028 _state.sent();
13029 _state.label = 17;
13030 case 17: return [3, 15];
13031 case 18:
13032 _this.processed = true;
13033 return [2, _this.stringify()];
13034 }
13035 });
13036 })();
13037 };
13038 _proto.runOnRoot = function runOnRoot(plugin22) {
13039 var _this = this;
13040 this.result.lastPlugin = plugin22;
13041 try {
13042 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
13043 if (this.result.root.type === "document") {
13044 var roots = this.result.root.nodes.map(function(root2) {
13045 return plugin22.Once(root2, _this.helpers);
13046 });
13047 if (isPromise(roots[0])) return Promise.all(roots);
13048 return roots;
13049 }
13050 return plugin22.Once(this.result.root, this.helpers);
13051 } else if (typeof plugin22 === "function") return plugin22(this.result.root, this.result);
13052 } catch (error) {
13053 throw this.handleError(error);
13054 }
13055 };
13056 _proto.stringify = function stringify() {
13057 if (this.error) throw this.error;
13058 if (this.stringified) return this.result;
13059 this.stringified = true;
13060 this.sync();
13061 var opts = this.result.opts;
13062 var str = stringify$2;
13063 if (opts.syntax) str = opts.syntax.stringify;
13064 if (opts.stringifier) str = opts.stringifier;
13065 if (str.stringify) str = str.stringify;
13066 var data = new MapGenerator$1(str, this.result.root, this.result.opts).generate();
13067 this.result.css = data[0];
13068 this.result.map = data[1];
13069 return this.result;
13070 };
13071 _proto.sync = function sync() {
13072 if (this.error) throw this.error;
13073 if (this.processed) return this.result;
13074 this.processed = true;
13075 if (this.processing) throw this.getAsyncError();
13076 for (var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;) {
13077 var plugin22 = _step.value;
13078 if (isPromise(this.runOnRoot(plugin22))) throw this.getAsyncError();
13079 }
13080 this.prepareVisitors();
13081 if (this.hasListener) {
13082 var root2 = this.result.root;
13083 while (!root2[isClean]) {
13084 root2[isClean] = true;
13085 this.walkSync(root2);
13086 }
13087 if (this.listeners.OnceExit) if (root2.type === "document") for (var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;) {
13088 var subRoot = _step1.value;
13089 this.visitSync(this.listeners.OnceExit, subRoot);
13090 }
13091 else this.visitSync(this.listeners.OnceExit, root2);
13092 }
13093 return this.result;
13094 };
13095 _proto.then = function then(onFulfilled, onRejected) {
13096 if (!("from" in this.opts)) 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.");
13097 return this.async().then(onFulfilled, onRejected);
13098 };
13099 _proto.toString = function toString() {
13100 return this.css;
13101 };
13102 _proto.visitSync = function visitSync(visitors, node2) {
13103 for (var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;) {
13104 var _step_value = _step.value;
13105 var plugin22 = _step_value[0];
13106 var visitor = _step_value[1];
13107 this.result.lastPlugin = plugin22;
13108 var promise = void 0;
13109 try {
13110 promise = visitor(node2, this.helpers);
13111 } catch (e2) {
13112 throw this.handleError(e2, node2.proxyOf);
13113 }
13114 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) return true;
13115 if (isPromise(promise)) throw this.getAsyncError();
13116 }
13117 };
13118 _proto.visitTick = function visitTick(stack) {
13119 var visit2 = stack[stack.length - 1];
13120 var node2 = visit2.node;
13121 var visitors = visit2.visitors;
13122 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
13123 stack.pop();
13124 return;
13125 }
13126 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
13127 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex];
13128 var plugin22 = _visitors_visit2_visitorIndex[0];
13129 var visitor = _visitors_visit2_visitorIndex[1];
13130 visit2.visitorIndex += 1;
13131 if (visit2.visitorIndex === visitors.length) {
13132 visit2.visitors = [];
13133 visit2.visitorIndex = 0;
13134 }
13135 this.result.lastPlugin = plugin22;
13136 try {
13137 return visitor(node2.toProxy(), this.helpers);
13138 } catch (e2) {
13139 throw this.handleError(e2, node2);
13140 }
13141 }
13142 if (visit2.iterator !== 0) {
13143 var iterator = visit2.iterator;
13144 var child;
13145 while (child = node2.nodes[node2.indexes[iterator]]) {
13146 node2.indexes[iterator] += 1;
13147 if (!child[isClean]) {
13148 child[isClean] = true;
13149 stack.push(toStack(child));
13150 return;
13151 }
13152 }
13153 visit2.iterator = 0;
13154 delete node2.indexes[iterator];
13155 }
13156 var events = visit2.events;
13157 while (visit2.eventIndex < events.length) {
13158 var event = events[visit2.eventIndex];
13159 visit2.eventIndex += 1;
13160 if (event === CHILDREN) {
13161 if (node2.nodes && node2.nodes.length) {
13162 node2[isClean] = true;
13163 visit2.iterator = node2.getIterator();
13164 }
13165 return;
13166 } else if (this.listeners[event]) {
13167 visit2.visitors = this.listeners[event];
13168 return;
13169 }
13170 }
13171 stack.pop();
13172 };
13173 _proto.walkSync = function walkSync(node2) {
13174 var _this = this;
13175 node2[isClean] = true;
13176 for (var _iterator = _create_for_of_iterator_helper_loose(getEvents(node2)), _step; !(_step = _iterator()).done;) {
13177 var event = _step.value;
13178 if (event === CHILDREN) {
13179 if (node2.nodes) node2.each(function(child) {
13180 if (!child[isClean]) _this.walkSync(child);
13181 });
13182 } else {
13183 var visitors = this.listeners[event];
13184 if (visitors) {
13185 if (this.visitSync(visitors, node2.toProxy())) return;
13186 }
13187 }
13188 }
13189 };
13190 _proto.warnings = function warnings() {
13191 return this.sync().warnings();
13192 };
13193 _create_class(LazyResult2, [
13194 {
13195 key: "content",
13196 get: function get() {
13197 return this.stringify().content;
13198 }
13199 },
13200 {
13201 key: "css",
13202 get: function get() {
13203 return this.stringify().css;
13204 }
13205 },
13206 {
13207 key: "map",
13208 get: function get() {
13209 return this.stringify().map;
13210 }
13211 },
13212 {
13213 key: "messages",
13214 get: function get() {
13215 return this.sync().messages;
13216 }
13217 },
13218 {
13219 key: "opts",
13220 get: function get() {
13221 return this.result.opts;
13222 }
13223 },
13224 {
13225 key: "processor",
13226 get: function get() {
13227 return this.result.processor;
13228 }
13229 },
13230 {
13231 key: "root",
13232 get: function get() {
13233 return this.sync().root;
13234 }
13235 },
13236 {
13237 key: Symbol.toStringTag,
13238 get: function get() {
13239 return "LazyResult";
13240 }
13241 }
13242 ]);
13243 return LazyResult2;
13244 }();
13245 LazyResult$2.registerPostcss = function(dependant) {
13246 postcss$2 = dependant;
13247 };
13248 var lazyResult = LazyResult$2;
13249 LazyResult$2.default = LazyResult$2;
13250 Root$3.registerLazyResult(LazyResult$2);
13251 Document$2.registerLazyResult(LazyResult$2);
13252 var MapGenerator22 = mapGenerator;
13253 var stringify$1 = stringify_1;
13254 var warnOnce22 = warnOnce$2;
13255 var parse$1 = parse_1;
13256 var Result$1 = result;
13257 var NoWorkResult$1 = /*#__PURE__*/ function() {
13258 function NoWorkResult2(processor2, css, opts) {
13259 css = css.toString();
13260 this.stringified = false;
13261 this._processor = processor2;
13262 this._css = css;
13263 this._opts = opts;
13264 this._map = void 0;
13265 var root2;
13266 var str = stringify$1;
13267 this.result = new Result$1(this._processor, root2, this._opts);
13268 this.result.css = css;
13269 var self = this;
13270 Object.defineProperty(this.result, "root", { get: function get() {
13271 return self.root;
13272 } });
13273 var map = new MapGenerator22(str, root2, this._opts, css);
13274 if (map.isMap()) {
13275 var _map_generate = map.generate();
13276 var generatedCSS = _map_generate[0];
13277 var generatedMap = _map_generate[1];
13278 if (generatedCSS) this.result.css = generatedCSS;
13279 if (generatedMap) this.result.map = generatedMap;
13280 } else {
13281 map.clearAnnotation();
13282 this.result.css = map.css;
13283 }
13284 }
13285 var _proto = NoWorkResult2.prototype;
13286 _proto.async = function async() {
13287 if (this.error) return Promise.reject(this.error);
13288 return Promise.resolve(this.result);
13289 };
13290 _proto.catch = function _catch(onRejected) {
13291 return this.async().catch(onRejected);
13292 };
13293 _proto.finally = function _finally(onFinally) {
13294 return this.async().then(onFinally, onFinally);
13295 };
13296 _proto.sync = function sync() {
13297 if (this.error) throw this.error;
13298 return this.result;
13299 };
13300 _proto.then = function then(onFulfilled, onRejected) {
13301 if (!("from" in this._opts)) 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.");
13302 return this.async().then(onFulfilled, onRejected);
13303 };
13304 _proto.toString = function toString() {
13305 return this._css;
13306 };
13307 _proto.warnings = function warnings() {
13308 return [];
13309 };
13310 _create_class(NoWorkResult2, [
13311 {
13312 key: "content",
13313 get: function get() {
13314 return this.result.css;
13315 }
13316 },
13317 {
13318 key: "css",
13319 get: function get() {
13320 return this.result.css;
13321 }
13322 },
13323 {
13324 key: "map",
13325 get: function get() {
13326 return this.result.map;
13327 }
13328 },
13329 {
13330 key: "messages",
13331 get: function get() {
13332 return [];
13333 }
13334 },
13335 {
13336 key: "opts",
13337 get: function get() {
13338 return this.result.opts;
13339 }
13340 },
13341 {
13342 key: "processor",
13343 get: function get() {
13344 return this.result.processor;
13345 }
13346 },
13347 {
13348 key: "root",
13349 get: function get() {
13350 if (this._root) return this._root;
13351 var root2;
13352 var parser2 = parse$1;
13353 try {
13354 root2 = parser2(this._css, this._opts);
13355 } catch (error) {
13356 this.error = error;
13357 }
13358 if (this.error) throw this.error;
13359 else {
13360 this._root = root2;
13361 return root2;
13362 }
13363 }
13364 },
13365 {
13366 key: Symbol.toStringTag,
13367 get: function get() {
13368 return "NoWorkResult";
13369 }
13370 }
13371 ]);
13372 return NoWorkResult2;
13373 }();
13374 var noWorkResult = NoWorkResult$1;
13375 NoWorkResult$1.default = NoWorkResult$1;
13376 var NoWorkResult22 = noWorkResult;
13377 var LazyResult$1 = lazyResult;
13378 var Document$1 = document$1$2;
13379 var Root$2 = root;
13380 var Processor$1 = /*#__PURE__*/ function() {
13381 function Processor2(plugins) {
13382 if (plugins === void 0) plugins = [];
13383 this.version = "8.4.38";
13384 this.plugins = this.normalize(plugins);
13385 }
13386 var _proto = Processor2.prototype;
13387 _proto.normalize = function normalize(plugins) {
13388 var normalized = [];
13389 for (var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;) {
13390 var i2 = _step.value;
13391 if (i2.postcss === true) i2 = i2();
13392 else if (i2.postcss) i2 = i2.postcss;
13393 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) normalized = normalized.concat(i2.plugins);
13394 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) normalized.push(i2);
13395 else if (typeof i2 === "function") normalized.push(i2);
13396 else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) 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.");
13397 else throw new Error(i2 + " is not a PostCSS plugin");
13398 }
13399 return normalized;
13400 };
13401 _proto.process = function process1(css, opts) {
13402 if (opts === void 0) opts = {};
13403 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) return new NoWorkResult22(this, css, opts);
13404 else return new LazyResult$1(this, css, opts);
13405 };
13406 _proto.use = function use(plugin22) {
13407 this.plugins = this.plugins.concat(this.normalize([plugin22]));
13408 return this;
13409 };
13410 return Processor2;
13411 }();
13412 var processor = Processor$1;
13413 Processor$1.default = Processor$1;
13414 Root$2.registerProcessor(Processor$1);
13415 Document$1.registerProcessor(Processor$1);
13416 var Declaration$1 = declaration;
13417 var PreviousMap22 = previousMap;
13418 var Comment$1 = comment;
13419 var AtRule$1 = atRule;
13420 var Input$1 = input;
13421 var Root$1 = root;
13422 var Rule$1 = rule;
13423 function fromJSON$1(json, inputs) {
13424 if (Array.isArray(json)) return json.map(function(n2) {
13425 return fromJSON$1(n2);
13426 });
13427 var ownInputs = json.inputs;
13428 var defaults = _object_without_properties_loose(json, ["inputs"]);
13429 if (ownInputs) {
13430 inputs = [];
13431 for (var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;) {
13432 var input2 = _step.value;
13433 var inputHydrated = _extends({}, input2, { __proto__: Input$1.prototype });
13434 if (inputHydrated.map) inputHydrated.map = _extends({}, inputHydrated.map, { __proto__: PreviousMap22.prototype });
13435 inputs.push(inputHydrated);
13436 }
13437 }
13438 if (defaults.nodes) defaults.nodes = json.nodes.map(function(n2) {
13439 return fromJSON$1(n2, inputs);
13440 });
13441 if (defaults.source) {
13442 var _defaults_source = defaults.source;
13443 var inputId = _defaults_source.inputId;
13444 defaults.source = _object_without_properties_loose(_defaults_source, ["inputId"]);
13445 if (inputId != null) defaults.source.input = inputs[inputId];
13446 }
13447 if (defaults.type === "root") return new Root$1(defaults);
13448 else if (defaults.type === "decl") return new Declaration$1(defaults);
13449 else if (defaults.type === "rule") return new Rule$1(defaults);
13450 else if (defaults.type === "comment") return new Comment$1(defaults);
13451 else if (defaults.type === "atrule") return new AtRule$1(defaults);
13452 else throw new Error("Unknown node type: " + json.type);
13453 }
13454 var fromJSON_1 = fromJSON$1;
13455 fromJSON$1.default = fromJSON$1;
13456 var CssSyntaxError22 = cssSyntaxError;
13457 var Declaration22 = declaration;
13458 var LazyResult22 = lazyResult;
13459 var Container22 = container;
13460 var Processor22 = processor;
13461 var stringify = stringify_1;
13462 var fromJSON = fromJSON_1;
13463 var Document222 = document$1$2;
13464 var Warning22 = warning;
13465 var Comment22 = comment;
13466 var AtRule22 = atRule;
13467 var Result22 = result;
13468 var Input22 = input;
13469 var parse = parse_1;
13470 var list = list_1;
13471 var Rule22 = rule;
13472 var Root22 = root;
13473 var Node22 = node;
13474 function postcss() {
13475 for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) plugins[_key] = arguments[_key];
13476 if (plugins.length === 1 && Array.isArray(plugins[0])) plugins = plugins[0];
13477 return new Processor22(plugins);
13478 }
13479 postcss.plugin = function plugin2(name, initializer) {
13480 var warningPrinted = false;
13481 function creator() {
13482 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
13483 if (console && console.warn && !warningPrinted) {
13484 warningPrinted = true;
13485 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
13486 if ({}.LANG && {}.LANG.startsWith("cn")) console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
13487 }
13488 var transformer = initializer.apply(void 0, [].concat(args));
13489 transformer.postcssPlugin = name;
13490 transformer.postcssVersion = new Processor22().version;
13491 return transformer;
13492 }
13493 var cache;
13494 Object.defineProperty(creator, "postcss", { get: function get() {
13495 if (!cache) cache = creator();
13496 return cache;
13497 } });
13498 creator.process = function(css, processOpts, pluginOpts) {
13499 return postcss([creator(pluginOpts)]).process(css, processOpts);
13500 };
13501 return creator;
13502 };
13503 postcss.stringify = stringify;
13504 postcss.parse = parse;
13505 postcss.fromJSON = fromJSON;
13506 postcss.list = list;
13507 postcss.comment = function(defaults) {
13508 return new Comment22(defaults);
13509 };
13510 postcss.atRule = function(defaults) {
13511 return new AtRule22(defaults);
13512 };
13513 postcss.decl = function(defaults) {
13514 return new Declaration22(defaults);
13515 };
13516 postcss.rule = function(defaults) {
13517 return new Rule22(defaults);
13518 };
13519 postcss.root = function(defaults) {
13520 return new Root22(defaults);
13521 };
13522 postcss.document = function(defaults) {
13523 return new Document222(defaults);
13524 };
13525 postcss.CssSyntaxError = CssSyntaxError22;
13526 postcss.Declaration = Declaration22;
13527 postcss.Container = Container22;
13528 postcss.Processor = Processor22;
13529 postcss.Document = Document222;
13530 postcss.Comment = Comment22;
13531 postcss.Warning = Warning22;
13532 postcss.AtRule = AtRule22;
13533 postcss.Result = Result22;
13534 postcss.Input = Input22;
13535 postcss.Rule = Rule22;
13536 postcss.Root = Root22;
13537 postcss.Node = Node22;
13538 LazyResult22.registerPostcss(postcss);
13539 var postcss_1 = postcss;
13540 postcss.default = postcss;
13541 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
13542 postcss$1.stringify;
13543 postcss$1.fromJSON;
13544 postcss$1.plugin;
13545 postcss$1.parse;
13546 postcss$1.list;
13547 postcss$1.document;
13548 postcss$1.comment;
13549 postcss$1.atRule;
13550 postcss$1.rule;
13551 postcss$1.decl;
13552 postcss$1.root;
13553 postcss$1.CssSyntaxError;
13554 postcss$1.Declaration;
13555 postcss$1.Container;
13556 postcss$1.Processor;
13557 postcss$1.Document;
13558 postcss$1.Comment;
13559 postcss$1.Warning;
13560 postcss$1.AtRule;
13561 postcss$1.Result;
13562 postcss$1.Input;
13563 postcss$1.Rule;
13564 postcss$1.Root;
13565 postcss$1.Node;
13566 var BaseRRNode = /*#__PURE__*/ function() {
13567 function BaseRRNode() {
13568 for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) _args[_key] = arguments[_key];
13569 __publicField2(this, "parentElement", null);
13570 __publicField2(this, "parentNode", null);
13571 __publicField2(this, "ownerDocument");
13572 __publicField2(this, "firstChild", null);
13573 __publicField2(this, "lastChild", null);
13574 __publicField2(this, "previousSibling", null);
13575 __publicField2(this, "nextSibling", null);
13576 __publicField2(this, "ELEMENT_NODE", 1);
13577 __publicField2(this, "TEXT_NODE", 3);
13578 __publicField2(this, "nodeType");
13579 __publicField2(this, "nodeName");
13580 __publicField2(this, "RRNodeType");
13581 }
13582 var _proto = BaseRRNode.prototype;
13583 _proto.contains = function contains(node2) {
13584 if (!_instanceof(node2, BaseRRNode)) return false;
13585 else if (node2.ownerDocument !== this.ownerDocument) return false;
13586 else if (node2 === this) return true;
13587 while (node2.parentNode) {
13588 if (node2.parentNode === this) return true;
13589 node2 = node2.parentNode;
13590 }
13591 return false;
13592 };
13593 _proto.appendChild = function appendChild(_newChild) {
13594 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
13595 };
13596 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
13597 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
13598 };
13599 _proto.removeChild = function removeChild(_node) {
13600 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
13601 };
13602 _proto.toString = function toString() {
13603 return "RRNode";
13604 };
13605 _create_class(BaseRRNode, [{
13606 key: "childNodes",
13607 get: function get() {
13608 var childNodes2 = [];
13609 var childIterator = this.firstChild;
13610 while (childIterator) {
13611 childNodes2.push(childIterator);
13612 childIterator = childIterator.nextSibling;
13613 }
13614 return childNodes2;
13615 }
13616 }]);
13617 return BaseRRNode;
13618 }();
13619 var testableAccessors = {
13620 Node: [
13621 "childNodes",
13622 "parentNode",
13623 "parentElement",
13624 "textContent"
13625 ],
13626 ShadowRoot: ["host", "styleSheets"],
13627 Element: [
13628 "shadowRoot",
13629 "querySelector",
13630 "querySelectorAll"
13631 ],
13632 MutationObserver: []
13633 };
13634 var testableMethods = {
13635 Node: ["contains", "getRootNode"],
13636 ShadowRoot: ["getSelection"],
13637 Element: [],
13638 MutationObserver: ["constructor"]
13639 };
13640 var untaintedBasePrototype = {};
13641 var isAngularZonePresent = function() {
13642 return !!globalThis.Zone;
13643 };
13644 function getUntaintedPrototype(key) {
13645 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
13646 var defaultObj = globalThis[key];
13647 var defaultPrototype = defaultObj.prototype;
13648 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
13649 var isUntaintedAccessors = Boolean(accessorNames && accessorNames.every(function(accessor) {
13650 var _a2;
13651 var _b;
13652 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
13653 }));
13654 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
13655 var isUntaintedMethods = Boolean(methodNames && methodNames.every(function(method) {
13656 var _a2;
13657 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
13658 }));
13659 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
13660 untaintedBasePrototype[key] = defaultObj.prototype;
13661 return defaultObj.prototype;
13662 }
13663 try {
13664 var iframeEl = document.createElement("iframe");
13665 document.body.appendChild(iframeEl);
13666 var win = iframeEl.contentWindow;
13667 if (!win) return defaultObj.prototype;
13668 var untaintedObject = win[key].prototype;
13669 document.body.removeChild(iframeEl);
13670 if (!untaintedObject) return defaultPrototype;
13671 return untaintedBasePrototype[key] = untaintedObject;
13672 } catch (e) {
13673 return defaultPrototype;
13674 }
13675 }
13676 var untaintedAccessorCache = {};
13677 function getUntaintedAccessor(key, instance, accessor) {
13678 var _a2;
13679 var cacheKey = key + "." + String(accessor);
13680 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
13681 var untaintedPrototype = getUntaintedPrototype(key);
13682 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
13683 if (!untaintedAccessor) return instance[accessor];
13684 untaintedAccessorCache[cacheKey] = untaintedAccessor;
13685 return untaintedAccessor.call(instance);
13686 }
13687 var untaintedMethodCache = {};
13688 function getUntaintedMethod(key, instance, method) {
13689 var cacheKey = key + "." + String(method);
13690 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
13691 var untaintedMethod = getUntaintedPrototype(key)[method];
13692 if (typeof untaintedMethod !== "function") return instance[method];
13693 untaintedMethodCache[cacheKey] = untaintedMethod;
13694 return untaintedMethod.bind(instance);
13695 }
13696 function childNodes(n2) {
13697 return getUntaintedAccessor("Node", n2, "childNodes");
13698 }
13699 function parentNode(n2) {
13700 return getUntaintedAccessor("Node", n2, "parentNode");
13701 }
13702 function parentElement(n2) {
13703 return getUntaintedAccessor("Node", n2, "parentElement");
13704 }
13705 function textContent(n2) {
13706 return getUntaintedAccessor("Node", n2, "textContent");
13707 }
13708 function contains(n2, other) {
13709 return getUntaintedMethod("Node", n2, "contains")(other);
13710 }
13711 function getRootNode(n2) {
13712 return getUntaintedMethod("Node", n2, "getRootNode")();
13713 }
13714 function host(n2) {
13715 if (!n2 || !("host" in n2)) return null;
13716 return getUntaintedAccessor("ShadowRoot", n2, "host");
13717 }
13718 function styleSheets(n2) {
13719 return n2.styleSheets;
13720 }
13721 function shadowRoot(n2) {
13722 if (!n2 || !("shadowRoot" in n2)) return null;
13723 return getUntaintedAccessor("Element", n2, "shadowRoot");
13724 }
13725 function querySelector(n2, selectors) {
13726 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
13727 }
13728 function querySelectorAll(n2, selectors) {
13729 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
13730 }
13731 function mutationObserverCtor() {
13732 return getUntaintedPrototype("MutationObserver").constructor;
13733 }
13734 function patch(source, name, replacement) {
13735 try {
13736 if (!(name in source)) return function() {};
13737 var original = source[name];
13738 var wrapped = replacement(original);
13739 if (typeof wrapped === "function") {
13740 wrapped.prototype = wrapped.prototype || {};
13741 Object.defineProperties(wrapped, { __rrweb_original__: {
13742 enumerable: false,
13743 value: original
13744 } });
13745 }
13746 source[name] = wrapped;
13747 return function() {
13748 source[name] = original;
13749 };
13750 } catch (e) {
13751 return function() {};
13752 }
13753 }
13754 var index = {
13755 childNodes,
13756 parentNode,
13757 parentElement,
13758 textContent,
13759 contains,
13760 getRootNode,
13761 host,
13762 styleSheets,
13763 shadowRoot,
13764 querySelector,
13765 querySelectorAll,
13766 mutationObserver: mutationObserverCtor,
13767 patch
13768 };
13769 function on(type, fn, target) {
13770 if (target === void 0) target = document;
13771 var options = {
13772 capture: true,
13773 passive: true
13774 };
13775 target.addEventListener(type, fn, options);
13776 return function() {
13777 return target.removeEventListener(type, fn, options);
13778 };
13779 }
13780 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.";
13781 var _mirror = {
13782 map: {},
13783 getId: function getId() {
13784 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13785 return -1;
13786 },
13787 getNode: function getNode() {
13788 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13789 return null;
13790 },
13791 removeNodeFromMap: function removeNodeFromMap() {
13792 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13793 },
13794 has: function has() {
13795 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13796 return false;
13797 },
13798 reset: function reset() {
13799 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13800 }
13801 };
13802 if (typeof window !== "undefined" && window.Proxy && window.Reflect) _mirror = new Proxy(_mirror, { get: function get(target, prop, receiver) {
13803 if (prop === "map") console.error(DEPARTED_MIRROR_ACCESS_WARNING);
13804 return Reflect.get(target, prop, receiver);
13805 } });
13806 function throttle(func, wait, options) {
13807 if (options === void 0) options = {};
13808 var timeout = null;
13809 var previous = 0;
13810 return function() {
13811 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
13812 var now = Date.now();
13813 if (!previous && options.leading === false) previous = now;
13814 var remaining = wait - (now - previous);
13815 var context = this;
13816 if (remaining <= 0 || remaining > wait) {
13817 if (timeout) {
13818 clearTimeout(timeout);
13819 timeout = null;
13820 }
13821 previous = now;
13822 func.apply(context, args);
13823 } else if (!timeout && options.trailing !== false) timeout = setTimeout(function() {
13824 previous = options.leading === false ? 0 : Date.now();
13825 timeout = null;
13826 func.apply(context, args);
13827 }, remaining);
13828 };
13829 }
13830 function hookSetter(target, key, d, isRevoked, win) {
13831 if (win === void 0) win = window;
13832 var original = win.Object.getOwnPropertyDescriptor(target, key);
13833 win.Object.defineProperty(target, key, isRevoked ? d : { set: function set(value) {
13834 var _this = this;
13835 setTimeout(function() {
13836 d.set.call(_this, value);
13837 }, 0);
13838 if (original && original.set) original.set.call(this, value);
13839 } });
13840 return function() {
13841 return hookSetter(target, key, original || {}, true);
13842 };
13843 }
13844 var nowTimestamp = Date.now;
13845 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) nowTimestamp = function() {
13846 return /* @__PURE__ */ (/* @__PURE__ */ new Date()).getTime();
13847 };
13848 function getWindowScroll(win) {
13849 var _a2;
13850 var _b;
13851 var _c;
13852 var _d;
13853 var doc = win.document;
13854 return {
13855 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,
13856 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
13857 };
13858 }
13859 function getWindowHeight() {
13860 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
13861 }
13862 function getWindowWidth() {
13863 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
13864 }
13865 function closestElementOfNode(node2) {
13866 if (!node2) return null;
13867 return node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
13868 }
13869 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
13870 if (!node2) return false;
13871 var el = closestElementOfNode(node2);
13872 if (!el) return false;
13873 try {
13874 if (typeof blockClass === "string") {
13875 if (el.classList.contains(blockClass)) return true;
13876 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
13877 } else if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
13878 } catch (e2) {}
13879 if (blockSelector) {
13880 if (el.matches(blockSelector)) return true;
13881 if (checkAncestors && el.closest(blockSelector) !== null) return true;
13882 }
13883 return false;
13884 }
13885 function isSerialized(n2, mirror2) {
13886 return mirror2.getId(n2) !== -1;
13887 }
13888 function isIgnored(n2, mirror2, slimDOMOptions) {
13889 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) return true;
13890 return mirror2.getId(n2) === IGNORED_NODE;
13891 }
13892 function isAncestorRemoved(target, mirror2) {
13893 if (isShadowRoot(target)) return false;
13894 var id = mirror2.getId(target);
13895 if (!mirror2.has(id)) return true;
13896 var parent = index.parentNode(target);
13897 if (parent && parent.nodeType === target.DOCUMENT_NODE) return false;
13898 if (!parent) return true;
13899 return isAncestorRemoved(parent, mirror2);
13900 }
13901 function legacy_isTouchEvent(event) {
13902 return Boolean(event.changedTouches);
13903 }
13904 function polyfill$1(win) {
13905 if (win === void 0) win = window;
13906 if ("NodeList" in win && !win.NodeList.prototype.forEach) win.NodeList.prototype.forEach = Array.prototype.forEach;
13907 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
13908 }
13909 function isSerializedIframe(n2, mirror2) {
13910 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
13911 }
13912 function isSerializedStylesheet(n2, mirror2) {
13913 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
13914 }
13915 function hasShadowRoot(n2) {
13916 if (!n2) return false;
13917 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) return Boolean(n2.shadowRoot);
13918 return Boolean(index.shadowRoot(n2));
13919 }
13920 var StyleSheetMirror = /*#__PURE__*/ function() {
13921 function StyleSheetMirror() {
13922 __publicField(this, "id", 1);
13923 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
13924 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
13925 }
13926 var _proto = StyleSheetMirror.prototype;
13927 _proto.getId = function getId(stylesheet) {
13928 var _this_styleIDMap_get;
13929 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
13930 };
13931 _proto.has = function has(stylesheet) {
13932 return this.styleIDMap.has(stylesheet);
13933 };
13934 /**
13935 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
13936 */ _proto.add = function add(stylesheet, id) {
13937 if (this.has(stylesheet)) return this.getId(stylesheet);
13938 var newId;
13939 if (id === void 0) newId = this.id++;
13940 else newId = id;
13941 this.styleIDMap.set(stylesheet, newId);
13942 this.idStyleMap.set(newId, stylesheet);
13943 return newId;
13944 };
13945 _proto.getStyle = function getStyle(id) {
13946 return this.idStyleMap.get(id) || null;
13947 };
13948 _proto.reset = function reset() {
13949 this.styleIDMap = /* @__PURE__ */ new WeakMap();
13950 this.idStyleMap = /* @__PURE__ */ new Map();
13951 this.id = 1;
13952 };
13953 _proto.generateId = function generateId() {
13954 return this.id++;
13955 };
13956 return StyleSheetMirror;
13957 }();
13958 function getShadowHost(n2) {
13959 var _a2;
13960 var shadowHost = null;
13961 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));
13962 return shadowHost;
13963 }
13964 function getRootShadowHost(n2) {
13965 var rootShadowHost = n2;
13966 var shadowHost;
13967 while (shadowHost = getShadowHost(rootShadowHost)) rootShadowHost = shadowHost;
13968 return rootShadowHost;
13969 }
13970 function shadowHostInDom(n2) {
13971 var doc = n2.ownerDocument;
13972 if (!doc) return false;
13973 var shadowHost = getRootShadowHost(n2);
13974 return index.contains(doc, shadowHost);
13975 }
13976 function inDom(n2) {
13977 var doc = n2.ownerDocument;
13978 if (!doc) return false;
13979 return index.contains(doc, n2) || shadowHostInDom(n2);
13980 }
13981 var EventType = /* @__PURE__ */ function(EventType2) {
13982 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
13983 EventType2[EventType2["Load"] = 1] = "Load";
13984 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
13985 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
13986 EventType2[EventType2["Meta"] = 4] = "Meta";
13987 EventType2[EventType2["Custom"] = 5] = "Custom";
13988 EventType2[EventType2["Plugin"] = 6] = "Plugin";
13989 return EventType2;
13990 }(EventType || {});
13991 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
13992 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
13993 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
13994 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
13995 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
13996 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
13997 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
13998 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
13999 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
14000 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
14001 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
14002 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
14003 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
14004 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
14005 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
14006 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
14007 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
14008 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
14009 return IncrementalSource2;
14010 }(IncrementalSource || {});
14011 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
14012 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
14013 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
14014 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
14015 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
14016 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
14017 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
14018 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
14019 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
14020 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
14021 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
14022 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
14023 return MouseInteractions2;
14024 }(MouseInteractions || {});
14025 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
14026 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
14027 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
14028 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
14029 return PointerTypes2;
14030 }(PointerTypes || {});
14031 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
14032 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
14033 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
14034 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
14035 return CanvasContext2;
14036 }(CanvasContext || {});
14037 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
14038 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
14039 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
14040 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
14041 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
14042 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
14043 return MediaInteractions2;
14044 }(MediaInteractions || {});
14045 var NodeType = /* @__PURE__ */ function(NodeType2) {
14046 NodeType2[NodeType2["Document"] = 0] = "Document";
14047 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
14048 NodeType2[NodeType2["Element"] = 2] = "Element";
14049 NodeType2[NodeType2["Text"] = 3] = "Text";
14050 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
14051 NodeType2[NodeType2["Comment"] = 5] = "Comment";
14052 return NodeType2;
14053 }(NodeType || {});
14054 function isNodeInLinkedList(n2) {
14055 return "__ln" in n2;
14056 }
14057 var DoubleLinkedList = /*#__PURE__*/ function() {
14058 function DoubleLinkedList() {
14059 __publicField(this, "length", 0);
14060 __publicField(this, "head", null);
14061 __publicField(this, "tail", null);
14062 }
14063 var _proto = DoubleLinkedList.prototype;
14064 _proto.get = function get(position) {
14065 if (position >= this.length) throw new Error("Position outside of list range");
14066 var current = this.head;
14067 for (var index2 = 0; index2 < position; index2++) current = (current == null ? void 0 : current.next) || null;
14068 return current;
14069 };
14070 _proto.addNode = function addNode(n2) {
14071 var node2 = {
14072 value: n2,
14073 previous: null,
14074 next: null
14075 };
14076 n2.__ln = node2;
14077 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
14078 var current = n2.previousSibling.__ln.next;
14079 node2.next = current;
14080 node2.previous = n2.previousSibling.__ln;
14081 n2.previousSibling.__ln.next = node2;
14082 if (current) current.previous = node2;
14083 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
14084 var current1 = n2.nextSibling.__ln.previous;
14085 node2.previous = current1;
14086 node2.next = n2.nextSibling.__ln;
14087 n2.nextSibling.__ln.previous = node2;
14088 if (current1) current1.next = node2;
14089 } else {
14090 if (this.head) this.head.previous = node2;
14091 node2.next = this.head;
14092 this.head = node2;
14093 }
14094 if (node2.next === null) this.tail = node2;
14095 this.length++;
14096 };
14097 _proto.removeNode = function removeNode(n2) {
14098 var current = n2.__ln;
14099 if (!this.head) return;
14100 if (!current.previous) {
14101 this.head = current.next;
14102 if (this.head) this.head.previous = null;
14103 else this.tail = null;
14104 } else {
14105 current.previous.next = current.next;
14106 if (current.next) current.next.previous = current.previous;
14107 else this.tail = current.previous;
14108 }
14109 if (n2.__ln) delete n2.__ln;
14110 this.length--;
14111 };
14112 return DoubleLinkedList;
14113 }();
14114 var moveKey = function(id, parentId) {
14115 return id + "@" + parentId;
14116 };
14117 var MutationBuffer = /*#__PURE__*/ function() {
14118 function MutationBuffer() {
14119 var _this = this;
14120 __publicField(this, "frozen", false);
14121 __publicField(this, "locked", false);
14122 __publicField(this, "texts", []);
14123 __publicField(this, "attributes", []);
14124 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
14125 __publicField(this, "removes", []);
14126 __publicField(this, "mapRemoves", []);
14127 __publicField(this, "movedMap", {});
14128 /**
14129 * the browser MutationObserver emits multiple mutations after
14130 * a delay for performance reasons, making tracing added nodes hard
14131 * in our `processMutations` callback function.
14132 * For example, if we append an element el_1 into body, and then append
14133 * another element el_2 into el_1, these two mutations may be passed to the
14134 * callback function together when the two operations were done.
14135 * Generally we need to trace child nodes of newly added nodes, but in this
14136 * case if we count el_2 as el_1's child node in the first mutation record,
14137 * then we will count el_2 again in the second mutation record which was
14138 * duplicated.
14139 * To avoid of duplicate counting added nodes, we use a Set to store
14140 * added nodes and its child nodes during iterate mutation records. Then
14141 * collect added nodes from the Set which have no duplicate copy. But
14142 * this also causes newly added nodes will not be serialized with id ASAP,
14143 * which means all the id related calculation should be lazy too.
14144 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
14145 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
14146 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
14147 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
14148 __publicField(this, "mutationCb");
14149 __publicField(this, "blockClass");
14150 __publicField(this, "blockSelector");
14151 __publicField(this, "maskTextClass");
14152 __publicField(this, "maskTextSelector");
14153 __publicField(this, "inlineStylesheet");
14154 __publicField(this, "maskInputOptions");
14155 __publicField(this, "maskTextFn");
14156 __publicField(this, "maskInputFn");
14157 __publicField(this, "keepIframeSrcFn");
14158 __publicField(this, "recordCanvas");
14159 __publicField(this, "inlineImages");
14160 __publicField(this, "slimDOMOptions");
14161 __publicField(this, "dataURLOptions");
14162 __publicField(this, "doc");
14163 __publicField(this, "mirror");
14164 __publicField(this, "iframeManager");
14165 __publicField(this, "stylesheetManager");
14166 __publicField(this, "shadowDomManager");
14167 __publicField(this, "canvasManager");
14168 __publicField(this, "processedNodeManager");
14169 __publicField(this, "unattachedDoc");
14170 __publicField(this, "processMutations", function(mutations) {
14171 mutations.forEach(_this.processMutation);
14172 _this.emit();
14173 });
14174 __publicField(this, "emit", function() {
14175 if (_this.frozen || _this.locked) return;
14176 var adds = [];
14177 var addedIds = /* @__PURE__ */ new Set();
14178 var addList = new DoubleLinkedList();
14179 var getNextId = function(n2) {
14180 var ns = n2;
14181 var nextId = IGNORED_NODE;
14182 while (nextId === IGNORED_NODE) {
14183 ns = ns && ns.nextSibling;
14184 nextId = ns && _this.mirror.getId(ns);
14185 }
14186 return nextId;
14187 };
14188 var pushAdd = function(n2) {
14189 var parent = index.parentNode(n2);
14190 if (!parent || !inDom(n2)) return;
14191 var cssCaptured = false;
14192 if (n2.nodeType === Node.TEXT_NODE) {
14193 var parentTag = parent.tagName;
14194 if (parentTag === "TEXTAREA") return;
14195 else if (parentTag === "STYLE" && _this.addedSet.has(parent)) cssCaptured = true;
14196 }
14197 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
14198 var nextId = getNextId(n2);
14199 if (parentId === -1 || nextId === -1) return addList.addNode(n2);
14200 var sn = serializeNodeWithId(n2, {
14201 doc: _this.doc,
14202 mirror: _this.mirror,
14203 blockClass: _this.blockClass,
14204 blockSelector: _this.blockSelector,
14205 maskTextClass: _this.maskTextClass,
14206 maskTextSelector: _this.maskTextSelector,
14207 skipChild: true,
14208 newlyAddedElement: true,
14209 inlineStylesheet: _this.inlineStylesheet,
14210 maskInputOptions: _this.maskInputOptions,
14211 maskTextFn: _this.maskTextFn,
14212 maskInputFn: _this.maskInputFn,
14213 slimDOMOptions: _this.slimDOMOptions,
14214 dataURLOptions: _this.dataURLOptions,
14215 recordCanvas: _this.recordCanvas,
14216 inlineImages: _this.inlineImages,
14217 onSerialize: function(currentN) {
14218 if (isSerializedIframe(currentN, _this.mirror)) _this.iframeManager.addIframe(currentN);
14219 if (isSerializedStylesheet(currentN, _this.mirror)) _this.stylesheetManager.trackLinkElement(currentN);
14220 if (hasShadowRoot(n2)) _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
14221 },
14222 onIframeLoad: function(iframe, childSn) {
14223 _this.iframeManager.attachIframe(iframe, childSn);
14224 _this.shadowDomManager.observeAttachShadow(iframe);
14225 },
14226 onStylesheetLoad: function(link, childSn) {
14227 _this.stylesheetManager.attachLinkElement(link, childSn);
14228 },
14229 cssCaptured
14230 });
14231 if (sn) {
14232 adds.push({
14233 parentId,
14234 nextId,
14235 node: sn
14236 });
14237 addedIds.add(sn.id);
14238 }
14239 };
14240 while (_this.mapRemoves.length) _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
14241 for (var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;) {
14242 var n2 = _step.value;
14243 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) continue;
14244 pushAdd(n2);
14245 }
14246 for (var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;) {
14247 var n21 = _step1.value;
14248 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) pushAdd(n21);
14249 else if (isAncestorInSet(_this.movedSet, n21)) pushAdd(n21);
14250 else _this.droppedSet.add(n21);
14251 }
14252 var candidate = null;
14253 while (addList.length) {
14254 var node2 = null;
14255 if (candidate) {
14256 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
14257 var nextId = getNextId(candidate.value);
14258 if (parentId !== -1 && nextId !== -1) node2 = candidate;
14259 }
14260 if (!node2) {
14261 var tailNode = addList.tail;
14262 while (tailNode) {
14263 var _node = tailNode;
14264 tailNode = tailNode.previous;
14265 if (_node) {
14266 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
14267 if (getNextId(_node.value) === -1) continue;
14268 else if (parentId1 !== -1) {
14269 node2 = _node;
14270 break;
14271 } else {
14272 var unhandledNode = _node.value;
14273 var parent = index.parentNode(unhandledNode);
14274 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
14275 var shadowHost = index.host(parent);
14276 if (_this.mirror.getId(shadowHost) !== -1) {
14277 node2 = _node;
14278 break;
14279 }
14280 }
14281 }
14282 }
14283 }
14284 }
14285 if (!node2) {
14286 while (addList.head) addList.removeNode(addList.head.value);
14287 break;
14288 }
14289 candidate = node2.previous;
14290 addList.removeNode(node2.value);
14291 pushAdd(node2.value);
14292 }
14293 var payload = {
14294 texts: _this.texts.map(function(text) {
14295 var n2 = text.node;
14296 var parent = index.parentNode(n2);
14297 if (parent && parent.tagName === "TEXTAREA") _this.genTextAreaValueMutation(parent);
14298 return {
14299 id: _this.mirror.getId(n2),
14300 value: text.value
14301 };
14302 }).filter(function(text) {
14303 return !addedIds.has(text.id);
14304 }).filter(function(text) {
14305 return _this.mirror.has(text.id);
14306 }),
14307 attributes: _this.attributes.map(function(attribute) {
14308 var attributes = attribute.attributes;
14309 if (typeof attributes.style === "string") {
14310 var diffAsStr = JSON.stringify(attribute.styleDiff);
14311 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
14312 if (diffAsStr.length < attributes.style.length) {
14313 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) attributes.style = attribute.styleDiff;
14314 }
14315 }
14316 return {
14317 id: _this.mirror.getId(attribute.node),
14318 attributes
14319 };
14320 }).filter(function(attribute) {
14321 return !addedIds.has(attribute.id);
14322 }).filter(function(attribute) {
14323 return _this.mirror.has(attribute.id);
14324 }),
14325 removes: _this.removes,
14326 adds
14327 };
14328 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) return;
14329 _this.texts = [];
14330 _this.attributes = [];
14331 _this.attributeMap = /* @__PURE__ */ new WeakMap();
14332 _this.removes = [];
14333 _this.addedSet = /* @__PURE__ */ new Set();
14334 _this.movedSet = /* @__PURE__ */ new Set();
14335 _this.droppedSet = /* @__PURE__ */ new Set();
14336 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
14337 _this.movedMap = {};
14338 _this.mutationCb(payload);
14339 });
14340 __publicField(this, "genTextAreaValueMutation", function(textarea) {
14341 var item = _this.attributeMap.get(textarea);
14342 if (!item) {
14343 item = {
14344 node: textarea,
14345 attributes: {},
14346 styleDiff: {},
14347 _unchangedStyles: {}
14348 };
14349 _this.attributes.push(item);
14350 _this.attributeMap.set(textarea, item);
14351 }
14352 var value = Array.from(index.childNodes(textarea), function(cn) {
14353 return index.textContent(cn) || "";
14354 }).join("");
14355 item.attributes.value = maskInputValue({
14356 element: textarea,
14357 maskInputOptions: _this.maskInputOptions,
14358 tagName: textarea.tagName,
14359 type: getInputType(textarea),
14360 value,
14361 maskInputFn: _this.maskInputFn
14362 });
14363 });
14364 __publicField(this, "processMutation", function(m) {
14365 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) return;
14366 switch (m.type) {
14367 case "characterData":
14368 var value = index.textContent(m.target);
14369 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) _this.texts.push({
14370 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
14371 node: m.target
14372 });
14373 break;
14374 case "attributes":
14375 var target = m.target;
14376 var attributeName = m.attributeName;
14377 var value1 = m.target.getAttribute(attributeName);
14378 if (attributeName === "value") {
14379 var type = getInputType(target);
14380 value1 = maskInputValue({
14381 element: target,
14382 maskInputOptions: _this.maskInputOptions,
14383 tagName: target.tagName,
14384 type,
14385 value: value1,
14386 maskInputFn: _this.maskInputFn
14387 });
14388 }
14389 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) return;
14390 var item = _this.attributeMap.get(m.target);
14391 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) if (!target.contentDocument) attributeName = "rr_src";
14392 else return;
14393 if (!item) {
14394 item = {
14395 node: m.target,
14396 attributes: {},
14397 styleDiff: {},
14398 _unchangedStyles: {}
14399 };
14400 _this.attributes.push(item);
14401 _this.attributeMap.set(m.target, item);
14402 }
14403 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") target.setAttribute("data-rr-is-password", "true");
14404 if (!ignoreAttribute(target.tagName, attributeName)) {
14405 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
14406 if (attributeName === "style") {
14407 if (!_this.unattachedDoc) try {
14408 _this.unattachedDoc = document.implementation.createHTMLDocument();
14409 } catch (e2) {
14410 _this.unattachedDoc = _this.doc;
14411 }
14412 var old = _this.unattachedDoc.createElement("span");
14413 if (m.oldValue) old.setAttribute("style", m.oldValue);
14414 for (var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;) {
14415 var pname = _step.value;
14416 var newValue = target.style.getPropertyValue(pname);
14417 var newPriority = target.style.getPropertyPriority(pname);
14418 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) if (newPriority === "") item.styleDiff[pname] = newValue;
14419 else item.styleDiff[pname] = [newValue, newPriority];
14420 else item._unchangedStyles[pname] = [newValue, newPriority];
14421 }
14422 for (var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;) {
14423 var pname1 = _step1.value;
14424 if (target.style.getPropertyValue(pname1) === "") item.styleDiff[pname1] = false;
14425 }
14426 } else if (attributeName === "open" && target.tagName === "DIALOG") if (target.matches("dialog:modal")) item.attributes["rr_open_mode"] = "modal";
14427 else item.attributes["rr_open_mode"] = "non-modal";
14428 }
14429 break;
14430 case "childList":
14431 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
14432 if (m.target.tagName === "TEXTAREA") {
14433 _this.genTextAreaValueMutation(m.target);
14434 return;
14435 }
14436 m.addedNodes.forEach(function(n2) {
14437 return _this.genAdds(n2, m.target);
14438 });
14439 m.removedNodes.forEach(function(n2) {
14440 var nodeId = _this.mirror.getId(n2);
14441 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
14442 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) return;
14443 if (_this.addedSet.has(n2)) {
14444 deepDelete(_this.addedSet, n2);
14445 _this.droppedSet.add(n2);
14446 } else if (_this.addedSet.has(m.target) && nodeId === -1);
14447 else if (isAncestorRemoved(m.target, _this.mirror));
14448 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) deepDelete(_this.movedSet, n2);
14449 else {
14450 _this.removes.push({
14451 parentId,
14452 id: nodeId,
14453 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
14454 });
14455 processRemoves(n2, _this.removesSubTreeCache);
14456 }
14457 _this.mapRemoves.push(n2);
14458 });
14459 break;
14460 }
14461 });
14462 /**
14463 * Make sure you check if `n`'s parent is blocked before calling this function
14464 * */ __publicField(this, "genAdds", function(n2, target) {
14465 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
14466 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
14467 if (_this.mirror.hasNode(n2)) {
14468 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) return;
14469 _this.movedSet.add(n2);
14470 var targetId = null;
14471 if (target && _this.mirror.hasNode(target)) targetId = _this.mirror.getId(target);
14472 if (targetId && targetId !== -1) _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
14473 } else {
14474 _this.addedSet.add(n2);
14475 _this.droppedSet.delete(n2);
14476 }
14477 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
14478 index.childNodes(n2).forEach(function(childN) {
14479 return _this.genAdds(childN);
14480 });
14481 if (hasShadowRoot(n2)) index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
14482 _this.processedNodeManager.add(childN, _this);
14483 _this.genAdds(childN, n2);
14484 });
14485 }
14486 });
14487 }
14488 var _proto = MutationBuffer.prototype;
14489 _proto.init = function init(options) {
14490 var _this = this;
14491 [
14492 "mutationCb",
14493 "blockClass",
14494 "blockSelector",
14495 "maskTextClass",
14496 "maskTextSelector",
14497 "inlineStylesheet",
14498 "maskInputOptions",
14499 "maskTextFn",
14500 "maskInputFn",
14501 "keepIframeSrcFn",
14502 "recordCanvas",
14503 "inlineImages",
14504 "slimDOMOptions",
14505 "dataURLOptions",
14506 "doc",
14507 "mirror",
14508 "iframeManager",
14509 "stylesheetManager",
14510 "shadowDomManager",
14511 "canvasManager",
14512 "processedNodeManager"
14513 ].forEach(function(key) {
14514 _this[key] = options[key];
14515 });
14516 };
14517 _proto.freeze = function freeze() {
14518 this.frozen = true;
14519 this.canvasManager.freeze();
14520 };
14521 _proto.unfreeze = function unfreeze() {
14522 this.frozen = false;
14523 this.canvasManager.unfreeze();
14524 this.emit();
14525 };
14526 _proto.isFrozen = function isFrozen() {
14527 return this.frozen;
14528 };
14529 _proto.lock = function lock() {
14530 this.locked = true;
14531 this.canvasManager.lock();
14532 };
14533 _proto.unlock = function unlock() {
14534 this.locked = false;
14535 this.canvasManager.unlock();
14536 this.emit();
14537 };
14538 _proto.reset = function reset() {
14539 this.shadowDomManager.reset();
14540 this.canvasManager.reset();
14541 };
14542 return MutationBuffer;
14543 }();
14544 function deepDelete(addsSet, n2) {
14545 addsSet.delete(n2);
14546 index.childNodes(n2).forEach(function(childN) {
14547 return deepDelete(addsSet, childN);
14548 });
14549 }
14550 function processRemoves(n2, cache) {
14551 var queue = [n2];
14552 while (queue.length) {
14553 var next = queue.pop();
14554 if (cache.has(next)) continue;
14555 cache.add(next);
14556 index.childNodes(next).forEach(function(n22) {
14557 return queue.push(n22);
14558 });
14559 }
14560 }
14561 function isParentRemoved(removes, n2, mirror2) {
14562 if (removes.size === 0) return false;
14563 return _isParentRemoved(removes, n2);
14564 }
14565 function _isParentRemoved(removes, n2, _mirror2) {
14566 var node2 = index.parentNode(n2);
14567 if (!node2) return false;
14568 return removes.has(node2);
14569 }
14570 function isAncestorInSet(set, n2) {
14571 if (set.size === 0) return false;
14572 return _isAncestorInSet(set, n2);
14573 }
14574 function _isAncestorInSet(set, n2) {
14575 var parent = index.parentNode(n2);
14576 if (!parent) return false;
14577 if (set.has(parent)) return true;
14578 return _isAncestorInSet(set, parent);
14579 }
14580 var errorHandler;
14581 function registerErrorHandler(handler) {
14582 errorHandler = handler;
14583 }
14584 function unregisterErrorHandler() {
14585 errorHandler = void 0;
14586 }
14587 var callbackWrapper = function(cb) {
14588 if (!errorHandler) return cb;
14589 var rrwebWrapped = function() {
14590 for (var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++) rest[_key] = arguments[_key];
14591 try {
14592 return cb.apply(void 0, [].concat(rest));
14593 } catch (error) {
14594 if (errorHandler && errorHandler(error) === true) return;
14595 throw error;
14596 }
14597 };
14598 return rrwebWrapped;
14599 };
14600 var mutationBuffers = [];
14601 function getEventTarget(event) {
14602 try {
14603 if ("composedPath" in event) {
14604 var path = event.composedPath();
14605 if (path.length) return path[0];
14606 } else if ("path" in event && event.path.length) return event.path[0];
14607 } catch (e) {}
14608 return event && event.target;
14609 }
14610 function initMutationObserver(options, rootEl) {
14611 var mutationBuffer = new MutationBuffer();
14612 mutationBuffers.push(mutationBuffer);
14613 mutationBuffer.init(options);
14614 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
14615 observer.observe(rootEl, {
14616 attributes: true,
14617 attributeOldValue: true,
14618 characterData: true,
14619 characterDataOldValue: true,
14620 childList: true,
14621 subtree: true
14622 });
14623 return observer;
14624 }
14625 function initMoveObserver(param) {
14626 var mousemoveCb = param.mousemoveCb;
14627 var sampling = param.sampling;
14628 var doc = param.doc;
14629 var mirror2 = param.mirror;
14630 if (sampling.mousemove === false) return function() {};
14631 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
14632 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
14633 var positions = [];
14634 var timeBaseline;
14635 var wrappedCb = throttle(callbackWrapper(function(source) {
14636 var totalOffset = Date.now() - timeBaseline;
14637 mousemoveCb(positions.map(function(p) {
14638 p.timeOffset -= totalOffset;
14639 return p;
14640 }), source);
14641 positions = [];
14642 timeBaseline = null;
14643 }), callbackThreshold);
14644 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
14645 var target = getEventTarget(evt);
14646 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;
14647 var clientX = _ref.clientX;
14648 var clientY = _ref.clientY;
14649 if (!timeBaseline) timeBaseline = nowTimestamp();
14650 positions.push({
14651 x: clientX,
14652 y: clientY,
14653 id: mirror2.getId(target),
14654 timeOffset: nowTimestamp() - timeBaseline
14655 });
14656 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
14657 }), threshold, { trailing: false }));
14658 var handlers = [
14659 on("mousemove", updatePosition, doc),
14660 on("touchmove", updatePosition, doc),
14661 on("drag", updatePosition, doc)
14662 ];
14663 return callbackWrapper(function() {
14664 handlers.forEach(function(h) {
14665 return h();
14666 });
14667 });
14668 }
14669 function initMouseInteractionObserver(param) {
14670 var mouseInteractionCb = param.mouseInteractionCb;
14671 var doc = param.doc;
14672 var mirror2 = param.mirror;
14673 var blockClass = param.blockClass;
14674 var blockSelector = param.blockSelector;
14675 var sampling = param.sampling;
14676 if (sampling.mouseInteraction === false) return function() {};
14677 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
14678 var handlers = [];
14679 var currentPointerType = null;
14680 var getHandler = function(eventKey) {
14681 return function(event) {
14682 var target = getEventTarget(event);
14683 if (isBlocked(target, blockClass, blockSelector, true)) return;
14684 var pointerType = null;
14685 var thisEventKey = eventKey;
14686 if ("pointerType" in event) {
14687 switch (event.pointerType) {
14688 case "mouse":
14689 pointerType = PointerTypes.Mouse;
14690 break;
14691 case "touch":
14692 pointerType = PointerTypes.Touch;
14693 break;
14694 case "pen":
14695 pointerType = PointerTypes.Pen;
14696 break;
14697 }
14698 if (pointerType === PointerTypes.Touch) {
14699 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) thisEventKey = "TouchStart";
14700 else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) thisEventKey = "TouchEnd";
14701 } else if (pointerType === PointerTypes.Pen);
14702 } else if (legacy_isTouchEvent(event)) pointerType = PointerTypes.Touch;
14703 if (pointerType !== null) {
14704 currentPointerType = pointerType;
14705 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) pointerType = null;
14706 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
14707 pointerType = currentPointerType;
14708 currentPointerType = null;
14709 }
14710 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
14711 if (!e2) return;
14712 var id = mirror2.getId(target);
14713 var clientX = e2.clientX;
14714 var clientY = e2.clientY;
14715 callbackWrapper(mouseInteractionCb)(_extends({
14716 type: MouseInteractions[thisEventKey],
14717 id,
14718 x: clientX,
14719 y: clientY
14720 }, pointerType !== null && { pointerType }));
14721 };
14722 };
14723 Object.keys(MouseInteractions).filter(function(key) {
14724 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
14725 }).forEach(function(eventKey) {
14726 var eventName = toLowerCase(eventKey);
14727 var handler = getHandler(eventKey);
14728 if (window.PointerEvent) switch (MouseInteractions[eventKey]) {
14729 case MouseInteractions.MouseDown:
14730 case MouseInteractions.MouseUp:
14731 eventName = eventName.replace("mouse", "pointer");
14732 break;
14733 case MouseInteractions.TouchStart:
14734 case MouseInteractions.TouchEnd: return;
14735 }
14736 handlers.push(on(eventName, handler, doc));
14737 });
14738 return callbackWrapper(function() {
14739 handlers.forEach(function(h) {
14740 return h();
14741 });
14742 });
14743 }
14744 function initScrollObserver(param) {
14745 var scrollCb = param.scrollCb;
14746 var doc = param.doc;
14747 var mirror2 = param.mirror;
14748 var blockClass = param.blockClass;
14749 var blockSelector = param.blockSelector;
14750 var sampling = param.sampling;
14751 return on("scroll", callbackWrapper(throttle(callbackWrapper(function(evt) {
14752 var target = getEventTarget(evt);
14753 if (!target || isBlocked(target, blockClass, blockSelector, true)) return;
14754 var id = mirror2.getId(target);
14755 if (target === doc && doc.defaultView) {
14756 var scrollLeftTop = getWindowScroll(doc.defaultView);
14757 scrollCb({
14758 id,
14759 x: scrollLeftTop.left,
14760 y: scrollLeftTop.top
14761 });
14762 } else scrollCb({
14763 id,
14764 x: target.scrollLeft,
14765 y: target.scrollTop
14766 });
14767 }), sampling.scroll || 100)), doc);
14768 }
14769 function initViewportResizeObserver(param, param1) {
14770 var viewportResizeCb = param.viewportResizeCb;
14771 var win = param1.win;
14772 var lastH = -1;
14773 var lastW = -1;
14774 return on("resize", callbackWrapper(throttle(callbackWrapper(function() {
14775 var height = getWindowHeight();
14776 var width = getWindowWidth();
14777 if (lastH !== height || lastW !== width) {
14778 viewportResizeCb({
14779 width: Number(width),
14780 height: Number(height)
14781 });
14782 lastH = height;
14783 lastW = width;
14784 }
14785 }), 200)), win);
14786 }
14787 var INPUT_TAGS = [
14788 "INPUT",
14789 "TEXTAREA",
14790 "SELECT"
14791 ];
14792 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
14793 function initInputObserver(param) {
14794 var inputCb = param.inputCb;
14795 var doc = param.doc;
14796 var mirror2 = param.mirror;
14797 var blockClass = param.blockClass;
14798 var blockSelector = param.blockSelector;
14799 var ignoreClass = param.ignoreClass;
14800 var ignoreSelector = param.ignoreSelector;
14801 var maskInputOptions = param.maskInputOptions;
14802 var maskInputFn = param.maskInputFn;
14803 var sampling = param.sampling;
14804 var userTriggeredOnInput = param.userTriggeredOnInput;
14805 function eventHandler(event) {
14806 var target = getEventTarget(event);
14807 var userTriggered = event.isTrusted;
14808 var tagName = target && target.tagName;
14809 if (target && tagName === "OPTION") target = index.parentElement(target);
14810 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) return;
14811 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) return;
14812 var text = target.value;
14813 var isChecked = false;
14814 var type = getInputType(target) || "";
14815 if (type === "radio" || type === "checkbox") isChecked = target.checked;
14816 else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) text = maskInputValue({
14817 element: target,
14818 maskInputOptions,
14819 tagName,
14820 type,
14821 value: text,
14822 maskInputFn
14823 });
14824 cbWithDedup(target, userTriggeredOnInput ? {
14825 text,
14826 isChecked,
14827 userTriggered
14828 } : {
14829 text,
14830 isChecked
14831 });
14832 var name = target.name;
14833 if (type === "radio" && name && isChecked) doc.querySelectorAll("input[type=\"radio\"][name=\"" + name + "\"]").forEach(function(el) {
14834 if (el !== target) {
14835 var text2 = el.value;
14836 cbWithDedup(el, userTriggeredOnInput ? {
14837 text: text2,
14838 isChecked: !isChecked,
14839 userTriggered: false
14840 } : {
14841 text: text2,
14842 isChecked: !isChecked
14843 });
14844 }
14845 });
14846 }
14847 function cbWithDedup(target, v2) {
14848 var lastInputValue = lastInputValueMap.get(target);
14849 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
14850 lastInputValueMap.set(target, v2);
14851 var id = mirror2.getId(target);
14852 callbackWrapper(inputCb)(_extends({}, v2, { id }));
14853 }
14854 }
14855 var handlers = (sampling.input === "last" ? ["change"] : ["input", "change"]).map(function(eventName) {
14856 return on(eventName, callbackWrapper(eventHandler), doc);
14857 });
14858 var currentWindow = doc.defaultView;
14859 if (!currentWindow) return function() {
14860 handlers.forEach(function(h) {
14861 return h();
14862 });
14863 };
14864 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
14865 var hookProperties = [
14866 [currentWindow.HTMLInputElement.prototype, "value"],
14867 [currentWindow.HTMLInputElement.prototype, "checked"],
14868 [currentWindow.HTMLSelectElement.prototype, "value"],
14869 [currentWindow.HTMLTextAreaElement.prototype, "value"],
14870 [currentWindow.HTMLSelectElement.prototype, "selectedIndex"],
14871 [currentWindow.HTMLOptionElement.prototype, "selected"]
14872 ];
14873 if (propertyDescriptor && propertyDescriptor.set) {
14874 var _handlers;
14875 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
14876 return hookSetter(p[0], p[1], { set: function set() {
14877 callbackWrapper(eventHandler)({
14878 target: this,
14879 isTrusted: false
14880 });
14881 } }, false, currentWindow);
14882 })));
14883 }
14884 return callbackWrapper(function() {
14885 handlers.forEach(function(h) {
14886 return h();
14887 });
14888 });
14889 }
14890 function getNestedCSSRulePositions(rule2) {
14891 var positions = [];
14892 function recurse(childRule, pos) {
14893 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)) {
14894 var index2 = Array.from(childRule.parentRule.cssRules).indexOf(childRule);
14895 pos.unshift(index2);
14896 } else if (childRule.parentStyleSheet) {
14897 var index21 = Array.from(childRule.parentStyleSheet.cssRules).indexOf(childRule);
14898 pos.unshift(index21);
14899 }
14900 return pos;
14901 }
14902 return recurse(rule2, positions);
14903 }
14904 function getIdAndStyleId(sheet, mirror2, styleMirror) {
14905 var id;
14906 var styleId;
14907 if (!sheet) return {};
14908 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
14909 else styleId = styleMirror.getId(sheet);
14910 return {
14911 styleId,
14912 id
14913 };
14914 }
14915 function initStyleSheetObserver(param, param1) {
14916 var styleSheetRuleCb = param.styleSheetRuleCb;
14917 var mirror2 = param.mirror;
14918 var stylesheetManager = param.stylesheetManager;
14919 var win = param1.win;
14920 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) return function() {};
14921 var insertRule = win.CSSStyleSheet.prototype.insertRule;
14922 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
14923 var rule2 = argumentsList[0];
14924 var index2 = argumentsList[1];
14925 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
14926 var id = _getIdAndStyleId.id;
14927 var styleId = _getIdAndStyleId.styleId;
14928 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
14929 id,
14930 styleId,
14931 adds: [{
14932 rule: rule2,
14933 index: index2
14934 }]
14935 });
14936 return target.apply(thisArg, argumentsList);
14937 }) });
14938 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
14939 if (index2 === void 0) index2 = this.cssRules.length;
14940 var rule2 = selector + " { " + styleBlock + " }";
14941 return win.CSSStyleSheet.prototype.insertRule.apply(this, [rule2, index2]);
14942 };
14943 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
14944 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
14945 var index2 = argumentsList[0];
14946 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
14947 var id = _getIdAndStyleId.id;
14948 var styleId = _getIdAndStyleId.styleId;
14949 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
14950 id,
14951 styleId,
14952 removes: [{ index: index2 }]
14953 });
14954 return target.apply(thisArg, argumentsList);
14955 }) });
14956 win.CSSStyleSheet.prototype.removeRule = function(index2) {
14957 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [index2]);
14958 };
14959 var replace;
14960 if (win.CSSStyleSheet.prototype.replace) {
14961 replace = win.CSSStyleSheet.prototype.replace;
14962 win.CSSStyleSheet.prototype.replace = new Proxy(replace, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
14963 var text = argumentsList[0];
14964 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
14965 var id = _getIdAndStyleId.id;
14966 var styleId = _getIdAndStyleId.styleId;
14967 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
14968 id,
14969 styleId,
14970 replace: text
14971 });
14972 return target.apply(thisArg, argumentsList);
14973 }) });
14974 }
14975 var replaceSync;
14976 if (win.CSSStyleSheet.prototype.replaceSync) {
14977 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
14978 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
14979 var text = argumentsList[0];
14980 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror);
14981 var id = _getIdAndStyleId.id;
14982 var styleId = _getIdAndStyleId.styleId;
14983 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
14984 id,
14985 styleId,
14986 replaceSync: text
14987 });
14988 return target.apply(thisArg, argumentsList);
14989 }) });
14990 }
14991 var supportedNestedCSSRuleTypes = {};
14992 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
14993 else {
14994 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
14995 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
14996 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
14997 }
14998 var unmodifiedFunctions = {};
14999 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
15000 var typeKey = param[0];
15001 var type = param[1];
15002 unmodifiedFunctions[typeKey] = {
15003 insertRule: type.prototype.insertRule,
15004 deleteRule: type.prototype.deleteRule
15005 };
15006 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15007 var rule2 = argumentsList[0];
15008 var index2 = argumentsList[1];
15009 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15010 var id = _getIdAndStyleId.id;
15011 var styleId = _getIdAndStyleId.styleId;
15012 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15013 id,
15014 styleId,
15015 adds: [{
15016 rule: rule2,
15017 index: [].concat(getNestedCSSRulePositions(thisArg), [index2 || 0])
15018 }]
15019 });
15020 return target.apply(thisArg, argumentsList);
15021 }) });
15022 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15023 var index2 = argumentsList[0];
15024 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15025 var id = _getIdAndStyleId.id;
15026 var styleId = _getIdAndStyleId.styleId;
15027 if (id && id !== -1 || styleId && styleId !== -1) styleSheetRuleCb({
15028 id,
15029 styleId,
15030 removes: [{ index: [].concat(getNestedCSSRulePositions(thisArg), [index2]) }]
15031 });
15032 return target.apply(thisArg, argumentsList);
15033 }) });
15034 });
15035 return callbackWrapper(function() {
15036 win.CSSStyleSheet.prototype.insertRule = insertRule;
15037 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
15038 replace && (win.CSSStyleSheet.prototype.replace = replace);
15039 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
15040 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
15041 var typeKey = param[0];
15042 var type = param[1];
15043 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
15044 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
15045 });
15046 });
15047 }
15048 function initAdoptedStyleSheetObserver(param, host2) {
15049 var mirror2 = param.mirror;
15050 var stylesheetManager = param.stylesheetManager;
15051 var _a2;
15052 var _b;
15053 var _c;
15054 var hostId = null;
15055 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
15056 else hostId = mirror2.getId(index.host(host2));
15057 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;
15058 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
15059 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
15060 Object.defineProperty(host2, "adoptedStyleSheets", {
15061 configurable: originalPropertyDescriptor.configurable,
15062 enumerable: originalPropertyDescriptor.enumerable,
15063 get: function get() {
15064 var _a3;
15065 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
15066 },
15067 set: function set(sheets) {
15068 var _a3;
15069 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
15070 if (hostId !== null && hostId !== -1) try {
15071 stylesheetManager.adoptStyleSheets(sheets, hostId);
15072 } catch (e2) {}
15073 return result2;
15074 }
15075 });
15076 return callbackWrapper(function() {
15077 Object.defineProperty(host2, "adoptedStyleSheets", {
15078 configurable: originalPropertyDescriptor.configurable,
15079 enumerable: originalPropertyDescriptor.enumerable,
15080 get: originalPropertyDescriptor.get,
15081 set: originalPropertyDescriptor.set
15082 });
15083 });
15084 }
15085 function initStyleDeclarationObserver(param, param1) {
15086 var styleDeclarationCb = param.styleDeclarationCb;
15087 var mirror2 = param.mirror;
15088 var ignoreCSSAttributes = param.ignoreCSSAttributes;
15089 var stylesheetManager = param.stylesheetManager;
15090 var win = param1.win;
15091 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
15092 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15093 var _a2;
15094 var property = argumentsList[0];
15095 var value = argumentsList[1];
15096 var priority = argumentsList[2];
15097 if (ignoreCSSAttributes.has(property)) return setProperty.apply(thisArg, [
15098 property,
15099 value,
15100 priority
15101 ]);
15102 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15103 var id = _getIdAndStyleId.id;
15104 var styleId = _getIdAndStyleId.styleId;
15105 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({
15106 id,
15107 styleId,
15108 set: {
15109 property,
15110 value,
15111 priority
15112 },
15113 index: getNestedCSSRulePositions(thisArg.parentRule)
15114 });
15115 return target.apply(thisArg, argumentsList);
15116 }) });
15117 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
15118 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, { apply: callbackWrapper(function(target, thisArg, argumentsList) {
15119 var _a2;
15120 var property = argumentsList[0];
15121 if (ignoreCSSAttributes.has(property)) return removeProperty.apply(thisArg, [property]);
15122 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror);
15123 var id = _getIdAndStyleId.id;
15124 var styleId = _getIdAndStyleId.styleId;
15125 if (id && id !== -1 || styleId && styleId !== -1) styleDeclarationCb({
15126 id,
15127 styleId,
15128 remove: { property },
15129 index: getNestedCSSRulePositions(thisArg.parentRule)
15130 });
15131 return target.apply(thisArg, argumentsList);
15132 }) });
15133 return callbackWrapper(function() {
15134 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
15135 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
15136 });
15137 }
15138 function initMediaInteractionObserver(param) {
15139 var mediaInteractionCb = param.mediaInteractionCb;
15140 var blockClass = param.blockClass;
15141 var blockSelector = param.blockSelector;
15142 var mirror2 = param.mirror;
15143 var sampling = param.sampling;
15144 var doc = param.doc;
15145 var handler = callbackWrapper(function(type) {
15146 return throttle(callbackWrapper(function(event) {
15147 var target = getEventTarget(event);
15148 if (!target || isBlocked(target, blockClass, blockSelector, true)) return;
15149 var currentTime = target.currentTime;
15150 var volume = target.volume;
15151 var muted = target.muted;
15152 var playbackRate = target.playbackRate;
15153 var loop = target.loop;
15154 mediaInteractionCb({
15155 type,
15156 id: mirror2.getId(target),
15157 currentTime,
15158 volume,
15159 muted,
15160 playbackRate,
15161 loop
15162 });
15163 }), sampling.media || 500);
15164 });
15165 var handlers = [
15166 on("play", handler(MediaInteractions.Play), doc),
15167 on("pause", handler(MediaInteractions.Pause), doc),
15168 on("seeked", handler(MediaInteractions.Seeked), doc),
15169 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
15170 on("ratechange", handler(MediaInteractions.RateChange), doc)
15171 ];
15172 return callbackWrapper(function() {
15173 handlers.forEach(function(h) {
15174 return h();
15175 });
15176 });
15177 }
15178 function initFontObserver(param) {
15179 var fontCb = param.fontCb;
15180 var doc = param.doc;
15181 var win = doc.defaultView;
15182 if (!win) return function() {};
15183 var handlers = [];
15184 var fontMap = /* @__PURE__ */ new WeakMap();
15185 var originalFontFace = win.FontFace;
15186 win.FontFace = function FontFace2(family, source, descriptors) {
15187 var fontFace = new originalFontFace(family, source, descriptors);
15188 fontMap.set(fontFace, {
15189 family,
15190 buffer: typeof source !== "string",
15191 descriptors,
15192 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
15193 });
15194 return fontFace;
15195 };
15196 var restoreHandler = patch(doc.fonts, "add", function(original) {
15197 return function(fontFace) {
15198 setTimeout(callbackWrapper(function() {
15199 var p = fontMap.get(fontFace);
15200 if (p) {
15201 fontCb(p);
15202 fontMap.delete(fontFace);
15203 }
15204 }), 0);
15205 return original.apply(this, [fontFace]);
15206 };
15207 });
15208 handlers.push(function() {
15209 win.FontFace = originalFontFace;
15210 });
15211 handlers.push(restoreHandler);
15212 return callbackWrapper(function() {
15213 handlers.forEach(function(h) {
15214 return h();
15215 });
15216 });
15217 }
15218 function initSelectionObserver(param) {
15219 var doc = param.doc;
15220 var mirror2 = param.mirror;
15221 var blockClass = param.blockClass;
15222 var blockSelector = param.blockSelector;
15223 var selectionCb = param.selectionCb;
15224 var collapsed = true;
15225 var updateSelection = callbackWrapper(function() {
15226 var selection = doc.getSelection();
15227 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
15228 collapsed = selection.isCollapsed || false;
15229 var ranges = [];
15230 var count = selection.rangeCount || 0;
15231 for (var i2 = 0; i2 < count; i2++) {
15232 var range = selection.getRangeAt(i2);
15233 var startContainer = range.startContainer;
15234 var startOffset = range.startOffset;
15235 var endContainer = range.endContainer;
15236 var endOffset = range.endOffset;
15237 if (isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true)) continue;
15238 ranges.push({
15239 start: mirror2.getId(startContainer),
15240 startOffset,
15241 end: mirror2.getId(endContainer),
15242 endOffset
15243 });
15244 }
15245 selectionCb({ ranges });
15246 });
15247 updateSelection();
15248 return on("selectionchange", updateSelection);
15249 }
15250 function initCustomElementObserver(param) {
15251 var doc = param.doc;
15252 var customElementCb = param.customElementCb;
15253 var win = doc.defaultView;
15254 if (!win || !win.customElements) return function() {};
15255 return patch(win.customElements, "define", function(original) {
15256 return function(name, constructor, options) {
15257 try {
15258 customElementCb({ define: { name } });
15259 } catch (e2) {
15260 console.warn("Custom element callback failed for " + name);
15261 }
15262 return original.apply(this, [
15263 name,
15264 constructor,
15265 options
15266 ]);
15267 };
15268 });
15269 }
15270 function mergeHooks(o2, hooks) {
15271 var mutationCb = o2.mutationCb;
15272 var mousemoveCb = o2.mousemoveCb;
15273 var mouseInteractionCb = o2.mouseInteractionCb;
15274 var scrollCb = o2.scrollCb;
15275 var viewportResizeCb = o2.viewportResizeCb;
15276 var inputCb = o2.inputCb;
15277 var mediaInteractionCb = o2.mediaInteractionCb;
15278 var styleSheetRuleCb = o2.styleSheetRuleCb;
15279 var styleDeclarationCb = o2.styleDeclarationCb;
15280 var canvasMutationCb = o2.canvasMutationCb;
15281 var fontCb = o2.fontCb;
15282 var selectionCb = o2.selectionCb;
15283 var customElementCb = o2.customElementCb;
15284 o2.mutationCb = function() {
15285 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15286 if (hooks.mutation) {
15287 var _hooks;
15288 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
15289 }
15290 mutationCb.apply(void 0, [].concat(p));
15291 };
15292 o2.mousemoveCb = function() {
15293 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15294 if (hooks.mousemove) {
15295 var _hooks;
15296 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
15297 }
15298 mousemoveCb.apply(void 0, [].concat(p));
15299 };
15300 o2.mouseInteractionCb = function() {
15301 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15302 if (hooks.mouseInteraction) {
15303 var _hooks;
15304 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
15305 }
15306 mouseInteractionCb.apply(void 0, [].concat(p));
15307 };
15308 o2.scrollCb = function() {
15309 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15310 if (hooks.scroll) {
15311 var _hooks;
15312 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
15313 }
15314 scrollCb.apply(void 0, [].concat(p));
15315 };
15316 o2.viewportResizeCb = function() {
15317 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15318 if (hooks.viewportResize) {
15319 var _hooks;
15320 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
15321 }
15322 viewportResizeCb.apply(void 0, [].concat(p));
15323 };
15324 o2.inputCb = function() {
15325 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15326 if (hooks.input) {
15327 var _hooks;
15328 (_hooks = hooks).input.apply(_hooks, [].concat(p));
15329 }
15330 inputCb.apply(void 0, [].concat(p));
15331 };
15332 o2.mediaInteractionCb = function() {
15333 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15334 if (hooks.mediaInteaction) {
15335 var _hooks;
15336 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
15337 }
15338 mediaInteractionCb.apply(void 0, [].concat(p));
15339 };
15340 o2.styleSheetRuleCb = function() {
15341 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15342 if (hooks.styleSheetRule) {
15343 var _hooks;
15344 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
15345 }
15346 styleSheetRuleCb.apply(void 0, [].concat(p));
15347 };
15348 o2.styleDeclarationCb = function() {
15349 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15350 if (hooks.styleDeclaration) {
15351 var _hooks;
15352 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
15353 }
15354 styleDeclarationCb.apply(void 0, [].concat(p));
15355 };
15356 o2.canvasMutationCb = function() {
15357 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15358 if (hooks.canvasMutation) {
15359 var _hooks;
15360 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
15361 }
15362 canvasMutationCb.apply(void 0, [].concat(p));
15363 };
15364 o2.fontCb = function() {
15365 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15366 if (hooks.font) {
15367 var _hooks;
15368 (_hooks = hooks).font.apply(_hooks, [].concat(p));
15369 }
15370 fontCb.apply(void 0, [].concat(p));
15371 };
15372 o2.selectionCb = function() {
15373 for (var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++) p[_key] = arguments[_key];
15374 if (hooks.selection) {
15375 var _hooks;
15376 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
15377 }
15378 selectionCb.apply(void 0, [].concat(p));
15379 };
15380 o2.customElementCb = function() {
15381 for (var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++) c2[_key] = arguments[_key];
15382 if (hooks.customElement) {
15383 var _hooks;
15384 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
15385 }
15386 customElementCb.apply(void 0, [].concat(c2));
15387 };
15388 }
15389 function initObservers(o2, hooks) {
15390 if (hooks === void 0) hooks = {};
15391 var currentWindow = o2.doc.defaultView;
15392 if (!currentWindow) return function() {};
15393 mergeHooks(o2, hooks);
15394 var mutationObserver;
15395 if (o2.recordDOM) mutationObserver = initMutationObserver(o2, o2.doc);
15396 var mousemoveHandler = initMoveObserver(o2);
15397 var mouseInteractionHandler = initMouseInteractionObserver(o2);
15398 var scrollHandler = initScrollObserver(o2);
15399 var viewportResizeHandler = initViewportResizeObserver(o2, { win: currentWindow });
15400 var inputHandler = initInputObserver(o2);
15401 var mediaInteractionHandler = initMediaInteractionObserver(o2);
15402 var styleSheetObserver = function() {};
15403 var adoptedStyleSheetObserver = function() {};
15404 var styleDeclarationObserver = function() {};
15405 var fontObserver = function() {};
15406 if (o2.recordDOM) {
15407 styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow });
15408 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
15409 styleDeclarationObserver = initStyleDeclarationObserver(o2, { win: currentWindow });
15410 if (o2.collectFonts) fontObserver = initFontObserver(o2);
15411 }
15412 var selectionObserver = initSelectionObserver(o2);
15413 var customElementObserver = initCustomElementObserver(o2);
15414 var pluginHandlers = [];
15415 for (var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;) {
15416 var plugin3 = _step.value;
15417 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
15418 }
15419 return callbackWrapper(function() {
15420 mutationBuffers.forEach(function(b) {
15421 return b.reset();
15422 });
15423 mutationObserver == null || mutationObserver.disconnect();
15424 mousemoveHandler();
15425 mouseInteractionHandler();
15426 scrollHandler();
15427 viewportResizeHandler();
15428 inputHandler();
15429 mediaInteractionHandler();
15430 styleSheetObserver();
15431 adoptedStyleSheetObserver();
15432 styleDeclarationObserver();
15433 fontObserver();
15434 selectionObserver();
15435 customElementObserver();
15436 pluginHandlers.forEach(function(h) {
15437 return h();
15438 });
15439 });
15440 }
15441 function hasNestedCSSRule(prop) {
15442 return typeof window[prop] !== "undefined";
15443 }
15444 function canMonkeyPatchNestedCSSRule(prop) {
15445 return Boolean(typeof window[prop] !== "undefined" && window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
15446 }
15447 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
15448 function CrossOriginIframeMirror(generateIdFn) {
15449 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
15450 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
15451 this.generateIdFn = generateIdFn;
15452 }
15453 var _proto = CrossOriginIframeMirror.prototype;
15454 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
15455 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
15456 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
15457 var id = idToRemoteIdMap.get(remoteId);
15458 if (!id) {
15459 id = this.generateIdFn();
15460 idToRemoteIdMap.set(remoteId, id);
15461 remoteIdToIdMap.set(id, remoteId);
15462 }
15463 return id;
15464 };
15465 _proto.getIds = function getIds(iframe, remoteId) {
15466 var _this = this;
15467 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
15468 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
15469 return remoteId.map(function(id) {
15470 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
15471 });
15472 };
15473 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
15474 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
15475 if (typeof id !== "number") return id;
15476 var remoteId = remoteIdToIdMap.get(id);
15477 if (!remoteId) return -1;
15478 return remoteId;
15479 };
15480 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
15481 var _this = this;
15482 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
15483 return ids.map(function(id) {
15484 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
15485 });
15486 };
15487 _proto.reset = function reset(iframe) {
15488 if (!iframe) {
15489 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
15490 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
15491 return;
15492 }
15493 this.iframeIdToRemoteIdMap.delete(iframe);
15494 this.iframeRemoteIdToIdMap.delete(iframe);
15495 };
15496 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
15497 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
15498 if (!idToRemoteIdMap) {
15499 idToRemoteIdMap = /* @__PURE__ */ new Map();
15500 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
15501 }
15502 return idToRemoteIdMap;
15503 };
15504 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
15505 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
15506 if (!remoteIdToIdMap) {
15507 remoteIdToIdMap = /* @__PURE__ */ new Map();
15508 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
15509 }
15510 return remoteIdToIdMap;
15511 };
15512 return CrossOriginIframeMirror;
15513 }();
15514 var IframeManager = /*#__PURE__*/ function() {
15515 function IframeManager(options) {
15516 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
15517 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
15518 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
15519 __publicField(this, "crossOriginIframeStyleMirror");
15520 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
15521 __publicField(this, "mirror");
15522 __publicField(this, "mutationCb");
15523 __publicField(this, "wrappedEmit");
15524 __publicField(this, "loadListener");
15525 __publicField(this, "stylesheetManager");
15526 __publicField(this, "recordCrossOriginIframes");
15527 this.mutationCb = options.mutationCb;
15528 this.wrappedEmit = options.wrappedEmit;
15529 this.stylesheetManager = options.stylesheetManager;
15530 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
15531 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
15532 this.mirror = options.mirror;
15533 if (this.recordCrossOriginIframes) window.addEventListener("message", this.handleMessage.bind(this));
15534 }
15535 var _proto = IframeManager.prototype;
15536 _proto.addIframe = function addIframe(iframeEl) {
15537 this.iframes.set(iframeEl, true);
15538 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
15539 };
15540 _proto.addLoadListener = function addLoadListener(cb) {
15541 this.loadListener = cb;
15542 };
15543 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
15544 var _a2;
15545 var _b;
15546 this.mutationCb({
15547 adds: [{
15548 parentId: this.mirror.getId(iframeEl),
15549 nextId: null,
15550 node: childSn
15551 }],
15552 removes: [],
15553 texts: [],
15554 attributes: [],
15555 isAttachIframe: true
15556 });
15557 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null || _a2.addEventListener("message", this.handleMessage.bind(this));
15558 (_b = this.loadListener) == null || _b.call(this, iframeEl);
15559 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
15560 };
15561 _proto.handleMessage = function handleMessage(message) {
15562 var crossOriginMessageEvent = message;
15563 if (crossOriginMessageEvent.data.type !== "rrweb" || crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
15564 if (!message.source) return;
15565 var iframeEl = this.crossOriginIframeMap.get(message.source);
15566 if (!iframeEl) return;
15567 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
15568 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
15569 };
15570 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
15571 var _this = this;
15572 var _a2;
15573 switch (e2.type) {
15574 case EventType.FullSnapshot:
15575 this.crossOriginIframeMirror.reset(iframeEl);
15576 this.crossOriginIframeStyleMirror.reset(iframeEl);
15577 this.replaceIdOnNode(e2.data.node, iframeEl);
15578 var rootId = e2.data.node.id;
15579 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
15580 this.patchRootIdOnNode(e2.data.node, rootId);
15581 return {
15582 timestamp: e2.timestamp,
15583 type: EventType.IncrementalSnapshot,
15584 data: {
15585 source: IncrementalSource.Mutation,
15586 adds: [{
15587 parentId: this.mirror.getId(iframeEl),
15588 nextId: null,
15589 node: e2.data.node
15590 }],
15591 removes: [],
15592 texts: [],
15593 attributes: [],
15594 isAttachIframe: true
15595 }
15596 };
15597 case EventType.Meta:
15598 case EventType.Load:
15599 case EventType.DomContentLoaded: return false;
15600 case EventType.Plugin: return e2;
15601 case EventType.Custom:
15602 this.replaceIds(e2.data.payload, iframeEl, [
15603 "id",
15604 "parentId",
15605 "previousId",
15606 "nextId"
15607 ]);
15608 return e2;
15609 case EventType.IncrementalSnapshot: switch (e2.data.source) {
15610 case IncrementalSource.Mutation:
15611 e2.data.adds.forEach(function(n2) {
15612 _this.replaceIds(n2, iframeEl, [
15613 "parentId",
15614 "nextId",
15615 "previousId"
15616 ]);
15617 _this.replaceIdOnNode(n2.node, iframeEl);
15618 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
15619 rootId && _this.patchRootIdOnNode(n2.node, rootId);
15620 });
15621 e2.data.removes.forEach(function(n2) {
15622 _this.replaceIds(n2, iframeEl, ["parentId", "id"]);
15623 });
15624 e2.data.attributes.forEach(function(n2) {
15625 _this.replaceIds(n2, iframeEl, ["id"]);
15626 });
15627 e2.data.texts.forEach(function(n2) {
15628 _this.replaceIds(n2, iframeEl, ["id"]);
15629 });
15630 return e2;
15631 case IncrementalSource.Drag:
15632 case IncrementalSource.TouchMove:
15633 case IncrementalSource.MouseMove:
15634 e2.data.positions.forEach(function(p) {
15635 _this.replaceIds(p, iframeEl, ["id"]);
15636 });
15637 return e2;
15638 case IncrementalSource.ViewportResize: return false;
15639 case IncrementalSource.MediaInteraction:
15640 case IncrementalSource.MouseInteraction:
15641 case IncrementalSource.Scroll:
15642 case IncrementalSource.CanvasMutation:
15643 case IncrementalSource.Input:
15644 this.replaceIds(e2.data, iframeEl, ["id"]);
15645 return e2;
15646 case IncrementalSource.StyleSheetRule:
15647 case IncrementalSource.StyleDeclaration:
15648 this.replaceIds(e2.data, iframeEl, ["id"]);
15649 this.replaceStyleIds(e2.data, iframeEl, ["styleId"]);
15650 return e2;
15651 case IncrementalSource.Font: return e2;
15652 case IncrementalSource.Selection:
15653 e2.data.ranges.forEach(function(range) {
15654 _this.replaceIds(range, iframeEl, ["start", "end"]);
15655 });
15656 return e2;
15657 case IncrementalSource.AdoptedStyleSheet:
15658 this.replaceIds(e2.data, iframeEl, ["id"]);
15659 this.replaceStyleIds(e2.data, iframeEl, ["styleIds"]);
15660 (_a2 = e2.data.styles) == null || _a2.forEach(function(style) {
15661 _this.replaceStyleIds(style, iframeEl, ["styleId"]);
15662 });
15663 return e2;
15664 }
15665 }
15666 return false;
15667 };
15668 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
15669 for (var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;) {
15670 var key = _step.value;
15671 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
15672 if (Array.isArray(obj[key])) obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
15673 else obj[key] = iframeMirror.getId(iframeEl, obj[key]);
15674 }
15675 return obj;
15676 };
15677 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
15678 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
15679 };
15680 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
15681 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
15682 };
15683 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
15684 var _this = this;
15685 this.replaceIds(node2, iframeEl, ["id", "rootId"]);
15686 if ("childNodes" in node2) node2.childNodes.forEach(function(child) {
15687 _this.replaceIdOnNode(child, iframeEl);
15688 });
15689 };
15690 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
15691 var _this = this;
15692 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
15693 if ("childNodes" in node2) node2.childNodes.forEach(function(child) {
15694 _this.patchRootIdOnNode(child, rootId);
15695 });
15696 };
15697 return IframeManager;
15698 }();
15699 var ShadowDomManager = /*#__PURE__*/ function() {
15700 function ShadowDomManager(options) {
15701 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
15702 __publicField(this, "mutationCb");
15703 __publicField(this, "scrollCb");
15704 __publicField(this, "bypassOptions");
15705 __publicField(this, "mirror");
15706 __publicField(this, "restoreHandlers", []);
15707 this.mutationCb = options.mutationCb;
15708 this.scrollCb = options.scrollCb;
15709 this.bypassOptions = options.bypassOptions;
15710 this.mirror = options.mirror;
15711 this.init();
15712 }
15713 var _proto = ShadowDomManager.prototype;
15714 _proto.init = function init() {
15715 this.reset();
15716 this.patchAttachShadow(Element, document);
15717 };
15718 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
15719 var _this = this;
15720 if (!isNativeShadowDom(shadowRoot2)) return;
15721 if (this.shadowDoms.has(shadowRoot2)) return;
15722 this.shadowDoms.add(shadowRoot2);
15723 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
15724 doc,
15725 mutationCb: this.mutationCb,
15726 mirror: this.mirror,
15727 shadowDomManager: this
15728 }), shadowRoot2);
15729 this.restoreHandlers.push(function() {
15730 return observer.disconnect();
15731 });
15732 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
15733 scrollCb: this.scrollCb,
15734 doc: shadowRoot2,
15735 mirror: this.mirror
15736 })));
15737 setTimeout(function() {
15738 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
15739 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
15740 mirror: _this.mirror,
15741 stylesheetManager: _this.bypassOptions.stylesheetManager
15742 }, shadowRoot2));
15743 }, 0);
15744 };
15745 /**
15746 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
15747 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
15748 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
15749 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
15750 };
15751 /**
15752 * Patch 'attachShadow' to observe newly added shadow doms.
15753 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
15754 var manager = this;
15755 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
15756 return function(option) {
15757 var sRoot = original.call(this, option);
15758 var shadowRootEl = index.shadowRoot(this);
15759 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
15760 return sRoot;
15761 };
15762 }));
15763 };
15764 _proto.reset = function reset() {
15765 this.restoreHandlers.forEach(function(handler) {
15766 try {
15767 handler();
15768 } catch (e2) {}
15769 });
15770 this.restoreHandlers = [];
15771 this.shadowDoms = /* @__PURE__ */ new WeakSet();
15772 };
15773 return ShadowDomManager;
15774 }();
15775 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
15776 var lookup = typeof Uint8Array === "undefined" ? [] : /* @__PURE__ */ new Uint8Array(256);
15777 for (var i$1 = 0; i$1 < chars.length; i$1++) lookup[chars.charCodeAt(i$1)] = i$1;
15778 var encode = function encode(arraybuffer) {
15779 var bytes = new Uint8Array(arraybuffer);
15780 var i2;
15781 var len = bytes.length;
15782 var base64 = "";
15783 for (i2 = 0; i2 < len; i2 += 3) {
15784 base64 += chars[bytes[i2] >> 2];
15785 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
15786 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
15787 base64 += chars[bytes[i2 + 2] & 63];
15788 }
15789 if (len % 3 === 2) base64 = base64.substring(0, base64.length - 1) + "=";
15790 else if (len % 3 === 1) base64 = base64.substring(0, base64.length - 2) + "==";
15791 return base64;
15792 };
15793 var canvasVarMap = /* @__PURE__ */ new Map();
15794 function variableListFor$1(ctx, ctor) {
15795 var contextMap = canvasVarMap.get(ctx);
15796 if (!contextMap) {
15797 contextMap = /* @__PURE__ */ new Map();
15798 canvasVarMap.set(ctx, contextMap);
15799 }
15800 if (!contextMap.has(ctor)) contextMap.set(ctor, []);
15801 return contextMap.get(ctor);
15802 }
15803 var saveWebGLVar = function(value, win, ctx) {
15804 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
15805 var name = value.constructor.name;
15806 var list2 = variableListFor$1(ctx, name);
15807 var index2 = list2.indexOf(value);
15808 if (index2 === -1) {
15809 index2 = list2.length;
15810 list2.push(value);
15811 }
15812 return index2;
15813 };
15814 function serializeArg(value, win, ctx) {
15815 if (_instanceof(value, Array)) return value.map(function(arg) {
15816 return serializeArg(arg, win, ctx);
15817 });
15818 else if (value === null) return value;
15819 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)) return {
15820 rr_type: value.constructor.name,
15821 args: [Object.values(value)]
15822 };
15823 else if (_instanceof(value, ArrayBuffer)) return {
15824 rr_type: value.constructor.name,
15825 base64: encode(value)
15826 };
15827 else if (_instanceof(value, DataView)) return {
15828 rr_type: value.constructor.name,
15829 args: [
15830 serializeArg(value.buffer, win, ctx),
15831 value.byteOffset,
15832 value.byteLength
15833 ]
15834 };
15835 else if (_instanceof(value, HTMLImageElement)) return {
15836 rr_type: value.constructor.name,
15837 src: value.src
15838 };
15839 else if (_instanceof(value, HTMLCanvasElement)) return {
15840 rr_type: "HTMLImageElement",
15841 src: value.toDataURL()
15842 };
15843 else if (_instanceof(value, ImageData)) return {
15844 rr_type: value.constructor.name,
15845 args: [
15846 serializeArg(value.data, win, ctx),
15847 value.width,
15848 value.height
15849 ]
15850 };
15851 else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") return {
15852 rr_type: value.constructor.name,
15853 index: saveWebGLVar(value, win, ctx)
15854 };
15855 return value;
15856 }
15857 var serializeArgs = function(args, win, ctx) {
15858 return args.map(function(arg) {
15859 return serializeArg(arg, win, ctx);
15860 });
15861 };
15862 var isInstanceOfWebGLObject = function(value, win) {
15863 var supportedWebGLConstructorNames = [
15864 "WebGLActiveInfo",
15865 "WebGLBuffer",
15866 "WebGLFramebuffer",
15867 "WebGLProgram",
15868 "WebGLRenderbuffer",
15869 "WebGLShader",
15870 "WebGLShaderPrecisionFormat",
15871 "WebGLTexture",
15872 "WebGLUniformLocation",
15873 "WebGLVertexArrayObject",
15874 "WebGLVertexArrayObjectOES"
15875 ].filter(function(name) {
15876 return typeof win[name] === "function";
15877 });
15878 return Boolean(supportedWebGLConstructorNames.find(function(name) {
15879 return _instanceof(value, win[name]);
15880 }));
15881 };
15882 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
15883 var _loop = function() {
15884 var prop = _step.value;
15885 try {
15886 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") return "continue";
15887 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
15888 return function() {
15889 var _this = this;
15890 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
15891 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) setTimeout(function() {
15892 var recordArgs = serializeArgs(args, win, _this);
15893 cb(_this.canvas, {
15894 type: CanvasContext["2D"],
15895 property: prop,
15896 args: recordArgs
15897 });
15898 }, 0);
15899 return original.apply(this, args);
15900 };
15901 });
15902 handlers.push(restoreHandler);
15903 } catch (e) {
15904 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, { set: function set(v2) {
15905 cb(this.canvas, {
15906 type: CanvasContext["2D"],
15907 property: prop,
15908 args: [v2],
15909 setter: true
15910 });
15911 } });
15912 handlers.push(hookHandler);
15913 }
15914 };
15915 var handlers = [];
15916 for (var _iterator = _create_for_of_iterator_helper_loose(Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype)), _step; !(_step = _iterator()).done;) _loop();
15917 return function() {
15918 handlers.forEach(function(h) {
15919 return h();
15920 });
15921 };
15922 }
15923 function getNormalizedContextName(contextType) {
15924 return contextType === "experimental-webgl" ? "webgl" : contextType;
15925 }
15926 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
15927 var handlers = [];
15928 try {
15929 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
15930 return function(contextType) {
15931 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key];
15932 if (!isBlocked(this, blockClass, blockSelector, true)) {
15933 var ctxName = getNormalizedContextName(contextType);
15934 if (!("__context" in this)) this.__context = ctxName;
15935 if (setPreserveDrawingBufferToTrue && ["webgl", "webgl2"].includes(ctxName)) if (args[0] && _type_of(args[0]) === "object") {
15936 var contextAttributes = args[0];
15937 if (!contextAttributes.preserveDrawingBuffer) contextAttributes.preserveDrawingBuffer = true;
15938 } else args.splice(0, 1, { preserveDrawingBuffer: true });
15939 }
15940 return original.apply(this, [].concat([contextType], args));
15941 };
15942 });
15943 handlers.push(restoreHandler);
15944 } catch (e) {
15945 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
15946 }
15947 return function() {
15948 handlers.forEach(function(h) {
15949 return h();
15950 });
15951 };
15952 }
15953 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
15954 var _loop = function() {
15955 var prop = _step.value;
15956 if ([
15957 "isContextLost",
15958 "canvas",
15959 "drawingBufferWidth",
15960 "drawingBufferHeight"
15961 ].includes(prop)) return "continue";
15962 try {
15963 if (typeof prototype[prop] !== "function") return "continue";
15964 var restoreHandler = patch(prototype, prop, function(original) {
15965 return function() {
15966 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
15967 var result2 = original.apply(this, args);
15968 saveWebGLVar(result2, win, this);
15969 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
15970 var mutation = {
15971 type,
15972 property: prop,
15973 args: serializeArgs(args, win, this)
15974 };
15975 cb(this.canvas, mutation);
15976 }
15977 return result2;
15978 };
15979 });
15980 handlers.push(restoreHandler);
15981 } catch (e) {
15982 var hookHandler = hookSetter(prototype, prop, { set: function set(v2) {
15983 cb(this.canvas, {
15984 type,
15985 property: prop,
15986 args: [v2],
15987 setter: true
15988 });
15989 } });
15990 handlers.push(hookHandler);
15991 }
15992 };
15993 var handlers = [];
15994 for (var _iterator = _create_for_of_iterator_helper_loose(Object.getOwnPropertyNames(prototype)), _step; !(_step = _iterator()).done;) _loop();
15995 return handlers;
15996 }
15997 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
15998 var _handlers;
15999 var handlers = [];
16000 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
16001 if (typeof win.WebGL2RenderingContext !== "undefined") {
16002 var _handlers1;
16003 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
16004 }
16005 return function() {
16006 handlers.forEach(function(h) {
16007 return h();
16008 });
16009 };
16010 }
16011 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
16012 var decodeBase64 = function(base64) {
16013 return Uint8Array.from(atob(base64), function(c2) {
16014 return c2.charCodeAt(0);
16015 });
16016 };
16017 var blob = typeof window !== "undefined" && window.Blob && new Blob([decodeBase64(encodedJs)], { type: "text/javascript;charset=utf-8" });
16018 function WorkerWrapper(options) {
16019 var objURL;
16020 try {
16021 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
16022 if (!objURL) throw "";
16023 var worker = new Worker(objURL, { name: options == null ? void 0 : options.name });
16024 worker.addEventListener("error", function() {
16025 (window.URL || window.webkitURL).revokeObjectURL(objURL);
16026 });
16027 return worker;
16028 } catch (e2) {
16029 return new Worker("data:text/javascript;base64," + encodedJs, { name: options == null ? void 0 : options.name });
16030 } finally {
16031 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
16032 }
16033 }
16034 var CanvasManager = /*#__PURE__*/ function() {
16035 function CanvasManager(options) {
16036 var _this = this;
16037 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
16038 __publicField(this, "rafStamps", {
16039 latestId: 0,
16040 invokeId: null
16041 });
16042 __publicField(this, "mirror");
16043 __publicField(this, "mutationCb");
16044 __publicField(this, "resetObservers");
16045 __publicField(this, "frozen", false);
16046 __publicField(this, "locked", false);
16047 __publicField(this, "processMutation", function(target, mutation) {
16048 if (_this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
16049 if (!_this.pendingCanvasMutations.has(target)) _this.pendingCanvasMutations.set(target, []);
16050 _this.pendingCanvasMutations.get(target).push(mutation);
16051 });
16052 var _options_sampling = options.sampling;
16053 var sampling = _options_sampling === void 0 ? "all" : _options_sampling;
16054 var win = options.win;
16055 var blockClass = options.blockClass;
16056 var blockSelector = options.blockSelector;
16057 var recordCanvas = options.recordCanvas;
16058 var dataURLOptions = options.dataURLOptions;
16059 this.mutationCb = options.mutationCb;
16060 this.mirror = options.mirror;
16061 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
16062 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, { dataURLOptions });
16063 }
16064 var _proto = CanvasManager.prototype;
16065 _proto.reset = function reset() {
16066 this.pendingCanvasMutations.clear();
16067 this.resetObservers && this.resetObservers();
16068 };
16069 _proto.freeze = function freeze() {
16070 this.frozen = true;
16071 };
16072 _proto.unfreeze = function unfreeze() {
16073 this.frozen = false;
16074 };
16075 _proto.lock = function lock() {
16076 this.locked = true;
16077 };
16078 _proto.unlock = function unlock() {
16079 this.locked = false;
16080 };
16081 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
16082 var _this = this;
16083 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
16084 var snapshotInProgressMap = /* @__PURE__ */ new Map();
16085 var worker = new WorkerWrapper();
16086 worker.onmessage = function(e2) {
16087 var id = e2.data.id;
16088 snapshotInProgressMap.set(id, false);
16089 if (!("base64" in e2.data)) return;
16090 var _e2_data = e2.data;
16091 var base64 = _e2_data.base64;
16092 var type = _e2_data.type;
16093 var width = _e2_data.width;
16094 var height = _e2_data.height;
16095 _this.mutationCb({
16096 id,
16097 type: CanvasContext["2D"],
16098 commands: [{
16099 property: "clearRect",
16100 args: [
16101 0,
16102 0,
16103 width,
16104 height
16105 ]
16106 }, {
16107 property: "drawImage",
16108 args: [
16109 {
16110 rr_type: "ImageBitmap",
16111 args: [{
16112 rr_type: "Blob",
16113 data: [{
16114 rr_type: "ArrayBuffer",
16115 base64
16116 }],
16117 type
16118 }]
16119 },
16120 0,
16121 0
16122 ]
16123 }]
16124 });
16125 };
16126 var timeBetweenSnapshots = 1e3 / fps;
16127 var lastSnapshotTime = 0;
16128 var rafId;
16129 var getCanvas = function() {
16130 var matchedCanvas = [];
16131 win.document.querySelectorAll("canvas").forEach(function(canvas) {
16132 if (!isBlocked(canvas, blockClass, blockSelector, true)) matchedCanvas.push(canvas);
16133 });
16134 return matchedCanvas;
16135 };
16136 var takeCanvasSnapshots = function(timestamp) {
16137 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
16138 rafId = requestAnimationFrame(takeCanvasSnapshots);
16139 return;
16140 }
16141 lastSnapshotTime = timestamp;
16142 var _this1 = _this;
16143 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
16144 var _a2;
16145 var id;
16146 var context;
16147 var bitmap;
16148 return _ts_generator(this, function(_state) {
16149 switch (_state.label) {
16150 case 0:
16151 id = _this1.mirror.getId(canvas);
16152 if (snapshotInProgressMap.get(id)) return [2];
16153 if (canvas.width === 0 || canvas.height === 0) return [2];
16154 snapshotInProgressMap.set(id, true);
16155 if (["webgl", "webgl2"].includes(canvas.__context)) {
16156 context = canvas.getContext(canvas.__context);
16157 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) context.clear(context.COLOR_BUFFER_BIT);
16158 }
16159 return [4, createImageBitmap(canvas)];
16160 case 1:
16161 bitmap = _state.sent();
16162 worker.postMessage({
16163 id,
16164 bitmap,
16165 width: canvas.width,
16166 height: canvas.height,
16167 dataURLOptions: options.dataURLOptions
16168 }, [bitmap]);
16169 return [2];
16170 }
16171 });
16172 }));
16173 rafId = requestAnimationFrame(takeCanvasSnapshots);
16174 };
16175 rafId = requestAnimationFrame(takeCanvasSnapshots);
16176 this.resetObservers = function() {
16177 canvasContextReset();
16178 cancelAnimationFrame(rafId);
16179 };
16180 };
16181 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
16182 this.startRAFTimestamping();
16183 this.startPendingCanvasMutationFlusher();
16184 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
16185 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
16186 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
16187 this.resetObservers = function() {
16188 canvasContextReset();
16189 canvas2DReset();
16190 canvasWebGL1and2Reset();
16191 };
16192 };
16193 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
16194 var _this = this;
16195 requestAnimationFrame(function() {
16196 return _this.flushPendingCanvasMutations();
16197 });
16198 };
16199 _proto.startRAFTimestamping = function startRAFTimestamping() {
16200 var _this = this;
16201 var setLatestRAFTimestamp = function(timestamp) {
16202 _this.rafStamps.latestId = timestamp;
16203 requestAnimationFrame(setLatestRAFTimestamp);
16204 };
16205 requestAnimationFrame(setLatestRAFTimestamp);
16206 };
16207 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
16208 var _this = this;
16209 this.pendingCanvasMutations.forEach(function(_values, canvas) {
16210 var id = _this.mirror.getId(canvas);
16211 _this.flushPendingCanvasMutationFor(canvas, id);
16212 });
16213 requestAnimationFrame(function() {
16214 return _this.flushPendingCanvasMutations();
16215 });
16216 };
16217 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
16218 if (this.frozen || this.locked) return;
16219 var valuesWithType = this.pendingCanvasMutations.get(canvas);
16220 if (!valuesWithType || id === -1) return;
16221 var values = valuesWithType.map(function(value) {
16222 value.type;
16223 return _object_without_properties_loose(value, ["type"]);
16224 });
16225 var type = valuesWithType[0].type;
16226 this.mutationCb({
16227 id,
16228 type,
16229 commands: values
16230 });
16231 this.pendingCanvasMutations.delete(canvas);
16232 };
16233 return CanvasManager;
16234 }();
16235 var StylesheetManager = /*#__PURE__*/ function() {
16236 function StylesheetManager(options) {
16237 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
16238 __publicField(this, "mutationCb");
16239 __publicField(this, "adoptedStyleSheetCb");
16240 __publicField(this, "styleMirror", new StyleSheetMirror());
16241 this.mutationCb = options.mutationCb;
16242 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
16243 }
16244 var _proto = StylesheetManager.prototype;
16245 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
16246 if ("_cssText" in childSn.attributes) this.mutationCb({
16247 adds: [],
16248 removes: [],
16249 texts: [],
16250 attributes: [{
16251 id: childSn.id,
16252 attributes: childSn.attributes
16253 }]
16254 });
16255 this.trackLinkElement(linkEl);
16256 };
16257 _proto.trackLinkElement = function trackLinkElement(linkEl) {
16258 if (this.trackedLinkElements.has(linkEl)) return;
16259 this.trackedLinkElements.add(linkEl);
16260 this.trackStylesheetInLinkElement(linkEl);
16261 };
16262 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
16263 var _this;
16264 var _loop = function() {
16265 var sheet = _step.value;
16266 var styleId = void 0;
16267 if (!_this.styleMirror.has(sheet)) {
16268 styleId = _this.styleMirror.add(sheet);
16269 styles.push({
16270 styleId,
16271 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
16272 return {
16273 rule: stringifyRule(r2, sheet.href),
16274 index: index2
16275 };
16276 })
16277 });
16278 } else styleId = _this.styleMirror.getId(sheet);
16279 adoptedStyleSheetData.styleIds.push(styleId);
16280 };
16281 if (sheets.length === 0) return;
16282 var adoptedStyleSheetData = {
16283 id: hostId,
16284 styleIds: []
16285 };
16286 var styles = [];
16287 for (var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;) _this = this, _loop();
16288 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
16289 this.adoptedStyleSheetCb(adoptedStyleSheetData);
16290 };
16291 _proto.reset = function reset() {
16292 this.styleMirror.reset();
16293 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
16294 };
16295 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
16296 return StylesheetManager;
16297 }();
16298 var ProcessedNodeManager = /*#__PURE__*/ function() {
16299 function ProcessedNodeManager() {
16300 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
16301 __publicField(this, "active", false);
16302 }
16303 var _proto = ProcessedNodeManager.prototype;
16304 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
16305 var buffers = this.nodeMap.get(node2);
16306 return buffers && Array.from(buffers).some(function(buffer) {
16307 return buffer !== thisBuffer;
16308 });
16309 };
16310 _proto.add = function add(node2, buffer) {
16311 var _this = this;
16312 if (!this.active) {
16313 this.active = true;
16314 requestAnimationFrame(function() {
16315 _this.nodeMap = /* @__PURE__ */ new WeakMap();
16316 _this.active = false;
16317 });
16318 }
16319 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
16320 };
16321 _proto.destroy = function destroy() {};
16322 return ProcessedNodeManager;
16323 }();
16324 var wrappedEmit;
16325 var takeFullSnapshot$1;
16326 var canvasManager;
16327 var recording = false;
16328 try {
16329 if (Array.from([1], function(x2) {
16330 return x2 * 2;
16331 })[0] !== 2) {
16332 var cleanFrame = document.createElement("iframe");
16333 document.body.appendChild(cleanFrame);
16334 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
16335 document.body.removeChild(cleanFrame);
16336 }
16337 } catch (err) {
16338 console.debug("Unable to override Array.from", err);
16339 }
16340 var mirror = createMirror$2();
16341 function record(options) {
16342 if (options === void 0) options = {};
16343 var emit = options.emit;
16344 var checkoutEveryNms = options.checkoutEveryNms;
16345 var checkoutEveryNth = options.checkoutEveryNth;
16346 var _options_blockClass = options.blockClass;
16347 var blockClass = _options_blockClass === void 0 ? "rr-block" : _options_blockClass;
16348 var _options_blockSelector = options.blockSelector;
16349 var blockSelector = _options_blockSelector === void 0 ? null : _options_blockSelector;
16350 var _options_ignoreClass = options.ignoreClass;
16351 var ignoreClass = _options_ignoreClass === void 0 ? "rr-ignore" : _options_ignoreClass;
16352 var _options_ignoreSelector = options.ignoreSelector;
16353 var ignoreSelector = _options_ignoreSelector === void 0 ? null : _options_ignoreSelector;
16354 var _options_maskTextClass = options.maskTextClass;
16355 var maskTextClass = _options_maskTextClass === void 0 ? "rr-mask" : _options_maskTextClass;
16356 var _options_maskTextSelector = options.maskTextSelector;
16357 var maskTextSelector = _options_maskTextSelector === void 0 ? null : _options_maskTextSelector;
16358 var _options_inlineStylesheet = options.inlineStylesheet;
16359 var inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet;
16360 var maskAllInputs = options.maskAllInputs;
16361 var _maskInputOptions = options.maskInputOptions;
16362 var _slimDOMOptions = options.slimDOMOptions;
16363 var maskInputFn = options.maskInputFn;
16364 var maskTextFn = options.maskTextFn;
16365 var hooks = options.hooks;
16366 var packFn = options.packFn;
16367 var _options_sampling = options.sampling;
16368 var sampling = _options_sampling === void 0 ? {} : _options_sampling;
16369 var _options_dataURLOptions = options.dataURLOptions;
16370 var dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions;
16371 var mousemoveWait = options.mousemoveWait;
16372 var _options_recordDOM = options.recordDOM;
16373 var recordDOM = _options_recordDOM === void 0 ? true : _options_recordDOM;
16374 var _options_recordCanvas = options.recordCanvas;
16375 var recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas;
16376 var _options_recordCrossOriginIframes = options.recordCrossOriginIframes;
16377 var recordCrossOriginIframes = _options_recordCrossOriginIframes === void 0 ? false : _options_recordCrossOriginIframes;
16378 var _options_recordAfter = options.recordAfter;
16379 var recordAfter = _options_recordAfter === void 0 ? options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load" : _options_recordAfter;
16380 var _options_userTriggeredOnInput = options.userTriggeredOnInput;
16381 var userTriggeredOnInput = _options_userTriggeredOnInput === void 0 ? false : _options_userTriggeredOnInput;
16382 var _options_collectFonts = options.collectFonts;
16383 var collectFonts = _options_collectFonts === void 0 ? false : _options_collectFonts;
16384 var _options_inlineImages = options.inlineImages;
16385 var inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages;
16386 var plugins = options.plugins;
16387 var _options_keepIframeSrcFn = options.keepIframeSrcFn;
16388 var keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
16389 return false;
16390 } : _options_keepIframeSrcFn;
16391 var _options_ignoreCSSAttributes = options.ignoreCSSAttributes;
16392 var ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes;
16393 var errorHandler2 = options.errorHandler;
16394 registerErrorHandler(errorHandler2);
16395 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
16396 var passEmitsToParent = false;
16397 if (!inEmittingFrame) try {
16398 if (window.parent.document) passEmitsToParent = false;
16399 } catch (e2) {
16400 passEmitsToParent = true;
16401 }
16402 if (inEmittingFrame && !emit) throw new Error("emit function is required");
16403 if (!inEmittingFrame && !passEmitsToParent) return function() {};
16404 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) sampling.mousemove = mousemoveWait;
16405 mirror.reset();
16406 var maskInputOptions = maskAllInputs === true ? {
16407 color: true,
16408 date: true,
16409 "datetime-local": true,
16410 email: true,
16411 month: true,
16412 number: true,
16413 range: true,
16414 search: true,
16415 tel: true,
16416 text: true,
16417 time: true,
16418 url: true,
16419 week: true,
16420 textarea: true,
16421 select: true,
16422 password: true,
16423 hidden: true
16424 } : _maskInputOptions !== void 0 ? _maskInputOptions : { password: true };
16425 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
16426 script: true,
16427 comment: true,
16428 headFavicon: true,
16429 headWhitespace: true,
16430 headMetaSocial: true,
16431 headMetaRobots: true,
16432 headMetaHttpEquiv: true,
16433 headMetaVerification: true,
16434 headMetaAuthorship: _slimDOMOptions === "all",
16435 headMetaDescKeywords: _slimDOMOptions === "all",
16436 headTitleMutations: _slimDOMOptions === "all"
16437 } : _slimDOMOptions ? _slimDOMOptions : {};
16438 polyfill$1();
16439 var lastFullSnapshotEvent;
16440 var incrementalSnapshotCount = 0;
16441 var eventProcessor = function(e2) {
16442 for (var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;) {
16443 var plugin3 = _step.value;
16444 if (plugin3.eventProcessor) e2 = plugin3.eventProcessor(e2);
16445 }
16446 if (packFn && !passEmitsToParent) e2 = packFn(e2);
16447 return e2;
16448 };
16449 wrappedEmit = function(r2, isCheckout) {
16450 var _a2;
16451 var e2 = r2;
16452 e2.timestamp = nowTimestamp();
16453 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) mutationBuffers.forEach(function(buf) {
16454 return buf.unfreeze();
16455 });
16456 if (inEmittingFrame) emit == null || emit(eventProcessor(e2), isCheckout);
16457 else if (passEmitsToParent) {
16458 var message = {
16459 type: "rrweb",
16460 event: eventProcessor(e2),
16461 origin: window.location.origin,
16462 isCheckout
16463 };
16464 window.parent.postMessage(message, "*");
16465 }
16466 if (e2.type === EventType.FullSnapshot) {
16467 lastFullSnapshotEvent = e2;
16468 incrementalSnapshotCount = 0;
16469 } else if (e2.type === EventType.IncrementalSnapshot) {
16470 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) return;
16471 incrementalSnapshotCount++;
16472 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
16473 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
16474 if (exceedCount || exceedTime) takeFullSnapshot$1(true);
16475 }
16476 };
16477 var wrappedMutationEmit = function(m) {
16478 wrappedEmit({
16479 type: EventType.IncrementalSnapshot,
16480 data: _extends({ source: IncrementalSource.Mutation }, m)
16481 });
16482 };
16483 var wrappedScrollEmit = function(p) {
16484 return wrappedEmit({
16485 type: EventType.IncrementalSnapshot,
16486 data: _extends({ source: IncrementalSource.Scroll }, p)
16487 });
16488 };
16489 var wrappedCanvasMutationEmit = function(p) {
16490 return wrappedEmit({
16491 type: EventType.IncrementalSnapshot,
16492 data: _extends({ source: IncrementalSource.CanvasMutation }, p)
16493 });
16494 };
16495 var wrappedAdoptedStyleSheetEmit = function(a2) {
16496 return wrappedEmit({
16497 type: EventType.IncrementalSnapshot,
16498 data: _extends({ source: IncrementalSource.AdoptedStyleSheet }, a2)
16499 });
16500 };
16501 var stylesheetManager = new StylesheetManager({
16502 mutationCb: wrappedMutationEmit,
16503 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
16504 });
16505 var iframeManager = new IframeManager({
16506 mirror,
16507 mutationCb: wrappedMutationEmit,
16508 stylesheetManager,
16509 recordCrossOriginIframes,
16510 wrappedEmit
16511 });
16512 for (var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;) {
16513 var plugin3 = _step.value;
16514 if (plugin3.getMirror) plugin3.getMirror({
16515 nodeMirror: mirror,
16516 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
16517 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
16518 });
16519 }
16520 var processedNodeManager = new ProcessedNodeManager();
16521 canvasManager = new CanvasManager({
16522 recordCanvas,
16523 mutationCb: wrappedCanvasMutationEmit,
16524 win: window,
16525 blockClass,
16526 blockSelector,
16527 mirror,
16528 sampling: sampling.canvas,
16529 dataURLOptions
16530 });
16531 var shadowDomManager = new ShadowDomManager({
16532 mutationCb: wrappedMutationEmit,
16533 scrollCb: wrappedScrollEmit,
16534 bypassOptions: {
16535 blockClass,
16536 blockSelector,
16537 maskTextClass,
16538 maskTextSelector,
16539 inlineStylesheet,
16540 maskInputOptions,
16541 dataURLOptions,
16542 maskTextFn,
16543 maskInputFn,
16544 recordCanvas,
16545 inlineImages,
16546 sampling,
16547 slimDOMOptions,
16548 iframeManager,
16549 stylesheetManager,
16550 canvasManager,
16551 keepIframeSrcFn,
16552 processedNodeManager
16553 },
16554 mirror
16555 });
16556 takeFullSnapshot$1 = function(isCheckout) {
16557 if (isCheckout === void 0) isCheckout = false;
16558 if (!recordDOM) return;
16559 wrappedEmit({
16560 type: EventType.Meta,
16561 data: {
16562 href: window.location.href,
16563 width: getWindowWidth(),
16564 height: getWindowHeight()
16565 }
16566 }, isCheckout);
16567 stylesheetManager.reset();
16568 shadowDomManager.init();
16569 mutationBuffers.forEach(function(buf) {
16570 return buf.lock();
16571 });
16572 var node2 = snapshot(document, {
16573 mirror,
16574 blockClass,
16575 blockSelector,
16576 maskTextClass,
16577 maskTextSelector,
16578 inlineStylesheet,
16579 maskAllInputs: maskInputOptions,
16580 maskTextFn,
16581 maskInputFn,
16582 slimDOM: slimDOMOptions,
16583 dataURLOptions,
16584 recordCanvas,
16585 inlineImages,
16586 onSerialize: function(n2) {
16587 if (isSerializedIframe(n2, mirror)) iframeManager.addIframe(n2);
16588 if (isSerializedStylesheet(n2, mirror)) stylesheetManager.trackLinkElement(n2);
16589 if (hasShadowRoot(n2)) shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
16590 },
16591 onIframeLoad: function(iframe, childSn) {
16592 iframeManager.attachIframe(iframe, childSn);
16593 shadowDomManager.observeAttachShadow(iframe);
16594 },
16595 onStylesheetLoad: function(linkEl, childSn) {
16596 stylesheetManager.attachLinkElement(linkEl, childSn);
16597 },
16598 keepIframeSrcFn
16599 });
16600 if (!node2) return console.warn("Failed to snapshot the document");
16601 wrappedEmit({
16602 type: EventType.FullSnapshot,
16603 data: {
16604 node: node2,
16605 initialOffset: getWindowScroll(window)
16606 }
16607 }, isCheckout);
16608 mutationBuffers.forEach(function(buf) {
16609 return buf.unlock();
16610 });
16611 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
16612 };
16613 try {
16614 var handlers = [];
16615 var observe = function(doc) {
16616 var _a2;
16617 return callbackWrapper(initObservers)({
16618 mutationCb: wrappedMutationEmit,
16619 mousemoveCb: function(positions, source) {
16620 return wrappedEmit({
16621 type: EventType.IncrementalSnapshot,
16622 data: {
16623 source,
16624 positions
16625 }
16626 });
16627 },
16628 mouseInteractionCb: function(d) {
16629 return wrappedEmit({
16630 type: EventType.IncrementalSnapshot,
16631 data: _extends({ source: IncrementalSource.MouseInteraction }, d)
16632 });
16633 },
16634 scrollCb: wrappedScrollEmit,
16635 viewportResizeCb: function(d) {
16636 return wrappedEmit({
16637 type: EventType.IncrementalSnapshot,
16638 data: _extends({ source: IncrementalSource.ViewportResize }, d)
16639 });
16640 },
16641 inputCb: function(v2) {
16642 return wrappedEmit({
16643 type: EventType.IncrementalSnapshot,
16644 data: _extends({ source: IncrementalSource.Input }, v2)
16645 });
16646 },
16647 mediaInteractionCb: function(p) {
16648 return wrappedEmit({
16649 type: EventType.IncrementalSnapshot,
16650 data: _extends({ source: IncrementalSource.MediaInteraction }, p)
16651 });
16652 },
16653 styleSheetRuleCb: function(r2) {
16654 return wrappedEmit({
16655 type: EventType.IncrementalSnapshot,
16656 data: _extends({ source: IncrementalSource.StyleSheetRule }, r2)
16657 });
16658 },
16659 styleDeclarationCb: function(r2) {
16660 return wrappedEmit({
16661 type: EventType.IncrementalSnapshot,
16662 data: _extends({ source: IncrementalSource.StyleDeclaration }, r2)
16663 });
16664 },
16665 canvasMutationCb: wrappedCanvasMutationEmit,
16666 fontCb: function(p) {
16667 return wrappedEmit({
16668 type: EventType.IncrementalSnapshot,
16669 data: _extends({ source: IncrementalSource.Font }, p)
16670 });
16671 },
16672 selectionCb: function(p) {
16673 wrappedEmit({
16674 type: EventType.IncrementalSnapshot,
16675 data: _extends({ source: IncrementalSource.Selection }, p)
16676 });
16677 },
16678 customElementCb: function(c2) {
16679 wrappedEmit({
16680 type: EventType.IncrementalSnapshot,
16681 data: _extends({ source: IncrementalSource.CustomElement }, c2)
16682 });
16683 },
16684 blockClass,
16685 ignoreClass,
16686 ignoreSelector,
16687 maskTextClass,
16688 maskTextSelector,
16689 maskInputOptions,
16690 inlineStylesheet,
16691 sampling,
16692 recordDOM,
16693 recordCanvas,
16694 inlineImages,
16695 userTriggeredOnInput,
16696 collectFonts,
16697 doc,
16698 maskInputFn,
16699 maskTextFn,
16700 keepIframeSrcFn,
16701 blockSelector,
16702 slimDOMOptions,
16703 dataURLOptions,
16704 mirror,
16705 iframeManager,
16706 stylesheetManager,
16707 shadowDomManager,
16708 processedNodeManager,
16709 canvasManager,
16710 ignoreCSSAttributes,
16711 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
16712 return p.observer;
16713 })) == null ? void 0 : _a2.map(function(p) {
16714 return {
16715 observer: p.observer,
16716 options: p.options,
16717 callback: function(payload) {
16718 return wrappedEmit({
16719 type: EventType.Plugin,
16720 data: {
16721 plugin: p.name,
16722 payload
16723 }
16724 });
16725 }
16726 };
16727 })) || []
16728 }, hooks);
16729 };
16730 iframeManager.addLoadListener(function(iframeEl) {
16731 try {
16732 handlers.push(observe(iframeEl.contentDocument));
16733 } catch (error) {
16734 console.warn(error);
16735 }
16736 });
16737 var init = function() {
16738 takeFullSnapshot$1();
16739 handlers.push(observe(document));
16740 recording = true;
16741 };
16742 if (document.readyState === "interactive" || document.readyState === "complete") init();
16743 else {
16744 handlers.push(on("DOMContentLoaded", function() {
16745 wrappedEmit({
16746 type: EventType.DomContentLoaded,
16747 data: {}
16748 });
16749 if (recordAfter === "DOMContentLoaded") init();
16750 }));
16751 handlers.push(on("load", function() {
16752 wrappedEmit({
16753 type: EventType.Load,
16754 data: {}
16755 });
16756 if (recordAfter === "load") init();
16757 }, window));
16758 }
16759 return function() {
16760 handlers.forEach(function(handler) {
16761 try {
16762 handler();
16763 } catch (error) {
16764 if (!String(error).toLowerCase().includes("cross-origin")) console.warn(error);
16765 }
16766 });
16767 processedNodeManager.destroy();
16768 recording = false;
16769 unregisterErrorHandler();
16770 };
16771 } catch (error) {
16772 console.warn(error);
16773 }
16774 }
16775 record.addCustomEvent = function(tag, payload) {
16776 if (!recording) throw new Error("please add custom event after start recording");
16777 wrappedEmit({
16778 type: EventType.Custom,
16779 data: {
16780 tag,
16781 payload
16782 }
16783 });
16784 };
16785 record.freezePage = function() {
16786 mutationBuffers.forEach(function(buf) {
16787 return buf.freeze();
16788 });
16789 };
16790 record.takeFullSnapshot = function(isCheckout) {
16791 if (!recording) throw new Error("please take full snapshot after start recording");
16792 takeFullSnapshot$1(isCheckout);
16793 };
16794 record.mirror = mirror;
16795 var n;
16796 (function(t2) {
16797 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
16798 })(n || (n = {}));
16799 record.addCustomEvent;
16800 record.freezePage;
16801 record.takeFullSnapshot;
16802 var setImmediate = win["setImmediate"];
16803 var builtInProp;
16804 var cycle;
16805 var schedulingQueue;
16806 var ToString = Object.prototype.toString;
16807 var timer = typeof setImmediate !== "undefined" ? function timer(fn) {
16808 return setImmediate(fn);
16809 } : setTimeout;
16810 try {
16811 Object.defineProperty({}, "x", {});
16812 builtInProp = function builtInProp(obj, name, val, config) {
16813 return Object.defineProperty(obj, name, {
16814 value: val,
16815 writable: true,
16816 configurable: config !== false
16817 });
16818 };
16819 } catch (err) {
16820 builtInProp = function builtInProp(obj, name, val) {
16821 obj[name] = val;
16822 return obj;
16823 };
16824 }
16825 schedulingQueue = (function Queue() {
16826 var first;
16827 var last;
16828 var item;
16829 function Item(fn, self) {
16830 this.fn = fn;
16831 this.self = self;
16832 this.next = void 0;
16833 }
16834 return {
16835 add: function add(fn, self) {
16836 item = new Item(fn, self);
16837 if (last) last.next = item;
16838 else first = item;
16839 last = item;
16840 item = void 0;
16841 },
16842 drain: function drain() {
16843 var f = first;
16844 first = last = cycle = void 0;
16845 while (f) {
16846 f.fn.call(f.self);
16847 f = f.next;
16848 }
16849 }
16850 };
16851 })();
16852 function schedule(fn, self) {
16853 schedulingQueue.add(fn, self);
16854 if (!cycle) cycle = timer(schedulingQueue.drain);
16855 }
16856 function isThenable(o) {
16857 var _then;
16858 var oType = typeof o;
16859 if (o !== null && (oType === "object" || oType === "function")) _then = o.then;
16860 return typeof _then === "function" ? _then : false;
16861 }
16862 function notify() {
16863 for (var i = 0; i < this.chain.length; i++) notifyIsolated(this, this.state === 1 ? this.chain[i].success : this.chain[i].failure, this.chain[i]);
16864 this.chain.length = 0;
16865 }
16866 function notifyIsolated(self, cb, chain) {
16867 var ret;
16868 var _then;
16869 try {
16870 if (cb === false) chain.reject(self.msg);
16871 else {
16872 if (cb === true) ret = self.msg;
16873 else ret = cb.call(void 0, self.msg);
16874 if (ret === chain.promise) chain.reject(TypeError("Promise-chain cycle"));
16875 else if (_then = isThenable(ret)) _then.call(ret, chain.resolve, chain.reject);
16876 else chain.resolve(ret);
16877 }
16878 } catch (err) {
16879 chain.reject(err);
16880 }
16881 }
16882 function resolve(msg) {
16883 var _then;
16884 var self = this;
16885 if (self.triggered) return;
16886 self.triggered = true;
16887 if (self.def) self = self.def;
16888 try {
16889 if (_then = isThenable(msg)) schedule(function() {
16890 var defWrapper = new MakeDefWrapper(self);
16891 try {
16892 _then.call(msg, function $resolve$() {
16893 resolve.apply(defWrapper, arguments);
16894 }, function $reject$() {
16895 reject.apply(defWrapper, arguments);
16896 });
16897 } catch (err) {
16898 reject.call(defWrapper, err);
16899 }
16900 });
16901 else {
16902 self.msg = msg;
16903 self.state = 1;
16904 if (self.chain.length > 0) schedule(notify, self);
16905 }
16906 } catch (err) {
16907 reject.call(new MakeDefWrapper(self), err);
16908 }
16909 }
16910 function reject(msg) {
16911 var self = this;
16912 if (self.triggered) return;
16913 self.triggered = true;
16914 if (self.def) self = self.def;
16915 self.msg = msg;
16916 self.state = 2;
16917 if (self.chain.length > 0) schedule(notify, self);
16918 }
16919 function iteratePromises(Constructor, arr, resolver, rejecter) {
16920 for (var idx = 0; idx < arr.length; idx++) (function IIFE(idx) {
16921 Constructor.resolve(arr[idx]).then(function $resolver$(msg) {
16922 resolver(idx, msg);
16923 }, rejecter);
16924 })(idx);
16925 }
16926 function MakeDefWrapper(self) {
16927 this.def = self;
16928 this.triggered = false;
16929 }
16930 function MakeDef(self) {
16931 this.promise = self;
16932 this.state = 0;
16933 this.triggered = false;
16934 this.chain = [];
16935 this.msg = void 0;
16936 }
16937 function NpoPromise(executor) {
16938 if (typeof executor !== "function") throw TypeError("Not a function");
16939 if (this["__NPO__"] !== 0) throw TypeError("Not a promise");
16940 this["__NPO__"] = 1;
16941 var def = new MakeDef(this);
16942 this["then"] = function then(success, failure) {
16943 var o = {
16944 success: typeof success === "function" ? success : true,
16945 failure: typeof failure === "function" ? failure : false
16946 };
16947 o.promise = new this.constructor(function extractChain(resolve, reject) {
16948 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
16949 o.resolve = resolve;
16950 o.reject = reject;
16951 });
16952 def.chain.push(o);
16953 if (def.state !== 0) schedule(notify, def);
16954 return o.promise;
16955 };
16956 this["catch"] = function $catch$(failure) {
16957 return this.then(void 0, failure);
16958 };
16959 try {
16960 executor.call(void 0, function publicResolve(msg) {
16961 resolve.call(def, msg);
16962 }, function publicReject(msg) {
16963 reject.call(def, msg);
16964 });
16965 } catch (err) {
16966 reject.call(def, err);
16967 }
16968 }
16969 var PromisePrototype = builtInProp({}, "constructor", NpoPromise, false);
16970 NpoPromise.prototype = PromisePrototype;
16971 builtInProp(PromisePrototype, "__NPO__", 0, false);
16972 builtInProp(NpoPromise, "resolve", function Promise$resolve(msg) {
16973 var Constructor = this;
16974 if (msg && typeof msg === "object" && msg["__NPO__"] === 1) return msg;
16975 return new Constructor(function executor(resolve, reject) {
16976 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
16977 resolve(msg);
16978 });
16979 });
16980 builtInProp(NpoPromise, "reject", function Promise$reject(msg) {
16981 return new this(function executor(resolve, reject) {
16982 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
16983 reject(msg);
16984 });
16985 });
16986 builtInProp(NpoPromise, "all", function Promise$all(arr) {
16987 var Constructor = this;
16988 if (ToString.call(arr) !== "[object Array]") return Constructor.reject(TypeError("Not an array"));
16989 if (arr.length === 0) return Constructor.resolve([]);
16990 return new Constructor(function executor(resolve, reject) {
16991 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
16992 var len = arr.length;
16993 var msgs = Array(len);
16994 var count = 0;
16995 iteratePromises(Constructor, arr, function resolver(idx, msg) {
16996 msgs[idx] = msg;
16997 if (++count === len) resolve(msgs);
16998 }, reject);
16999 });
17000 });
17001 builtInProp(NpoPromise, "race", function Promise$race(arr) {
17002 var Constructor = this;
17003 if (ToString.call(arr) !== "[object Array]") return Constructor.reject(TypeError("Not an array"));
17004 return new Constructor(function executor(resolve, reject) {
17005 if (typeof resolve !== "function" || typeof reject !== "function") throw TypeError("Not a function");
17006 iteratePromises(Constructor, arr, function resolver(idx, msg) {
17007 resolve(msg);
17008 }, reject);
17009 });
17010 });
17011 var PromisePolyfill;
17012 if (typeof Promise !== "undefined" && Promise.toString().indexOf("[native code]") !== -1) PromisePolyfill = Promise;
17013 else PromisePolyfill = NpoPromise;
17014 var Config = {
17015 DEBUG: false,
17016 LIB_VERSION: "2.71.1"
17017 };
17018 var MAX_RECORDING_MS = 1440 * 60 * 1e3;
17019 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1e3;
17020 var ArrayProto = Array.prototype;
17021 var FuncProto = Function.prototype;
17022 var ObjProto = Object.prototype;
17023 var slice = ArrayProto.slice;
17024 var toString = ObjProto.toString;
17025 var hasOwnProperty = ObjProto.hasOwnProperty;
17026 var windowConsole = win.console;
17027 var navigator = win.navigator;
17028 var document$1 = win.document;
17029 var windowOpera = win.opera;
17030 var screen = win.screen;
17031 var userAgent = navigator.userAgent;
17032 var nativeBind = FuncProto.bind;
17033 var nativeForEach = ArrayProto.forEach;
17034 var nativeIndexOf = ArrayProto.indexOf;
17035 var nativeMap = ArrayProto.map;
17036 var nativeIsArray = Array.isArray;
17037 var breaker = {};
17038 var _$1 = { trim: function(str) {
17039 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
17040 } };
17041 var console$1 = {
17042 /** @type {function(...*)} */
17043 log: function() {
17044 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) try {
17045 windowConsole.log.apply(windowConsole, arguments);
17046 } catch (err) {
17047 _$1.each(arguments, function(arg) {
17048 windowConsole.log(arg);
17049 });
17050 }
17051 },
17052 /** @type {function(...*)} */
17053 warn: function() {
17054 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) {
17055 var args = ["Mixpanel warning:"].concat(_$1.toArray(arguments));
17056 try {
17057 windowConsole.warn.apply(windowConsole, args);
17058 } catch (err) {
17059 _$1.each(args, function(arg) {
17060 windowConsole.warn(arg);
17061 });
17062 }
17063 }
17064 },
17065 /** @type {function(...*)} */
17066 error: function() {
17067 if (Config.DEBUG && !_$1.isUndefined(windowConsole) && windowConsole) {
17068 var args = ["Mixpanel error:"].concat(_$1.toArray(arguments));
17069 try {
17070 windowConsole.error.apply(windowConsole, args);
17071 } catch (err) {
17072 _$1.each(args, function(arg) {
17073 windowConsole.error(arg);
17074 });
17075 }
17076 }
17077 },
17078 /** @type {function(...*)} */
17079 critical: function() {
17080 if (!_$1.isUndefined(windowConsole) && windowConsole) {
17081 var args = ["Mixpanel error:"].concat(_$1.toArray(arguments));
17082 try {
17083 windowConsole.error.apply(windowConsole, args);
17084 } catch (err) {
17085 _$1.each(args, function(arg) {
17086 windowConsole.error(arg);
17087 });
17088 }
17089 }
17090 }
17091 };
17092 var log_func_with_prefix = function(func, prefix) {
17093 return function() {
17094 arguments[0] = "[" + prefix + "] " + arguments[0];
17095 return func.apply(console$1, arguments);
17096 };
17097 };
17098 var console_with_prefix = function(prefix) {
17099 return {
17100 log: log_func_with_prefix(console$1.log, prefix),
17101 error: log_func_with_prefix(console$1.error, prefix),
17102 critical: log_func_with_prefix(console$1.critical, prefix)
17103 };
17104 };
17105 var safewrap = function(f) {
17106 return function() {
17107 try {
17108 return f.apply(this, arguments);
17109 } catch (e) {
17110 console$1.critical("Implementation error. Please turn on debug and contact support@mixpanel.com.");
17111 if (Config.DEBUG) console$1.critical(e);
17112 }
17113 };
17114 };
17115 var safewrapClass = function(klass) {
17116 var proto = klass.prototype;
17117 for (var func in proto) if (typeof proto[func] === "function") proto[func] = safewrap(proto[func]);
17118 };
17119 _$1.bind = function(func, context) {
17120 var args;
17121 var bound;
17122 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
17123 if (!_$1.isFunction(func)) throw new TypeError();
17124 args = slice.call(arguments, 2);
17125 bound = function() {
17126 if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
17127 var ctor = {};
17128 ctor.prototype = func.prototype;
17129 var self = new ctor();
17130 ctor.prototype = null;
17131 var result = func.apply(self, args.concat(slice.call(arguments)));
17132 if (Object(result) === result) return result;
17133 return self;
17134 };
17135 return bound;
17136 };
17137 /**
17138 * @param {*=} obj
17139 * @param {function(...*)=} iterator
17140 * @param {Object=} context
17141 */
17142 _$1.each = function(obj, iterator, context) {
17143 if (obj === null || obj === void 0) return;
17144 if (nativeForEach && obj.forEach === nativeForEach) obj.forEach(iterator, context);
17145 else if (obj.length === +obj.length) {
17146 for (var i = 0, l = obj.length; i < l; i++) if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
17147 } else for (var key in obj) if (hasOwnProperty.call(obj, key)) {
17148 if (iterator.call(context, obj[key], key, obj) === breaker) return;
17149 }
17150 };
17151 _$1.extend = function(obj) {
17152 _$1.each(slice.call(arguments, 1), function(source) {
17153 for (var prop in source) if (source[prop] !== void 0) obj[prop] = source[prop];
17154 });
17155 return obj;
17156 };
17157 _$1.isArray = nativeIsArray || function(obj) {
17158 return toString.call(obj) === "[object Array]";
17159 };
17160 _$1.isFunction = function(f) {
17161 try {
17162 return /^\s*\bfunction\b/.test(f);
17163 } catch (x) {
17164 return false;
17165 }
17166 };
17167 _$1.isArguments = function(obj) {
17168 return !!(obj && hasOwnProperty.call(obj, "callee"));
17169 };
17170 _$1.toArray = function(iterable) {
17171 if (!iterable) return [];
17172 if (iterable.toArray) return iterable.toArray();
17173 if (_$1.isArray(iterable)) return slice.call(iterable);
17174 if (_$1.isArguments(iterable)) return slice.call(iterable);
17175 return _$1.values(iterable);
17176 };
17177 _$1.map = function(arr, callback, context) {
17178 if (nativeMap && arr.map === nativeMap) return arr.map(callback, context);
17179 else {
17180 var results = [];
17181 _$1.each(arr, function(item) {
17182 results.push(callback.call(context, item));
17183 });
17184 return results;
17185 }
17186 };
17187 _$1.keys = function(obj) {
17188 var results = [];
17189 if (obj === null) return results;
17190 _$1.each(obj, function(value, key) {
17191 results[results.length] = key;
17192 });
17193 return results;
17194 };
17195 _$1.values = function(obj) {
17196 var results = [];
17197 if (obj === null) return results;
17198 _$1.each(obj, function(value) {
17199 results[results.length] = value;
17200 });
17201 return results;
17202 };
17203 _$1.include = function(obj, target) {
17204 var found = false;
17205 if (obj === null) return found;
17206 if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
17207 _$1.each(obj, function(value) {
17208 if (found || (found = value === target)) return breaker;
17209 });
17210 return found;
17211 };
17212 _$1.includes = function(str, needle) {
17213 return str.indexOf(needle) !== -1;
17214 };
17215 _$1.inherit = function(subclass, superclass) {
17216 subclass.prototype = new superclass();
17217 subclass.prototype.constructor = subclass;
17218 subclass.superclass = superclass.prototype;
17219 return subclass;
17220 };
17221 _$1.isObject = function(obj) {
17222 return obj === Object(obj) && !_$1.isArray(obj);
17223 };
17224 _$1.isEmptyObject = function(obj) {
17225 if (_$1.isObject(obj)) {
17226 for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
17227 return true;
17228 }
17229 return false;
17230 };
17231 _$1.isUndefined = function(obj) {
17232 return obj === void 0;
17233 };
17234 _$1.isString = function(obj) {
17235 return toString.call(obj) == "[object String]";
17236 };
17237 _$1.isDate = function(obj) {
17238 return toString.call(obj) == "[object Date]";
17239 };
17240 _$1.isNumber = function(obj) {
17241 return toString.call(obj) == "[object Number]";
17242 };
17243 _$1.isElement = function(obj) {
17244 return !!(obj && obj.nodeType === 1);
17245 };
17246 _$1.encodeDates = function(obj) {
17247 _$1.each(obj, function(v, k) {
17248 if (_$1.isDate(v)) obj[k] = _$1.formatDate(v);
17249 else if (_$1.isObject(v)) obj[k] = _$1.encodeDates(v);
17250 });
17251 return obj;
17252 };
17253 _$1.timestamp = function() {
17254 Date.now = Date.now || function() {
17255 return +/* @__PURE__ */ new Date();
17256 };
17257 return Date.now();
17258 };
17259 _$1.formatDate = function(d) {
17260 function pad(n) {
17261 return n < 10 ? "0" + n : n;
17262 }
17263 return d.getUTCFullYear() + "-" + pad(d.getUTCMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes()) + ":" + pad(d.getUTCSeconds());
17264 };
17265 _$1.strip_empty_properties = function(p) {
17266 var ret = {};
17267 _$1.each(p, function(v, k) {
17268 if (_$1.isString(v) && v.length > 0) ret[k] = v;
17269 });
17270 return ret;
17271 };
17272 _$1.truncate = function(obj, length) {
17273 var ret;
17274 if (typeof obj === "string") ret = obj.slice(0, length);
17275 else if (_$1.isArray(obj)) {
17276 ret = [];
17277 _$1.each(obj, function(val) {
17278 ret.push(_$1.truncate(val, length));
17279 });
17280 } else if (_$1.isObject(obj)) {
17281 ret = {};
17282 _$1.each(obj, function(val, key) {
17283 ret[key] = _$1.truncate(val, length);
17284 });
17285 } else ret = obj;
17286 return ret;
17287 };
17288 _$1.JSONEncode = (function() {
17289 return function(mixed_val) {
17290 var value = mixed_val;
17291 var quote = function(string) {
17292 var escapable = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
17293 var meta = {
17294 "\b": "\\b",
17295 " ": "\\t",
17296 "\n": "\\n",
17297 "\f": "\\f",
17298 "\r": "\\r",
17299 "\"": "\\\"",
17300 "\\": "\\\\"
17301 };
17302 escapable.lastIndex = 0;
17303 return escapable.test(string) ? "\"" + string.replace(escapable, function(a) {
17304 var c = meta[a];
17305 return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
17306 }) + "\"" : "\"" + string + "\"";
17307 };
17308 var str = function(key, holder) {
17309 var gap = "";
17310 var indent = " ";
17311 var i = 0;
17312 var k = "";
17313 var v = "";
17314 var length = 0;
17315 var mind = gap;
17316 var partial = [];
17317 var value = holder[key];
17318 if (value && typeof value === "object" && typeof value.toJSON === "function") value = value.toJSON(key);
17319 switch (typeof value) {
17320 case "string": return quote(value);
17321 case "number": return isFinite(value) ? String(value) : "null";
17322 case "boolean":
17323 case "null": return String(value);
17324 case "object":
17325 if (!value) return "null";
17326 gap += indent;
17327 partial = [];
17328 if (toString.apply(value) === "[object Array]") {
17329 length = value.length;
17330 for (i = 0; i < length; i += 1) partial[i] = str(i, value) || "null";
17331 v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]";
17332 gap = mind;
17333 return v;
17334 }
17335 for (k in value) if (hasOwnProperty.call(value, k)) {
17336 v = str(k, value);
17337 if (v) partial.push(quote(k) + (gap ? ": " : ":") + v);
17338 }
17339 v = partial.length === 0 ? "{}" : gap ? "{" + partial.join(",") + mind + "}" : "{" + partial.join(",") + "}";
17340 gap = mind;
17341 return v;
17342 }
17343 };
17344 return str("", { "": value });
17345 };
17346 })();
17347 /**
17348 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
17349 * Slightly modified to throw a real Error rather than a POJO
17350 */
17351 _$1.JSONDecode = (function() {
17352 var at;
17353 var ch;
17354 var escapee = {
17355 "\"": "\"",
17356 "\\": "\\",
17357 "/": "/",
17358 "b": "\b",
17359 "f": "\f",
17360 "n": "\n",
17361 "r": "\r",
17362 "t": " "
17363 };
17364 var text;
17365 var error = function(m) {
17366 var e = new SyntaxError(m);
17367 e.at = at;
17368 e.text = text;
17369 throw e;
17370 };
17371 var next = function(c) {
17372 if (c && c !== ch) error("Expected '" + c + "' instead of '" + ch + "'");
17373 ch = text.charAt(at);
17374 at += 1;
17375 return ch;
17376 };
17377 var number = function() {
17378 var number;
17379 var string = "";
17380 if (ch === "-") {
17381 string = "-";
17382 next("-");
17383 }
17384 while (ch >= "0" && ch <= "9") {
17385 string += ch;
17386 next();
17387 }
17388 if (ch === ".") {
17389 string += ".";
17390 while (next() && ch >= "0" && ch <= "9") string += ch;
17391 }
17392 if (ch === "e" || ch === "E") {
17393 string += ch;
17394 next();
17395 if (ch === "-" || ch === "+") {
17396 string += ch;
17397 next();
17398 }
17399 while (ch >= "0" && ch <= "9") {
17400 string += ch;
17401 next();
17402 }
17403 }
17404 number = +string;
17405 if (!isFinite(number)) error("Bad number");
17406 else return number;
17407 };
17408 var string = function() {
17409 var hex;
17410 var i;
17411 var string = "";
17412 var uffff;
17413 if (ch === "\"") while (next()) {
17414 if (ch === "\"") {
17415 next();
17416 return string;
17417 }
17418 if (ch === "\\") {
17419 next();
17420 if (ch === "u") {
17421 uffff = 0;
17422 for (i = 0; i < 4; i += 1) {
17423 hex = parseInt(next(), 16);
17424 if (!isFinite(hex)) break;
17425 uffff = uffff * 16 + hex;
17426 }
17427 string += String.fromCharCode(uffff);
17428 } else if (typeof escapee[ch] === "string") string += escapee[ch];
17429 else break;
17430 } else string += ch;
17431 }
17432 error("Bad string");
17433 };
17434 var white = function() {
17435 while (ch && ch <= " ") next();
17436 };
17437 var word = function() {
17438 switch (ch) {
17439 case "t":
17440 next("t");
17441 next("r");
17442 next("u");
17443 next("e");
17444 return true;
17445 case "f":
17446 next("f");
17447 next("a");
17448 next("l");
17449 next("s");
17450 next("e");
17451 return false;
17452 case "n":
17453 next("n");
17454 next("u");
17455 next("l");
17456 next("l");
17457 return null;
17458 }
17459 error("Unexpected \"" + ch + "\"");
17460 };
17461 var value;
17462 var array = function() {
17463 var array = [];
17464 if (ch === "[") {
17465 next("[");
17466 white();
17467 if (ch === "]") {
17468 next("]");
17469 return array;
17470 }
17471 while (ch) {
17472 array.push(value());
17473 white();
17474 if (ch === "]") {
17475 next("]");
17476 return array;
17477 }
17478 next(",");
17479 white();
17480 }
17481 }
17482 error("Bad array");
17483 };
17484 var object = function() {
17485 var key;
17486 var object = {};
17487 if (ch === "{") {
17488 next("{");
17489 white();
17490 if (ch === "}") {
17491 next("}");
17492 return object;
17493 }
17494 while (ch) {
17495 key = string();
17496 white();
17497 next(":");
17498 if (Object.hasOwnProperty.call(object, key)) error("Duplicate key \"" + key + "\"");
17499 object[key] = value();
17500 white();
17501 if (ch === "}") {
17502 next("}");
17503 return object;
17504 }
17505 next(",");
17506 white();
17507 }
17508 }
17509 error("Bad object");
17510 };
17511 value = function() {
17512 white();
17513 switch (ch) {
17514 case "{": return object();
17515 case "[": return array();
17516 case "\"": return string();
17517 case "-": return number();
17518 default: return ch >= "0" && ch <= "9" ? number() : word();
17519 }
17520 };
17521 return function(source) {
17522 var result;
17523 text = source;
17524 at = 0;
17525 ch = " ";
17526 result = value();
17527 white();
17528 if (ch) error("Syntax error");
17529 return result;
17530 };
17531 })();
17532 _$1.base64Encode = function(data) {
17533 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17534 var o1;
17535 var o2;
17536 var o3;
17537 var h1;
17538 var h2;
17539 var h3;
17540 var h4;
17541 var bits;
17542 var i = 0;
17543 var ac = 0;
17544 var enc = "";
17545 var tmp_arr = [];
17546 if (!data) return data;
17547 data = _$1.utf8Encode(data);
17548 do {
17549 o1 = data.charCodeAt(i++);
17550 o2 = data.charCodeAt(i++);
17551 o3 = data.charCodeAt(i++);
17552 bits = o1 << 16 | o2 << 8 | o3;
17553 h1 = bits >> 18 & 63;
17554 h2 = bits >> 12 & 63;
17555 h3 = bits >> 6 & 63;
17556 h4 = bits & 63;
17557 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
17558 } while (i < data.length);
17559 enc = tmp_arr.join("");
17560 switch (data.length % 3) {
17561 case 1:
17562 enc = enc.slice(0, -2) + "==";
17563 break;
17564 case 2:
17565 enc = enc.slice(0, -1) + "=";
17566 break;
17567 }
17568 return enc;
17569 };
17570 _$1.utf8Encode = function(string) {
17571 string = (string + "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
17572 var utftext = "";
17573 var start;
17574 var end;
17575 var stringl = 0;
17576 var n;
17577 start = end = 0;
17578 stringl = string.length;
17579 for (n = 0; n < stringl; n++) {
17580 var c1 = string.charCodeAt(n);
17581 var enc = null;
17582 if (c1 < 128) end++;
17583 else if (c1 > 127 && c1 < 2048) enc = String.fromCharCode(c1 >> 6 | 192, c1 & 63 | 128);
17584 else enc = String.fromCharCode(c1 >> 12 | 224, c1 >> 6 & 63 | 128, c1 & 63 | 128);
17585 if (enc !== null) {
17586 if (end > start) utftext += string.substring(start, end);
17587 utftext += enc;
17588 start = end = n + 1;
17589 }
17590 }
17591 if (end > start) utftext += string.substring(start, string.length);
17592 return utftext;
17593 };
17594 _$1.UUID = function() {
17595 try {
17596 return win["crypto"]["randomUUID"]();
17597 } catch (err) {
17598 var uuid = new Array(36);
17599 for (var i = 0; i < 36; i++) uuid[i] = Math.floor(Math.random() * 16);
17600 uuid[14] = 4;
17601 uuid[19] = uuid[19] &= -5;
17602 uuid[19] = uuid[19] |= 8;
17603 uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
17604 return _$1.map(uuid, function(x) {
17605 return x.toString(16);
17606 }).join("");
17607 }
17608 };
17609 var BLOCKED_UA_STRS = [
17610 "ahrefsbot",
17611 "ahrefssiteaudit",
17612 "amazonbot",
17613 "baiduspider",
17614 "bingbot",
17615 "bingpreview",
17616 "chrome-lighthouse",
17617 "facebookexternal",
17618 "petalbot",
17619 "pinterest",
17620 "screaming frog",
17621 "yahoo! slurp",
17622 "yandex",
17623 "adsbot-google",
17624 "apis-google",
17625 "duplexweb-google",
17626 "feedfetcher-google",
17627 "google favicon",
17628 "google web preview",
17629 "google-read-aloud",
17630 "googlebot",
17631 "googleweblight",
17632 "mediapartners-google",
17633 "storebot-google"
17634 ];
17635 _$1.isBlockedUA = function(ua) {
17636 var i;
17637 ua = ua.toLowerCase();
17638 for (i = 0; i < BLOCKED_UA_STRS.length; i++) if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) return true;
17639 return false;
17640 };
17641 /**
17642 * @param {Object=} formdata
17643 * @param {string=} arg_separator
17644 */
17645 _$1.HTTPBuildQuery = function(formdata, arg_separator) {
17646 var use_val;
17647 var use_key;
17648 var tmp_arr = [];
17649 if (_$1.isUndefined(arg_separator)) arg_separator = "&";
17650 _$1.each(formdata, function(val, key) {
17651 use_val = encodeURIComponent(val.toString());
17652 use_key = encodeURIComponent(key);
17653 tmp_arr[tmp_arr.length] = use_key + "=" + use_val;
17654 });
17655 return tmp_arr.join(arg_separator);
17656 };
17657 _$1.getQueryParam = function(url, param) {
17658 param = param.replace(/[[]/g, "\\[").replace(/[\]]/g, "\\]");
17659 var regexS = "[\\?&]" + param + "=([^&#]*)";
17660 var results = new RegExp(regexS).exec(url);
17661 if (results === null || results && typeof results[1] !== "string" && results[1].length) return "";
17662 else {
17663 var result = results[1];
17664 try {
17665 result = decodeURIComponent(result);
17666 } catch (err) {
17667 console$1.error("Skipping decoding for malformed query param: " + result);
17668 }
17669 return result.replace(/\+/g, " ");
17670 }
17671 };
17672 _$1.cookie = {
17673 get: function(name) {
17674 var nameEQ = name + "=";
17675 var ca = document$1.cookie.split(";");
17676 for (var i = 0; i < ca.length; i++) {
17677 var c = ca[i];
17678 while (c.charAt(0) == " ") c = c.substring(1, c.length);
17679 if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
17680 }
17681 return null;
17682 },
17683 parse: function(name) {
17684 var cookie;
17685 try {
17686 cookie = _$1.JSONDecode(_$1.cookie.get(name)) || {};
17687 } catch (err) {}
17688 return cookie;
17689 },
17690 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
17691 var cdomain = "";
17692 var expires = "";
17693 var secure = "";
17694 if (domain_override) cdomain = "; domain=" + domain_override;
17695 else if (is_cross_subdomain) {
17696 var domain = extract_domain(document$1.location.hostname);
17697 cdomain = domain ? "; domain=." + domain : "";
17698 }
17699 if (seconds) {
17700 var date = /* @__PURE__ */ new Date();
17701 date.setTime(date.getTime() + seconds * 1e3);
17702 expires = "; expires=" + date.toGMTString();
17703 }
17704 if (is_cross_site) {
17705 is_secure = true;
17706 secure = "; SameSite=None";
17707 }
17708 if (is_secure) secure += "; secure";
17709 document$1.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/" + cdomain + secure;
17710 },
17711 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
17712 var cdomain = "";
17713 var expires = "";
17714 var secure = "";
17715 if (domain_override) cdomain = "; domain=" + domain_override;
17716 else if (is_cross_subdomain) {
17717 var domain = extract_domain(document$1.location.hostname);
17718 cdomain = domain ? "; domain=." + domain : "";
17719 }
17720 if (days) {
17721 var date = /* @__PURE__ */ new Date();
17722 date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
17723 expires = "; expires=" + date.toGMTString();
17724 }
17725 if (is_cross_site) {
17726 is_secure = true;
17727 secure = "; SameSite=None";
17728 }
17729 if (is_secure) secure += "; secure";
17730 var new_cookie_val = name + "=" + encodeURIComponent(value) + expires + "; path=/" + cdomain + secure;
17731 document$1.cookie = new_cookie_val;
17732 return new_cookie_val;
17733 },
17734 remove: function(name, is_cross_subdomain, domain_override) {
17735 _$1.cookie.set(name, "", -1, is_cross_subdomain, false, false, domain_override);
17736 }
17737 };
17738 var _testStorageSupported = function(storage) {
17739 var supported = true;
17740 try {
17741 var key = "__mplss_" + cheap_guid(8);
17742 var val = "xyz";
17743 storage.setItem(key, val);
17744 if (storage.getItem(key) !== val) supported = false;
17745 storage.removeItem(key);
17746 } catch (err) {
17747 supported = false;
17748 }
17749 return supported;
17750 };
17751 var _localStorageSupported = null;
17752 var localStorageSupported = function(storage, forceCheck) {
17753 if (_localStorageSupported !== null && !forceCheck) return _localStorageSupported;
17754 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
17755 };
17756 var _sessionStorageSupported = null;
17757 var sessionStorageSupported = function(storage, forceCheck) {
17758 if (_sessionStorageSupported !== null && !forceCheck) return _sessionStorageSupported;
17759 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
17760 };
17761 function _storageWrapper(storage, name, is_supported_fn) {
17762 var log_error = function(msg) {
17763 console$1.error(name + " error: " + msg);
17764 };
17765 return {
17766 is_supported: function(forceCheck) {
17767 var supported = is_supported_fn(storage, forceCheck);
17768 if (!supported) console$1.error(name + " unsupported");
17769 return supported;
17770 },
17771 error: log_error,
17772 get: function(key) {
17773 try {
17774 return storage.getItem(key);
17775 } catch (err) {
17776 log_error(err);
17777 }
17778 return null;
17779 },
17780 parse: function(key) {
17781 try {
17782 return _$1.JSONDecode(storage.getItem(key)) || {};
17783 } catch (err) {}
17784 return null;
17785 },
17786 set: function(key, value) {
17787 try {
17788 storage.setItem(key, value);
17789 } catch (err) {
17790 log_error(err);
17791 }
17792 },
17793 remove: function(key) {
17794 try {
17795 storage.removeItem(key);
17796 } catch (err) {
17797 log_error(err);
17798 }
17799 }
17800 };
17801 }
17802 _$1.localStorage = _storageWrapper(win.localStorage, "localStorage", localStorageSupported);
17803 _$1.sessionStorage = _storageWrapper(win.sessionStorage, "sessionStorage", sessionStorageSupported);
17804 _$1.register_event = (function() {
17805 /**
17806 * @param {Object} element
17807 * @param {string} type
17808 * @param {function(...*)} handler
17809 * @param {boolean=} oldSchool
17810 * @param {boolean=} useCapture
17811 */
17812 var register_event = function(element, type, handler, oldSchool, useCapture) {
17813 if (!element) {
17814 console$1.error("No valid element provided to register_event");
17815 return;
17816 }
17817 if (element.addEventListener && !oldSchool) element.addEventListener(type, handler, !!useCapture);
17818 else {
17819 var ontype = "on" + type;
17820 var old_handler = element[ontype];
17821 element[ontype] = makeHandler(element, handler, old_handler);
17822 }
17823 };
17824 function makeHandler(element, new_handler, old_handlers) {
17825 var handler = function(event) {
17826 event = event || fixEvent(win.event);
17827 if (!event) return;
17828 var ret = true;
17829 var old_result;
17830 var new_result;
17831 if (_$1.isFunction(old_handlers)) old_result = old_handlers(event);
17832 new_result = new_handler.call(element, event);
17833 if (false === old_result || false === new_result) ret = false;
17834 return ret;
17835 };
17836 return handler;
17837 }
17838 function fixEvent(event) {
17839 if (event) {
17840 event.preventDefault = fixEvent.preventDefault;
17841 event.stopPropagation = fixEvent.stopPropagation;
17842 }
17843 return event;
17844 }
17845 fixEvent.preventDefault = function() {
17846 this.returnValue = false;
17847 };
17848 fixEvent.stopPropagation = function() {
17849 this.cancelBubble = true;
17850 };
17851 return register_event;
17852 })();
17853 var TOKEN_MATCH_REGEX = /* @__PURE__ */ new RegExp("^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?\"?([^\\]\"]*)\"?\\]$");
17854 _$1.dom_query = (function() {
17855 function getAllChildren(e) {
17856 return e.all ? e.all : e.getElementsByTagName("*");
17857 }
17858 var bad_whitespace = /[\t\r\n]/g;
17859 function hasClass(elem, selector) {
17860 var className = " " + selector + " ";
17861 return (" " + elem.className + " ").replace(bad_whitespace, " ").indexOf(className) >= 0;
17862 }
17863 function getElementsBySelector(selector) {
17864 if (!document$1.getElementsByTagName) return [];
17865 var tokens = selector.split(" ");
17866 var token;
17867 var bits;
17868 var tagName;
17869 var found;
17870 var foundCount;
17871 var i;
17872 var j;
17873 var k;
17874 var elements;
17875 var currentContextIndex;
17876 var currentContext = [document$1];
17877 for (i = 0; i < tokens.length; i++) {
17878 token = tokens[i].replace(/^\s+/, "").replace(/\s+$/, "");
17879 if (token.indexOf("#") > -1) {
17880 bits = token.split("#");
17881 tagName = bits[0];
17882 var id = bits[1];
17883 var element = document$1.getElementById(id);
17884 if (!element || tagName && element.nodeName.toLowerCase() != tagName) return [];
17885 currentContext = [element];
17886 continue;
17887 }
17888 if (token.indexOf(".") > -1) {
17889 bits = token.split(".");
17890 tagName = bits[0];
17891 var className = bits[1];
17892 if (!tagName) tagName = "*";
17893 found = [];
17894 foundCount = 0;
17895 for (j = 0; j < currentContext.length; j++) {
17896 if (tagName == "*") elements = getAllChildren(currentContext[j]);
17897 else elements = currentContext[j].getElementsByTagName(tagName);
17898 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
17899 }
17900 currentContext = [];
17901 currentContextIndex = 0;
17902 for (j = 0; j < found.length; j++) if (found[j].className && _$1.isString(found[j].className) && hasClass(found[j], className)) currentContext[currentContextIndex++] = found[j];
17903 continue;
17904 }
17905 var token_match = token.match(TOKEN_MATCH_REGEX);
17906 if (token_match) {
17907 tagName = token_match[1];
17908 var attrName = token_match[2];
17909 var attrOperator = token_match[3];
17910 var attrValue = token_match[4];
17911 if (!tagName) tagName = "*";
17912 found = [];
17913 foundCount = 0;
17914 for (j = 0; j < currentContext.length; j++) {
17915 if (tagName == "*") elements = getAllChildren(currentContext[j]);
17916 else elements = currentContext[j].getElementsByTagName(tagName);
17917 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
17918 }
17919 currentContext = [];
17920 currentContextIndex = 0;
17921 var checkFunction;
17922 switch (attrOperator) {
17923 case "=":
17924 checkFunction = function(e) {
17925 return e.getAttribute(attrName) == attrValue;
17926 };
17927 break;
17928 case "~":
17929 checkFunction = function(e) {
17930 return e.getAttribute(attrName).match(new RegExp("\\b" + attrValue + "\\b"));
17931 };
17932 break;
17933 case "|":
17934 checkFunction = function(e) {
17935 return e.getAttribute(attrName).match(new RegExp("^" + attrValue + "-?"));
17936 };
17937 break;
17938 case "^":
17939 checkFunction = function(e) {
17940 return e.getAttribute(attrName).indexOf(attrValue) === 0;
17941 };
17942 break;
17943 case "$":
17944 checkFunction = function(e) {
17945 return e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length;
17946 };
17947 break;
17948 case "*":
17949 checkFunction = function(e) {
17950 return e.getAttribute(attrName).indexOf(attrValue) > -1;
17951 };
17952 break;
17953 default: checkFunction = function(e) {
17954 return e.getAttribute(attrName);
17955 };
17956 }
17957 currentContext = [];
17958 currentContextIndex = 0;
17959 for (j = 0; j < found.length; j++) if (checkFunction(found[j])) currentContext[currentContextIndex++] = found[j];
17960 continue;
17961 }
17962 tagName = token;
17963 found = [];
17964 foundCount = 0;
17965 for (j = 0; j < currentContext.length; j++) {
17966 elements = currentContext[j].getElementsByTagName(tagName);
17967 for (k = 0; k < elements.length; k++) found[foundCount++] = elements[k];
17968 }
17969 currentContext = found;
17970 }
17971 return currentContext;
17972 }
17973 return function(query) {
17974 if (_$1.isElement(query)) return [query];
17975 else if (_$1.isObject(query) && !_$1.isUndefined(query.length)) return query;
17976 else return getElementsBySelector.call(this, query);
17977 };
17978 })();
17979 var CAMPAIGN_KEYWORDS = [
17980 "utm_source",
17981 "utm_medium",
17982 "utm_campaign",
17983 "utm_content",
17984 "utm_term",
17985 "utm_id",
17986 "utm_source_platform",
17987 "utm_campaign_id",
17988 "utm_creative_format",
17989 "utm_marketing_tactic"
17990 ];
17991 var CLICK_IDS = [
17992 "dclid",
17993 "fbclid",
17994 "gclid",
17995 "ko_click_id",
17996 "li_fat_id",
17997 "msclkid",
17998 "sccid",
17999 "ttclid",
18000 "twclid",
18001 "wbraid"
18002 ];
18003 _$1.info = {
18004 campaignParams: function(default_value) {
18005 var kw = "";
18006 var params = {};
18007 _$1.each(CAMPAIGN_KEYWORDS, function(kwkey) {
18008 kw = _$1.getQueryParam(document$1.URL, kwkey);
18009 if (kw.length) params[kwkey] = kw;
18010 else if (default_value !== void 0) params[kwkey] = default_value;
18011 });
18012 return params;
18013 },
18014 clickParams: function() {
18015 var id = "";
18016 var params = {};
18017 _$1.each(CLICK_IDS, function(idkey) {
18018 id = _$1.getQueryParam(document$1.URL, idkey);
18019 if (id.length) params[idkey] = id;
18020 });
18021 return params;
18022 },
18023 marketingParams: function() {
18024 return _$1.extend(_$1.info.campaignParams(), _$1.info.clickParams());
18025 },
18026 searchEngine: function(referrer) {
18027 if (referrer.search("https?://(.*)google.([^/?]*)") === 0) return "google";
18028 else if (referrer.search("https?://(.*)bing.com") === 0) return "bing";
18029 else if (referrer.search("https?://(.*)yahoo.com") === 0) return "yahoo";
18030 else if (referrer.search("https?://(.*)duckduckgo.com") === 0) return "duckduckgo";
18031 else return null;
18032 },
18033 searchInfo: function(referrer) {
18034 var search = _$1.info.searchEngine(referrer);
18035 var param = search != "yahoo" ? "q" : "p";
18036 var ret = {};
18037 if (search !== null) {
18038 ret["$search_engine"] = search;
18039 var keyword = _$1.getQueryParam(referrer, param);
18040 if (keyword.length) ret["mp_keyword"] = keyword;
18041 }
18042 return ret;
18043 },
18044 /**
18045 * This function detects which browser is running this script.
18046 * The order of the checks are important since many user agents
18047 * include key words used in later checks.
18048 */
18049 browser: function(user_agent, vendor, opera) {
18050 vendor = vendor || "";
18051 if (opera || _$1.includes(user_agent, " OPR/")) {
18052 if (_$1.includes(user_agent, "Mini")) return "Opera Mini";
18053 return "Opera";
18054 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) return "BlackBerry";
18055 else if (_$1.includes(user_agent, "IEMobile") || _$1.includes(user_agent, "WPDesktop")) return "Internet Explorer Mobile";
18056 else if (_$1.includes(user_agent, "SamsungBrowser/")) return "Samsung Internet";
18057 else if (_$1.includes(user_agent, "Edge") || _$1.includes(user_agent, "Edg/")) return "Microsoft Edge";
18058 else if (_$1.includes(user_agent, "FBIOS")) return "Facebook Mobile";
18059 else if (_$1.includes(user_agent, "Whale/")) return "Whale Browser";
18060 else if (_$1.includes(user_agent, "Chrome")) return "Chrome";
18061 else if (_$1.includes(user_agent, "CriOS")) return "Chrome iOS";
18062 else if (_$1.includes(user_agent, "UCWEB") || _$1.includes(user_agent, "UCBrowser")) return "UC Browser";
18063 else if (_$1.includes(user_agent, "FxiOS")) return "Firefox iOS";
18064 else if (_$1.includes(vendor, "Apple")) {
18065 if (_$1.includes(user_agent, "Mobile")) return "Mobile Safari";
18066 return "Safari";
18067 } else if (_$1.includes(user_agent, "Android")) return "Android Mobile";
18068 else if (_$1.includes(user_agent, "Konqueror")) return "Konqueror";
18069 else if (_$1.includes(user_agent, "Firefox")) return "Firefox";
18070 else if (_$1.includes(user_agent, "MSIE") || _$1.includes(user_agent, "Trident/")) return "Internet Explorer";
18071 else if (_$1.includes(user_agent, "Gecko")) return "Mozilla";
18072 else return "";
18073 },
18074 /**
18075 * This function detects which browser version is running this script,
18076 * parsing major and minor version (e.g., 42.1). User agent strings from:
18077 * http://www.useragentstring.com/pages/useragentstring.php
18078 */
18079 browserVersion: function(userAgent, vendor, opera) {
18080 var regex = {
18081 "Internet Explorer Mobile": /rv:(\d+(\.\d+)?)/,
18082 "Microsoft Edge": /Edge?\/(\d+(\.\d+)?)/,
18083 "Chrome": /Chrome\/(\d+(\.\d+)?)/,
18084 "Chrome iOS": /CriOS\/(\d+(\.\d+)?)/,
18085 "UC Browser": /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
18086 "Safari": /Version\/(\d+(\.\d+)?)/,
18087 "Mobile Safari": /Version\/(\d+(\.\d+)?)/,
18088 "Opera": /(Opera|OPR)\/(\d+(\.\d+)?)/,
18089 "Firefox": /Firefox\/(\d+(\.\d+)?)/,
18090 "Firefox iOS": /FxiOS\/(\d+(\.\d+)?)/,
18091 "Konqueror": /Konqueror:(\d+(\.\d+)?)/,
18092 "BlackBerry": /BlackBerry (\d+(\.\d+)?)/,
18093 "Android Mobile": /android\s(\d+(\.\d+)?)/,
18094 "Samsung Internet": /SamsungBrowser\/(\d+(\.\d+)?)/,
18095 "Internet Explorer": /(rv:|MSIE )(\d+(\.\d+)?)/,
18096 "Mozilla": /rv:(\d+(\.\d+)?)/,
18097 "Whale Browser": /Whale\/(\d+(\.\d+)?)/
18098 }[_$1.info.browser(userAgent, vendor, opera)];
18099 if (regex === void 0) return null;
18100 var matches = userAgent.match(regex);
18101 if (!matches) return null;
18102 return parseFloat(matches[matches.length - 2]);
18103 },
18104 os: function() {
18105 var a = userAgent;
18106 if (/Windows/i.test(a)) {
18107 if (/Phone/.test(a) || /WPDesktop/.test(a)) return "Windows Phone";
18108 return "Windows";
18109 } else if (/(iPhone|iPad|iPod)/.test(a)) return "iOS";
18110 else if (/Android/.test(a)) return "Android";
18111 else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) return "BlackBerry";
18112 else if (/Mac/i.test(a)) return "Mac OS X";
18113 else if (/Linux/.test(a)) return "Linux";
18114 else if (/CrOS/.test(a)) return "Chrome OS";
18115 else return "";
18116 },
18117 device: function(user_agent) {
18118 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) return "Windows Phone";
18119 else if (/iPad/.test(user_agent)) return "iPad";
18120 else if (/iPod/.test(user_agent)) return "iPod Touch";
18121 else if (/iPhone/.test(user_agent)) return "iPhone";
18122 else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) return "BlackBerry";
18123 else if (/Android/.test(user_agent)) return "Android";
18124 else return "";
18125 },
18126 referringDomain: function(referrer) {
18127 var split = referrer.split("/");
18128 if (split.length >= 3) return split[2];
18129 return "";
18130 },
18131 currentUrl: function() {
18132 return win.location.href;
18133 },
18134 properties: function(extra_props) {
18135 if (typeof extra_props !== "object") extra_props = {};
18136 return _$1.extend(_$1.strip_empty_properties({
18137 "$os": _$1.info.os(),
18138 "$browser": _$1.info.browser(userAgent, navigator.vendor, windowOpera),
18139 "$referrer": document$1.referrer,
18140 "$referring_domain": _$1.info.referringDomain(document$1.referrer),
18141 "$device": _$1.info.device(userAgent)
18142 }), {
18143 "$current_url": _$1.info.currentUrl(),
18144 "$browser_version": _$1.info.browserVersion(userAgent, navigator.vendor, windowOpera),
18145 "$screen_height": screen.height,
18146 "$screen_width": screen.width,
18147 "mp_lib": "web",
18148 "$lib_version": Config.LIB_VERSION,
18149 "$insert_id": cheap_guid(),
18150 "time": _$1.timestamp() / 1e3
18151 }, _$1.strip_empty_properties(extra_props));
18152 },
18153 people_properties: function() {
18154 return _$1.extend(_$1.strip_empty_properties({
18155 "$os": _$1.info.os(),
18156 "$browser": _$1.info.browser(userAgent, navigator.vendor, windowOpera)
18157 }), { "$browser_version": _$1.info.browserVersion(userAgent, navigator.vendor, windowOpera) });
18158 },
18159 mpPageViewProperties: function() {
18160 return _$1.strip_empty_properties({
18161 "current_page_title": document$1.title,
18162 "current_domain": win.location.hostname,
18163 "current_url_path": win.location.pathname,
18164 "current_url_protocol": win.location.protocol,
18165 "current_url_search": win.location.search
18166 });
18167 }
18168 };
18169 /**
18170 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
18171 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
18172 */
18173 var batchedThrottle = function(fn, waitMs) {
18174 var timeoutPromise = null;
18175 var throttledItems = [];
18176 return function(item) {
18177 var self = this;
18178 throttledItems.push(item);
18179 if (!timeoutPromise) timeoutPromise = new PromisePolyfill(function(resolve) {
18180 setTimeout(function() {
18181 var returnValue = fn.apply(self, [throttledItems]);
18182 timeoutPromise = null;
18183 throttledItems = [];
18184 resolve(returnValue);
18185 }, waitMs);
18186 });
18187 return timeoutPromise;
18188 };
18189 };
18190 var cheap_guid = function(maxlen) {
18191 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
18192 return maxlen ? guid.substring(0, maxlen) : guid;
18193 };
18194 /**
18195 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
18196 * https://www.w3.org/TR/trace-context/#traceparent-header
18197 */
18198 var generateTraceparent = function() {
18199 var traceID = _$1.UUID().replace(/-/g, "");
18200 var parentID = _$1.UUID().replace(/-/g, "").substring(0, 16);
18201 return "00-" + traceID + "-" + parentID + "-01";
18202 };
18203 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
18204 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
18205 /**
18206 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
18207 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
18208 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
18209 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
18210 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
18211 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
18212 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
18213 * offers the 'cookie_domain' config option to set it explicitly.
18214 * @example
18215 * extract_domain('my.sub.example.com')
18216 * // 'example.com'
18217 */
18218 var extract_domain = function(hostname) {
18219 var domain_regex = DOMAIN_MATCH_REGEX;
18220 var parts = hostname.split(".");
18221 var tld = parts[parts.length - 1];
18222 if (tld.length > 4 || tld === "com" || tld === "org") domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
18223 var matches = hostname.match(domain_regex);
18224 return matches ? matches[0] : "";
18225 };
18226 /**
18227 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
18228 * @returns {boolean}
18229 */
18230 var isOnline = function() {
18231 var onLine = win.navigator["onLine"];
18232 return _$1.isUndefined(onLine) || onLine;
18233 };
18234 var NOOP_FUNC = function() {};
18235 var JSONStringify = null;
18236 var JSONParse = null;
18237 if (typeof JSON !== "undefined") {
18238 JSONStringify = JSON.stringify;
18239 JSONParse = JSON.parse;
18240 }
18241 JSONStringify = JSONStringify || _$1.JSONEncode;
18242 JSONParse = JSONParse || _$1.JSONDecode;
18243 _$1["info"] = _$1.info;
18244 _$1["info"]["browser"] = _$1.info.browser;
18245 _$1["info"]["browserVersion"] = _$1.info.browserVersion;
18246 _$1["info"]["device"] = _$1.info.device;
18247 _$1["info"]["properties"] = _$1.info.properties;
18248 _$1["isBlockedUA"] = _$1.isBlockedUA;
18249 _$1["isEmptyObject"] = _$1.isEmptyObject;
18250 _$1["isObject"] = _$1.isObject;
18251 _$1["JSONDecode"] = _$1.JSONDecode;
18252 _$1["JSONEncode"] = _$1.JSONEncode;
18253 _$1["toArray"] = _$1.toArray;
18254 _$1["NPO"] = NpoPromise;
18255 var MIXPANEL_DB_NAME = "mixpanelBrowserDb";
18256 var RECORDING_EVENTS_STORE_NAME = "mixpanelRecordingEvents";
18257 var RECORDING_REGISTRY_STORE_NAME = "mixpanelRecordingRegistry";
18258 var DB_VERSION = 1;
18259 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
18260 /**
18261 * @type {import('./wrapper').StorageWrapper}
18262 */
18263 var IDBStorageWrapper = function(storeName) {
18264 /**
18265 * @type {Promise<IDBDatabase>|null}
18266 */
18267 this.dbPromise = null;
18268 this.storeName = storeName;
18269 };
18270 IDBStorageWrapper.prototype._openDb = function() {
18271 return new PromisePolyfill(function(resolve, reject) {
18272 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
18273 openRequest["onerror"] = function() {
18274 reject(openRequest.error);
18275 };
18276 openRequest["onsuccess"] = function() {
18277 resolve(openRequest.result);
18278 };
18279 openRequest["onupgradeneeded"] = function(ev) {
18280 var db = ev.target.result;
18281 OBJECT_STORES.forEach(function(storeName) {
18282 db.createObjectStore(storeName);
18283 });
18284 };
18285 });
18286 };
18287 IDBStorageWrapper.prototype.init = function() {
18288 if (!win.indexedDB) return PromisePolyfill.reject("indexedDB is not supported in this browser");
18289 if (!this.dbPromise) this.dbPromise = this._openDb();
18290 return this.dbPromise.then(function(dbOrError) {
18291 if (dbOrError instanceof win["IDBDatabase"]) return PromisePolyfill.resolve();
18292 else return PromisePolyfill.reject(dbOrError);
18293 });
18294 };
18295 IDBStorageWrapper.prototype.isInitialized = function() {
18296 return !!this.dbPromise;
18297 };
18298 /**
18299 * @param {IDBTransactionMode} mode
18300 * @param {function(IDBObjectStore): void} storeCb
18301 */
18302 IDBStorageWrapper.prototype.makeTransaction = function(mode, storeCb) {
18303 var storeName = this.storeName;
18304 var doTransaction = function(db) {
18305 return new PromisePolyfill(function(resolve, reject) {
18306 var transaction = db.transaction(storeName, mode);
18307 transaction.oncomplete = function() {
18308 resolve(transaction);
18309 };
18310 transaction.onabort = transaction.onerror = function() {
18311 reject(transaction.error);
18312 };
18313 storeCb(transaction.objectStore(storeName));
18314 });
18315 };
18316 return this.dbPromise.then(doTransaction).catch(function(err) {
18317 if (err && err["name"] === "InvalidStateError") {
18318 this.dbPromise = this._openDb();
18319 return this.dbPromise.then(doTransaction);
18320 } else return PromisePolyfill.reject(err);
18321 }.bind(this));
18322 };
18323 IDBStorageWrapper.prototype.setItem = function(key, value) {
18324 return this.makeTransaction("readwrite", function(objectStore) {
18325 objectStore.put(value, key);
18326 });
18327 };
18328 IDBStorageWrapper.prototype.getItem = function(key) {
18329 var req;
18330 return this.makeTransaction("readonly", function(objectStore) {
18331 req = objectStore.get(key);
18332 }).then(function() {
18333 return req.result;
18334 });
18335 };
18336 IDBStorageWrapper.prototype.removeItem = function(key) {
18337 return this.makeTransaction("readwrite", function(objectStore) {
18338 objectStore.delete(key);
18339 });
18340 };
18341 IDBStorageWrapper.prototype.getAll = function() {
18342 var req;
18343 return this.makeTransaction("readonly", function(objectStore) {
18344 req = objectStore.getAll();
18345 }).then(function() {
18346 return req.result;
18347 });
18348 };
18349 /**
18350 * GDPR utils
18351 *
18352 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
18353 * and privacy for all individuals within the European Union. It addresses the export of personal
18354 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
18355 * over their personal data and to simplify the regulatory environment for international business
18356 * by unifying the regulation within the EU.
18357 *
18358 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
18359 * These functions are used internally by the SDK and are not intended to be publicly exposed.
18360 */
18361 /**
18362 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
18363 * @callback trackFunction
18364 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
18365 * @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.
18366 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
18367 */
18368 /** Public **/
18369 var GDPR_DEFAULT_PERSISTENCE_PREFIX = "__mp_opt_in_out_";
18370 /**
18371 * Opt the user in to data tracking and cookies/localstorage for the given token
18372 * @param {string} token - Mixpanel project tracking token
18373 * @param {Object} [options]
18374 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
18375 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
18376 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
18377 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18378 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18379 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18380 * @param {string} [options.cookieDomain] - custom cookie domain
18381 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18382 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18383 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18384 */
18385 function optIn(token, options) {
18386 _optInOut(true, token, options);
18387 }
18388 /**
18389 * Opt the user out of data tracking and cookies/localstorage for the given token
18390 * @param {string} token - Mixpanel project tracking token
18391 * @param {Object} [options]
18392 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18393 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18394 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
18395 * @param {string} [options.cookieDomain] - custom cookie domain
18396 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18397 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
18398 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
18399 */
18400 function optOut(token, options) {
18401 _optInOut(false, token, options);
18402 }
18403 /**
18404 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
18405 * @param {string} token - Mixpanel project tracking token
18406 * @param {Object} [options]
18407 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18408 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18409 * @returns {boolean} whether the user has opted in to the given opt type
18410 */
18411 function hasOptedIn(token, options) {
18412 return _getStorageValue(token, options) === "1";
18413 }
18414 /**
18415 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
18416 * @param {string} token - Mixpanel project tracking token
18417 * @param {Object} [options]
18418 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18419 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18420 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
18421 * @returns {boolean} whether the user has opted out of the given opt type
18422 */
18423 function hasOptedOut(token, options) {
18424 if (_hasDoNotTrackFlagOn(options)) {
18425 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\"");
18426 return true;
18427 }
18428 var optedOut = _getStorageValue(token, options) === "0";
18429 if (optedOut) console$1.warn("You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.");
18430 return optedOut;
18431 }
18432 /**
18433 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18434 * If the user has opted out, return early instead of executing the method.
18435 * If a callback argument was provided, execute it passing the 0 error code.
18436 * @param {function} method - wrapped method to be executed if the user has not opted out
18437 * @returns {*} the result of executing method OR undefined if the user has opted out
18438 */
18439 function addOptOutCheckMixpanelLib(method) {
18440 return _addOptOutCheck(method, function(name) {
18441 return this.get_config(name);
18442 });
18443 }
18444 /**
18445 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18446 * If the user has opted out, return early instead of executing the method.
18447 * If a callback argument was provided, execute it passing the 0 error code.
18448 * @param {function} method - wrapped method to be executed if the user has not opted out
18449 * @returns {*} the result of executing method OR undefined if the user has opted out
18450 */
18451 function addOptOutCheckMixpanelPeople(method) {
18452 return _addOptOutCheck(method, function(name) {
18453 return this._get_config(name);
18454 });
18455 }
18456 /**
18457 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18458 * If the user has opted out, return early instead of executing the method.
18459 * If a callback argument was provided, execute it passing the 0 error code.
18460 * @param {function} method - wrapped method to be executed if the user has not opted out
18461 * @returns {*} the result of executing method OR undefined if the user has opted out
18462 */
18463 function addOptOutCheckMixpanelGroup(method) {
18464 return _addOptOutCheck(method, function(name) {
18465 return this._get_config(name);
18466 });
18467 }
18468 /**
18469 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
18470 * @param {string} token - Mixpanel project tracking token
18471 * @param {Object} [options]
18472 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
18473 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18474 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18475 * @param {string} [options.cookieDomain] - custom cookie domain
18476 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18477 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18478 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18479 */
18480 function clearOptInOut(token, options) {
18481 options = options || {};
18482 _getStorage(options).remove(_getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain);
18483 }
18484 /** Private **/
18485 /**
18486 * Get storage util
18487 * @param {Object} [options]
18488 * @param {string} [options.persistenceType]
18489 * @returns {object} either _.cookie or _.localstorage
18490 */
18491 function _getStorage(options) {
18492 options = options || {};
18493 return options.persistenceType === "localStorage" ? _$1.localStorage : _$1.cookie;
18494 }
18495 /**
18496 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
18497 * @param {string} token - Mixpanel project tracking token
18498 * @param {Object} [options]
18499 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18500 * @returns {string} the name of the cookie for the given opt type
18501 */
18502 function _getStorageKey(token, options) {
18503 options = options || {};
18504 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
18505 }
18506 /**
18507 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
18508 * @param {string} token - Mixpanel project tracking token
18509 * @param {Object} [options]
18510 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18511 * @returns {string} the value of the cookie for the given opt type
18512 */
18513 function _getStorageValue(token, options) {
18514 return _getStorage(options).get(_getStorageKey(token, options));
18515 }
18516 /**
18517 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
18518 * @param {Object} [options]
18519 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
18520 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
18521 * @returns {boolean} whether the DNT setting is true
18522 */
18523 function _hasDoNotTrackFlagOn(options) {
18524 if (options && options.ignoreDnt) return false;
18525 var win$1 = options && options.window || win;
18526 var nav = win$1["navigator"] || {};
18527 var hasDntOn = false;
18528 _$1.each([
18529 nav["doNotTrack"],
18530 nav["msDoNotTrack"],
18531 win$1["doNotTrack"]
18532 ], function(dntValue) {
18533 if (_$1.includes([
18534 true,
18535 1,
18536 "1",
18537 "yes"
18538 ], dntValue)) hasDntOn = true;
18539 });
18540 return hasDntOn;
18541 }
18542 /**
18543 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
18544 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
18545 * @param {string} token - Mixpanel project tracking token
18546 * @param {Object} [options]
18547 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
18548 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
18549 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
18550 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
18551 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
18552 * @param {string} [options.cookieDomain] - custom cookie domain
18553 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
18554 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
18555 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
18556 */
18557 function _optInOut(optValue, token, options) {
18558 if (!_$1.isString(token) || !token.length) {
18559 console$1.error("gdpr." + (optValue ? "optIn" : "optOut") + " called with an invalid token");
18560 return;
18561 }
18562 options = options || {};
18563 _getStorage(options).set(_getStorageKey(token, options), optValue ? 1 : 0, _$1.isNumber(options.cookieExpiration) ? options.cookieExpiration : null, !!options.crossSubdomainCookie, !!options.secureCookie, !!options.crossSiteCookie, options.cookieDomain);
18564 if (options.track && optValue) options.track(options.trackEventName || "$opt_in", options.trackProperties, { "send_immediately": true });
18565 }
18566 /**
18567 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
18568 * If the user has opted out, return early instead of executing the method.
18569 * If a callback argument was provided, execute it passing the 0 error code.
18570 * @param {function} method - wrapped method to be executed if the user has not opted out
18571 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
18572 * @returns {*} the result of executing method OR undefined if the user has opted out
18573 */
18574 function _addOptOutCheck(method, getConfigValue) {
18575 return function() {
18576 var optedOut = false;
18577 try {
18578 var token = getConfigValue.call(this, "token");
18579 var ignoreDnt = getConfigValue.call(this, "ignore_dnt");
18580 var persistenceType = getConfigValue.call(this, "opt_out_tracking_persistence_type");
18581 var persistencePrefix = getConfigValue.call(this, "opt_out_tracking_cookie_prefix");
18582 var win = getConfigValue.call(this, "window");
18583 if (token) optedOut = hasOptedOut(token, {
18584 ignoreDnt,
18585 persistenceType,
18586 persistencePrefix,
18587 window: win
18588 });
18589 } catch (err) {
18590 console$1.error("Unexpected error when checking tracking opt-out status: " + err);
18591 }
18592 if (!optedOut) return method.apply(this, arguments);
18593 var callback = arguments[arguments.length - 1];
18594 if (typeof callback === "function") callback(0);
18595 };
18596 }
18597 var logger$6 = console_with_prefix("lock");
18598 /**
18599 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
18600 * window/tab at a time will be able to access shared resources.
18601 *
18602 * Based on the Alur and Taubenfeld fast lock
18603 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
18604 * with an added timeout to ensure there will be eventual progress in the event
18605 * that a window is closed in the middle of the callback.
18606 *
18607 * Implementation based on the original version by David Wolever (https://github.com/wolever)
18608 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
18609 *
18610 * @example
18611 * const myLock = new SharedLock('some-key');
18612 * myLock.withLock(function() {
18613 * console.log('I hold the mutex!');
18614 * });
18615 *
18616 * @constructor
18617 */
18618 var SharedLock = function(key, options) {
18619 options = options || {};
18620 this.storageKey = key;
18621 this.storage = options.storage || win.localStorage;
18622 this.pollIntervalMS = options.pollIntervalMS || 100;
18623 this.timeoutMS = options.timeoutMS || 2e3;
18624 this.promiseImpl = options.promiseImpl || PromisePolyfill;
18625 };
18626 SharedLock.prototype.withLock = function(lockedCB, pid) {
18627 var Promise = this.promiseImpl;
18628 return new Promise(_$1.bind(function(resolve, reject) {
18629 var i = pid || (/* @__PURE__ */ new Date()).getTime() + "|" + Math.random();
18630 var startTime = (/* @__PURE__ */ new Date()).getTime();
18631 var key = this.storageKey;
18632 var pollIntervalMS = this.pollIntervalMS;
18633 var timeoutMS = this.timeoutMS;
18634 var storage = this.storage;
18635 var keyX = key + ":X";
18636 var keyY = key + ":Y";
18637 var keyZ = key + ":Z";
18638 var delay = function(cb) {
18639 if ((/* @__PURE__ */ new Date()).getTime() - startTime > timeoutMS) {
18640 logger$6.error("Timeout waiting for mutex on " + key + "; clearing lock. [" + i + "]");
18641 storage.removeItem(keyZ);
18642 storage.removeItem(keyY);
18643 loop();
18644 return;
18645 }
18646 setTimeout(function() {
18647 try {
18648 cb();
18649 } catch (err) {
18650 reject(err);
18651 }
18652 }, pollIntervalMS * (Math.random() + .1));
18653 };
18654 var waitFor = function(predicate, cb) {
18655 if (predicate()) cb();
18656 else delay(function() {
18657 waitFor(predicate, cb);
18658 });
18659 };
18660 var getSetY = function() {
18661 var valY = storage.getItem(keyY);
18662 if (valY && valY !== i) return false;
18663 else {
18664 storage.setItem(keyY, i);
18665 if (storage.getItem(keyY) === i) return true;
18666 else {
18667 if (!localStorageSupported(storage, true)) reject(/* @__PURE__ */ new Error("localStorage support dropped while acquiring lock"));
18668 return false;
18669 }
18670 }
18671 };
18672 var loop = function() {
18673 storage.setItem(keyX, i);
18674 waitFor(getSetY, function() {
18675 if (storage.getItem(keyX) === i) {
18676 criticalSection();
18677 return;
18678 }
18679 delay(function() {
18680 if (storage.getItem(keyY) !== i) {
18681 loop();
18682 return;
18683 }
18684 waitFor(function() {
18685 return !storage.getItem(keyZ);
18686 }, criticalSection);
18687 });
18688 });
18689 };
18690 var criticalSection = function() {
18691 storage.setItem(keyZ, "1");
18692 var removeLock = function() {
18693 storage.removeItem(keyZ);
18694 if (storage.getItem(keyY) === i) storage.removeItem(keyY);
18695 if (storage.getItem(keyX) === i) storage.removeItem(keyX);
18696 };
18697 lockedCB().then(function(ret) {
18698 removeLock();
18699 resolve(ret);
18700 }).catch(function(err) {
18701 removeLock();
18702 reject(err);
18703 });
18704 };
18705 try {
18706 if (localStorageSupported(storage, true)) loop();
18707 else throw new Error("localStorage support check failed");
18708 } catch (err) {
18709 reject(err);
18710 }
18711 }, this));
18712 };
18713 /**
18714 * @type {import('./wrapper').StorageWrapper}
18715 */
18716 var LocalStorageWrapper = function(storageOverride) {
18717 this.storage = storageOverride || win.localStorage;
18718 };
18719 LocalStorageWrapper.prototype.init = function() {
18720 return PromisePolyfill.resolve();
18721 };
18722 LocalStorageWrapper.prototype.isInitialized = function() {
18723 return true;
18724 };
18725 LocalStorageWrapper.prototype.setItem = function(key, value) {
18726 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18727 try {
18728 this.storage.setItem(key, JSONStringify(value));
18729 } catch (e) {
18730 reject(e);
18731 }
18732 resolve();
18733 }, this));
18734 };
18735 LocalStorageWrapper.prototype.getItem = function(key) {
18736 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18737 var item;
18738 try {
18739 item = JSONParse(this.storage.getItem(key));
18740 } catch (e) {
18741 reject(e);
18742 }
18743 resolve(item);
18744 }, this));
18745 };
18746 LocalStorageWrapper.prototype.removeItem = function(key) {
18747 return new PromisePolyfill(_$1.bind(function(resolve, reject) {
18748 try {
18749 this.storage.removeItem(key);
18750 } catch (e) {
18751 reject(e);
18752 }
18753 resolve();
18754 }, this));
18755 };
18756 var logger$5 = console_with_prefix("batch");
18757 /**
18758 * RequestQueue: queue for batching API requests with localStorage backup for retries.
18759 * Maintains an in-memory queue which represents the source of truth for the current
18760 * page, but also writes all items out to a copy in the browser's localStorage, which
18761 * can be read on subsequent pageloads and retried. For batchability, all the request
18762 * items in the queue should be of the same type (events, people updates, group updates)
18763 * so they can be sent in a single request to the same API endpoint.
18764 *
18765 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
18766 * the same site to access the same persisted data, they must share the same localStorage
18767 * key (for instance based on project token and queue type). Therefore access to the
18768 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
18769 * simultaneously open windows/tabs from overwriting each other's data (which would lead
18770 * to data loss in some situations).
18771 * @constructor
18772 */
18773 var RequestQueue = function(storageKey, options) {
18774 options = options || {};
18775 this.storageKey = storageKey;
18776 this.usePersistence = options.usePersistence;
18777 if (this.usePersistence) {
18778 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
18779 this.lock = new SharedLock(storageKey, {
18780 storage: options.sharedLockStorage || win.localStorage,
18781 timeoutMS: options.sharedLockTimeoutMS
18782 });
18783 }
18784 this.reportError = options.errorReporter || _$1.bind(logger$5.error, logger$5);
18785 this.pid = options.pid || null;
18786 this.memQueue = [];
18787 this.initialized = false;
18788 if (options.enqueueThrottleMs) this.enqueuePersisted = batchedThrottle(_$1.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
18789 else this.enqueuePersisted = _$1.bind(function(queueEntry) {
18790 return this._enqueuePersisted([queueEntry]);
18791 }, this);
18792 };
18793 RequestQueue.prototype.ensureInit = function() {
18794 if (this.initialized || !this.usePersistence) return PromisePolyfill.resolve();
18795 return this.queueStorage.init().then(_$1.bind(function() {
18796 this.initialized = true;
18797 }, this)).catch(_$1.bind(function(err) {
18798 this.reportError("Error initializing queue persistence. Disabling persistence", err);
18799 this.initialized = true;
18800 this.usePersistence = false;
18801 }, this));
18802 };
18803 /**
18804 * Add one item to queues (memory and localStorage). The queued entry includes
18805 * the given item along with an auto-generated ID and a "flush-after" timestamp.
18806 * It is expected that the item will be sent over the network and dequeued
18807 * before the flush-after time; if this doesn't happen it is considered orphaned
18808 * (e.g., the original tab where it was enqueued got closed before it could be
18809 * sent) and the item can be sent by any tab that finds it in localStorage.
18810 *
18811 * The final callback param is called with a param indicating success or
18812 * failure of the enqueue operation; it is asynchronous because the localStorage
18813 * lock is asynchronous.
18814 */
18815 RequestQueue.prototype.enqueue = function(item, flushInterval) {
18816 var queueEntry = {
18817 "id": cheap_guid(),
18818 "flushAfter": (/* @__PURE__ */ new Date()).getTime() + flushInterval * 2,
18819 "payload": item
18820 };
18821 if (!this.usePersistence) {
18822 this.memQueue.push(queueEntry);
18823 return PromisePolyfill.resolve(true);
18824 } else return this.enqueuePersisted(queueEntry);
18825 };
18826 RequestQueue.prototype._enqueuePersisted = function(queueEntries) {
18827 var enqueueItem = _$1.bind(function() {
18828 return this.ensureInit().then(_$1.bind(function() {
18829 return this.readFromStorage();
18830 }, this)).then(_$1.bind(function(storedQueue) {
18831 return this.saveToStorage(storedQueue.concat(queueEntries));
18832 }, this)).then(_$1.bind(function(succeeded) {
18833 if (succeeded) this.memQueue = this.memQueue.concat(queueEntries);
18834 return succeeded;
18835 }, this)).catch(_$1.bind(function(err) {
18836 this.reportError("Error enqueueing items", err, queueEntries);
18837 return false;
18838 }, this));
18839 }, this);
18840 return this.lock.withLock(enqueueItem, this.pid).catch(_$1.bind(function(err) {
18841 this.reportError("Error acquiring storage lock", err);
18842 return false;
18843 }, this));
18844 };
18845 /**
18846 * Read out the given number of queue entries. If this.memQueue
18847 * has fewer than batchSize items, then look for "orphaned" items
18848 * in the persisted queue (items where the 'flushAfter' time has
18849 * already passed).
18850 */
18851 RequestQueue.prototype.fillBatch = function(batchSize) {
18852 var batch = this.memQueue.slice(0, batchSize);
18853 if (this.usePersistence && batch.length < batchSize) return this.ensureInit().then(_$1.bind(function() {
18854 return this.readFromStorage();
18855 }, this)).then(_$1.bind(function(storedQueue) {
18856 if (storedQueue.length) {
18857 var idsInBatch = {};
18858 _$1.each(batch, function(item) {
18859 idsInBatch[item["id"]] = true;
18860 });
18861 for (var i = 0; i < storedQueue.length; i++) {
18862 var item = storedQueue[i];
18863 if ((/* @__PURE__ */ new Date()).getTime() > item["flushAfter"] && !idsInBatch[item["id"]]) {
18864 item.orphaned = true;
18865 batch.push(item);
18866 if (batch.length >= batchSize) break;
18867 }
18868 }
18869 }
18870 return batch;
18871 }, this));
18872 else return PromisePolyfill.resolve(batch);
18873 };
18874 /**
18875 * Remove items with matching 'id' from array (immutably)
18876 * also remove any item without a valid id (e.g., malformed
18877 * storage entries).
18878 */
18879 var filterOutIDsAndInvalid = function(items, idSet) {
18880 var filteredItems = [];
18881 _$1.each(items, function(item) {
18882 if (item["id"] && !idSet[item["id"]]) filteredItems.push(item);
18883 });
18884 return filteredItems;
18885 };
18886 /**
18887 * Remove items with matching IDs from both in-memory queue
18888 * and persisted queue
18889 */
18890 RequestQueue.prototype.removeItemsByID = function(ids) {
18891 var idSet = {};
18892 _$1.each(ids, function(id) {
18893 idSet[id] = true;
18894 });
18895 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
18896 if (!this.usePersistence) return PromisePolyfill.resolve(true);
18897 else {
18898 var removeFromStorage = _$1.bind(function() {
18899 return this.ensureInit().then(_$1.bind(function() {
18900 return this.readFromStorage();
18901 }, this)).then(_$1.bind(function(storedQueue) {
18902 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
18903 return this.saveToStorage(storedQueue);
18904 }, this)).then(_$1.bind(function() {
18905 return this.readFromStorage();
18906 }, this)).then(_$1.bind(function(storedQueue) {
18907 for (var i = 0; i < storedQueue.length; i++) {
18908 var item = storedQueue[i];
18909 if (item["id"] && !!idSet[item["id"]]) throw new Error("Item not removed from storage");
18910 }
18911 return true;
18912 }, this)).catch(_$1.bind(function(err) {
18913 this.reportError("Error removing items", err, ids);
18914 return false;
18915 }, this));
18916 }, this);
18917 return this.lock.withLock(removeFromStorage, this.pid).catch(_$1.bind(function(err) {
18918 this.reportError("Error acquiring storage lock", err);
18919 if (!localStorageSupported(this.lock.storage, true)) return removeFromStorage().then(_$1.bind(function(success) {
18920 if (!success) return this.queueStorage.removeItem(this.storageKey).then(function() {
18921 return success;
18922 });
18923 return success;
18924 }, this)).catch(_$1.bind(function(err) {
18925 this.reportError("Error clearing queue", err);
18926 return false;
18927 }, this));
18928 else return false;
18929 }, this));
18930 }
18931 };
18932 var updatePayloads = function(existingItems, itemsToUpdate) {
18933 var newItems = [];
18934 _$1.each(existingItems, function(item) {
18935 var id = item["id"];
18936 if (id in itemsToUpdate) {
18937 var newPayload = itemsToUpdate[id];
18938 if (newPayload !== null) {
18939 item["payload"] = newPayload;
18940 newItems.push(item);
18941 }
18942 } else newItems.push(item);
18943 });
18944 return newItems;
18945 };
18946 /**
18947 * Update payloads of given items in both in-memory queue and
18948 * persisted queue. Items set to null are removed from queues.
18949 */
18950 RequestQueue.prototype.updatePayloads = function(itemsToUpdate) {
18951 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
18952 if (!this.usePersistence) return PromisePolyfill.resolve(true);
18953 else return this.lock.withLock(_$1.bind(function lockAcquired() {
18954 return this.ensureInit().then(_$1.bind(function() {
18955 return this.readFromStorage();
18956 }, this)).then(_$1.bind(function(storedQueue) {
18957 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
18958 return this.saveToStorage(storedQueue);
18959 }, this)).catch(_$1.bind(function(err) {
18960 this.reportError("Error updating items", itemsToUpdate, err);
18961 return false;
18962 }, this));
18963 }, this), this.pid).catch(_$1.bind(function(err) {
18964 this.reportError("Error acquiring storage lock", err);
18965 return false;
18966 }, this));
18967 };
18968 /**
18969 * Read and parse items array from localStorage entry, handling
18970 * malformed/missing data if necessary.
18971 */
18972 RequestQueue.prototype.readFromStorage = function() {
18973 return this.ensureInit().then(_$1.bind(function() {
18974 return this.queueStorage.getItem(this.storageKey);
18975 }, this)).then(_$1.bind(function(storageEntry) {
18976 if (storageEntry) {
18977 if (!_$1.isArray(storageEntry)) {
18978 this.reportError("Invalid storage entry:", storageEntry);
18979 storageEntry = null;
18980 }
18981 }
18982 return storageEntry || [];
18983 }, this)).catch(_$1.bind(function(err) {
18984 this.reportError("Error retrieving queue", err);
18985 return [];
18986 }, this));
18987 };
18988 /**
18989 * Serialize the given items array to localStorage.
18990 */
18991 RequestQueue.prototype.saveToStorage = function(queue) {
18992 return this.ensureInit().then(_$1.bind(function() {
18993 return this.queueStorage.setItem(this.storageKey, queue);
18994 }, this)).then(function() {
18995 return true;
18996 }).catch(_$1.bind(function(err) {
18997 this.reportError("Error saving queue", err);
18998 return false;
18999 }, this));
19000 };
19001 /**
19002 * Clear out queues (memory and localStorage).
19003 */
19004 RequestQueue.prototype.clear = function() {
19005 this.memQueue = [];
19006 if (this.usePersistence) return this.ensureInit().then(_$1.bind(function() {
19007 return this.queueStorage.removeItem(this.storageKey);
19008 }, this));
19009 else return PromisePolyfill.resolve();
19010 };
19011 var MAX_RETRY_INTERVAL_MS = 600 * 1e3;
19012 var logger$4 = console_with_prefix("batch");
19013 /**
19014 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
19015 * type (events, people, groups).
19016 * Uses RequestQueue to manage the backing store.
19017 * @constructor
19018 */
19019 var RequestBatcher = function(storageKey, options) {
19020 this.errorReporter = options.errorReporter;
19021 this.queue = new RequestQueue(storageKey, {
19022 errorReporter: _$1.bind(this.reportError, this),
19023 queueStorage: options.queueStorage,
19024 sharedLockStorage: options.sharedLockStorage,
19025 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
19026 usePersistence: options.usePersistence,
19027 enqueueThrottleMs: options.enqueueThrottleMs
19028 });
19029 this.libConfig = options.libConfig;
19030 this.sendRequest = options.sendRequestFunc;
19031 this.beforeSendHook = options.beforeSendHook;
19032 this.stopAllBatching = options.stopAllBatchingFunc;
19033 this.batchSize = this.libConfig["batch_size"];
19034 this.flushInterval = this.libConfig["batch_flush_interval_ms"];
19035 this.stopped = !this.libConfig["batch_autostart"];
19036 this.consecutiveRemovalFailures = 0;
19037 this.itemIdsSentSuccessfully = {};
19038 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
19039 this._flushPromise = null;
19040 };
19041 /**
19042 * Add one item to queue.
19043 */
19044 RequestBatcher.prototype.enqueue = function(item) {
19045 return this.queue.enqueue(item, this.flushInterval);
19046 };
19047 /**
19048 * Start flushing batches at the configured time interval. Must call
19049 * this method upon SDK init in order to send anything over the network.
19050 */
19051 RequestBatcher.prototype.start = function() {
19052 this.stopped = false;
19053 this.consecutiveRemovalFailures = 0;
19054 return this.flush();
19055 };
19056 /**
19057 * Stop flushing batches. Can be restarted by calling start().
19058 */
19059 RequestBatcher.prototype.stop = function() {
19060 this.stopped = true;
19061 if (this.timeoutID) {
19062 clearTimeout(this.timeoutID);
19063 this.timeoutID = null;
19064 }
19065 };
19066 /**
19067 * Clear out queue.
19068 */
19069 RequestBatcher.prototype.clear = function() {
19070 return this.queue.clear();
19071 };
19072 /**
19073 * Restore batch size configuration to whatever is set in the main SDK.
19074 */
19075 RequestBatcher.prototype.resetBatchSize = function() {
19076 this.batchSize = this.libConfig["batch_size"];
19077 };
19078 /**
19079 * Restore flush interval time configuration to whatever is set in the main SDK.
19080 */
19081 RequestBatcher.prototype.resetFlush = function() {
19082 this.scheduleFlush(this.libConfig["batch_flush_interval_ms"]);
19083 };
19084 /**
19085 * Schedule the next flush in the given number of milliseconds.
19086 */
19087 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
19088 this.flushInterval = flushMS;
19089 if (!this.stopped) this.timeoutID = setTimeout(_$1.bind(function() {
19090 if (!this.stopped) this._flushPromise = this.flush();
19091 }, this), this.flushInterval);
19092 };
19093 /**
19094 * Send a request using the sendRequest callback, but promisified.
19095 * TODO: sendRequest should be promisified in the first place.
19096 */
19097 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
19098 return new PromisePolyfill(_$1.bind(function(resolve) {
19099 this.sendRequest(data, options, resolve);
19100 }, this));
19101 };
19102 /**
19103 * Flush one batch to network. Depending on success/failure modes, it will either
19104 * remove the batch from the queue or leave it in for retry, and schedule the next
19105 * flush. In cases of most network or API failures, it will back off exponentially
19106 * when retrying.
19107 * @param {Object} [options]
19108 * @param {boolean} [options.sendBeacon] - whether to send batch with
19109 * navigator.sendBeacon (only useful for sending batches before page unloads, as
19110 * sendBeacon offers no callbacks or status indications)
19111 */
19112 RequestBatcher.prototype.flush = function(options) {
19113 if (this.requestInProgress) {
19114 logger$4.log("Flush: Request already in progress");
19115 return PromisePolyfill.resolve();
19116 }
19117 this.requestInProgress = true;
19118 options = options || {};
19119 var timeoutMS = this.libConfig["batch_request_timeout_ms"];
19120 var startTime = (/* @__PURE__ */ new Date()).getTime();
19121 var currentBatchSize = this.batchSize;
19122 return this.queue.fillBatch(currentBatchSize).then(_$1.bind(function(batch) {
19123 var attemptSecondaryFlush = batch.length === currentBatchSize;
19124 var dataForRequest = [];
19125 var transformedItems = {};
19126 _$1.each(batch, function(item) {
19127 var payload = item["payload"];
19128 if (this.beforeSendHook && !item.orphaned) payload = this.beforeSendHook(payload);
19129 if (payload) {
19130 if (payload["event"] && payload["properties"]) payload["properties"] = _$1.extend({}, payload["properties"], { "mp_sent_by_lib_version": Config.LIB_VERSION });
19131 var addPayload = true;
19132 var itemId = item["id"];
19133 if (itemId) {
19134 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
19135 this.reportError("[dupe] item ID sent too many times, not sending", {
19136 item,
19137 batchSize: batch.length,
19138 timesSent: this.itemIdsSentSuccessfully[itemId]
19139 });
19140 addPayload = false;
19141 }
19142 } else this.reportError("[dupe] found item with no ID", { item });
19143 if (addPayload) dataForRequest.push(payload);
19144 }
19145 transformedItems[item["id"]] = payload;
19146 }, this);
19147 if (dataForRequest.length < 1) {
19148 this.requestInProgress = false;
19149 this.resetFlush();
19150 return PromisePolyfill.resolve();
19151 }
19152 var removeItemsFromQueue = _$1.bind(function() {
19153 return this.queue.removeItemsByID(_$1.map(batch, function(item) {
19154 return item["id"];
19155 })).then(_$1.bind(function(succeeded) {
19156 _$1.each(batch, _$1.bind(function(item) {
19157 var itemId = item["id"];
19158 if (itemId) {
19159 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
19160 this.itemIdsSentSuccessfully[itemId]++;
19161 if (this.itemIdsSentSuccessfully[itemId] > 5) this.reportError("[dupe] item ID sent too many times", {
19162 item,
19163 batchSize: batch.length,
19164 timesSent: this.itemIdsSentSuccessfully[itemId]
19165 });
19166 } else this.reportError("[dupe] found item with no ID while removing", { item });
19167 }, this));
19168 if (succeeded) {
19169 this.consecutiveRemovalFailures = 0;
19170 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
19171 this.resetFlush();
19172 return PromisePolyfill.resolve();
19173 } else return this.flush();
19174 } else {
19175 if (++this.consecutiveRemovalFailures > 5) {
19176 this.reportError("Too many queue failures; disabling batching system.");
19177 this.stopAllBatching();
19178 } else this.resetFlush();
19179 return PromisePolyfill.resolve();
19180 }
19181 }, this));
19182 }, this);
19183 var batchSendCallback = _$1.bind(function(res) {
19184 this.requestInProgress = false;
19185 try {
19186 if (options.unloading) return this.queue.updatePayloads(transformedItems);
19187 else if (_$1.isObject(res) && res.error === "timeout" && (/* @__PURE__ */ new Date()).getTime() - startTime >= timeoutMS) {
19188 this.reportError("Network timeout; retrying");
19189 return this.flush();
19190 } else if (_$1.isObject(res) && (res.httpStatusCode >= 500 || res.httpStatusCode === 429 || res.httpStatusCode <= 0 && !isOnline() || res.error === "timeout")) {
19191 var retryMS = this.flushInterval * 2;
19192 if (res.retryAfter) retryMS = parseInt(res.retryAfter, 10) * 1e3 || retryMS;
19193 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
19194 this.reportError("Error; retry in " + retryMS + " ms");
19195 this.scheduleFlush(retryMS);
19196 return PromisePolyfill.resolve();
19197 } else if (_$1.isObject(res) && res.httpStatusCode === 413) if (batch.length > 1) {
19198 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
19199 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
19200 this.reportError("413 response; reducing batch size to " + this.batchSize);
19201 this.resetFlush();
19202 return PromisePolyfill.resolve();
19203 } else {
19204 this.reportError("Single-event request too large; dropping", batch);
19205 this.resetBatchSize();
19206 return removeItemsFromQueue();
19207 }
19208 else return removeItemsFromQueue();
19209 } catch (err) {
19210 this.reportError("Error handling API response", err);
19211 this.resetFlush();
19212 }
19213 }, this);
19214 var requestOptions = {
19215 method: "POST",
19216 verbose: true,
19217 ignore_json_errors: true,
19218 timeout_ms: timeoutMS
19219 };
19220 if (options.unloading) requestOptions.transport = "sendBeacon";
19221 logger$4.log("MIXPANEL REQUEST:", dataForRequest);
19222 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
19223 }, this)).catch(_$1.bind(function(err) {
19224 this.reportError("Error flushing request queue", err);
19225 this.resetFlush();
19226 }, this));
19227 };
19228 /**
19229 * Log error to global logger and optional user-defined logger.
19230 */
19231 RequestBatcher.prototype.reportError = function(msg, err) {
19232 logger$4.error.apply(logger$4.error, arguments);
19233 if (this.errorReporter) try {
19234 if (!(err instanceof Error)) err = new Error(msg);
19235 this.errorReporter(msg, err);
19236 } catch (err) {
19237 logger$4.error(err);
19238 }
19239 };
19240 /**
19241 * @param {import('./session-recording').SerializedRecording} serializedRecording
19242 * @returns {boolean}
19243 */
19244 var isRecordingExpired = function(serializedRecording) {
19245 var now = Date.now();
19246 return !serializedRecording || now > serializedRecording["maxExpires"] || now > serializedRecording["idleExpires"];
19247 };
19248 var RECORD_ENQUEUE_THROTTLE_MS = 250;
19249 var logger$3 = console_with_prefix("recorder");
19250 var CompressionStream = win["CompressionStream"];
19251 var RECORDER_BATCHER_LIB_CONFIG = {
19252 "batch_size": 1e3,
19253 "batch_flush_interval_ms": 10 * 1e3,
19254 "batch_request_timeout_ms": 90 * 1e3,
19255 "batch_autostart": true
19256 };
19257 var ACTIVE_SOURCES = /* @__PURE__ */ new Set([
19258 IncrementalSource.MouseMove,
19259 IncrementalSource.MouseInteraction,
19260 IncrementalSource.Scroll,
19261 IncrementalSource.ViewportResize,
19262 IncrementalSource.Input,
19263 IncrementalSource.TouchMove,
19264 IncrementalSource.MediaInteraction,
19265 IncrementalSource.Drag,
19266 IncrementalSource.Selection
19267 ]);
19268 function isUserEvent(ev) {
19269 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
19270 }
19271 /**
19272 * @typedef {Object} SerializedRecording
19273 * @property {number} idleExpires
19274 * @property {number} maxExpires
19275 * @property {number} replayStartTime
19276 * @property {number} seqNo
19277 * @property {string} batchStartUrl
19278 * @property {string} replayId
19279 * @property {string} tabId
19280 * @property {string} replayStartUrl
19281 */
19282 /**
19283 * @typedef {Object} SessionRecordingOptions
19284 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
19285 * @property {String} [options.replayId] - unique uuid for a single replay
19286 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
19287 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
19288 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
19289 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
19290 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
19291 * optional properties for deserialization:
19292 * @property {number} idleExpires
19293 * @property {number} maxExpires
19294 * @property {number} replayStartTime
19295 * @property {number} seqNo
19296 * @property {string} batchStartUrl
19297 * @property {string} replayStartUrl
19298 */
19299 /**
19300 * @typedef {Object} UserIdInfo
19301 * @property {string} distinct_id
19302 * @property {string} user_id
19303 * @property {string} device_id
19304 */
19305 /**
19306 * This class encapsulates a single session recording and its lifecycle.
19307 * @param {SessionRecordingOptions} options
19308 */
19309 var SessionRecording = function(options) {
19310 this._mixpanel = options.mixpanelInstance;
19311 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
19312 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
19313 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
19314 this._rrwebRecord = options.rrwebRecord || null;
19315 this._stopRecording = null;
19316 this.replayId = options.replayId;
19317 this.batchStartUrl = options.batchStartUrl || null;
19318 this.replayStartUrl = options.replayStartUrl || null;
19319 this.idleExpires = options.idleExpires || null;
19320 this.maxExpires = options.maxExpires || null;
19321 this.replayStartTime = options.replayStartTime || null;
19322 this.seqNo = options.seqNo || 0;
19323 this.idleTimeoutId = null;
19324 this.maxTimeoutId = null;
19325 this.recordMaxMs = MAX_RECORDING_MS;
19326 this.recordMinMs = 0;
19327 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig("disable_persistence");
19328 this.batcherKey = "__mprec_" + this.getConfig("name") + "_" + this.getConfig("token") + "_" + this.replayId;
19329 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
19330 this.batcher = new RequestBatcher(this.batcherKey, {
19331 errorReporter: this.reportError.bind(this),
19332 flushOnlyOnInterval: true,
19333 libConfig: RECORDER_BATCHER_LIB_CONFIG,
19334 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
19335 queueStorage: this.queueStorage,
19336 sharedLockStorage: options.sharedLockStorage,
19337 usePersistence,
19338 stopAllBatchingFunc: this.stopRecording.bind(this),
19339 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
19340 sharedLockTimeoutMS: 10 * 1e3
19341 });
19342 };
19343 /**
19344 * @returns {UserIdInfo}
19345 */
19346 SessionRecording.prototype.getUserIdInfo = function() {
19347 if (this.finalFlushUserIdInfo) return this.finalFlushUserIdInfo;
19348 var userIdInfo = { "distinct_id": String(this._mixpanel.get_distinct_id()) };
19349 var deviceId = this._mixpanel.get_property("$device_id");
19350 if (deviceId) userIdInfo["$device_id"] = deviceId;
19351 var userId = this._mixpanel.get_property("$user_id");
19352 if (userId) userIdInfo["$user_id"] = userId;
19353 return userIdInfo;
19354 };
19355 SessionRecording.prototype.unloadPersistedData = function() {
19356 this.batcher.stop();
19357 return this.batcher.flush().then(function() {
19358 return this.queueStorage.removeItem(this.batcherKey);
19359 }.bind(this));
19360 };
19361 SessionRecording.prototype.getConfig = function(configVar) {
19362 return this._mixpanel.get_config(configVar);
19363 };
19364 SessionRecording.prototype.get_config = function(configVar) {
19365 return this.getConfig(configVar);
19366 };
19367 SessionRecording.prototype.startRecording = function(shouldStopBatcher) {
19368 if (this._rrwebRecord === null) {
19369 this.reportError("rrweb record function not provided. ");
19370 return;
19371 }
19372 if (this._stopRecording !== null) {
19373 logger$3.log("Recording already in progress, skipping startRecording.");
19374 return;
19375 }
19376 this.recordMaxMs = this.getConfig("record_max_ms");
19377 if (this.recordMaxMs > MAX_RECORDING_MS) {
19378 this.recordMaxMs = MAX_RECORDING_MS;
19379 logger$3.critical("record_max_ms cannot be greater than " + MAX_RECORDING_MS + "ms. Capping value.");
19380 }
19381 if (!this.maxExpires) this.maxExpires = (/* @__PURE__ */ new Date()).getTime() + this.recordMaxMs;
19382 this.recordMinMs = this.getConfig("record_min_ms");
19383 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
19384 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
19385 logger$3.critical("record_min_ms cannot be greater than " + MAX_VALUE_FOR_MIN_RECORDING_MS + "ms. Capping value.");
19386 }
19387 if (!this.replayStartTime) {
19388 this.replayStartTime = (/* @__PURE__ */ new Date()).getTime();
19389 this.batchStartUrl = _$1.info.currentUrl();
19390 this.replayStartUrl = _$1.info.currentUrl();
19391 }
19392 if (shouldStopBatcher || this.recordMinMs > 0) this.batcher.stop();
19393 else this.batcher.start();
19394 var resetIdleTimeout = function() {
19395 clearTimeout(this.idleTimeoutId);
19396 var idleTimeoutMs = this.getConfig("record_idle_timeout_ms");
19397 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
19398 this.idleExpires = (/* @__PURE__ */ new Date()).getTime() + idleTimeoutMs;
19399 }.bind(this);
19400 resetIdleTimeout();
19401 var blockSelector = this.getConfig("record_block_selector");
19402 if (blockSelector === "" || blockSelector === null) blockSelector = void 0;
19403 try {
19404 this._stopRecording = this._rrwebRecord({
19405 "emit": function(ev) {
19406 if (this.idleExpires && this.idleExpires < ev.timestamp) {
19407 this._onIdleTimeout();
19408 return;
19409 }
19410 if (isUserEvent(ev)) {
19411 if (this.batcher.stopped && (/* @__PURE__ */ new Date()).getTime() - this.replayStartTime >= this.recordMinMs) this.batcher.start();
19412 resetIdleTimeout();
19413 }
19414 this.__enqueuePromise = this.batcher.enqueue(ev);
19415 }.bind(this),
19416 "blockClass": this.getConfig("record_block_class"),
19417 "blockSelector": blockSelector,
19418 "collectFonts": this.getConfig("record_collect_fonts"),
19419 "dataURLOptions": {
19420 "type": "image/webp",
19421 "quality": .6
19422 },
19423 "maskAllInputs": true,
19424 "maskTextClass": this.getConfig("record_mask_text_class"),
19425 "maskTextSelector": this.getConfig("record_mask_text_selector"),
19426 "recordCanvas": this.getConfig("record_canvas"),
19427 "sampling": { "canvas": 15 }
19428 });
19429 } catch (err) {
19430 this.reportError("Unexpected error when starting rrweb recording.", err);
19431 }
19432 if (typeof this._stopRecording !== "function") {
19433 this.reportError("rrweb failed to start, skipping this recording.");
19434 this._stopRecording = null;
19435 this.stopRecording();
19436 return;
19437 }
19438 var maxTimeoutMs = this.maxExpires - (/* @__PURE__ */ new Date()).getTime();
19439 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
19440 };
19441 SessionRecording.prototype.stopRecording = function(skipFlush) {
19442 this.finalFlushUserIdInfo = this.getUserIdInfo();
19443 if (!this.isRrwebStopped()) {
19444 try {
19445 this._stopRecording();
19446 } catch (err) {
19447 this.reportError("Error with rrweb stopRecording", err);
19448 }
19449 this._stopRecording = null;
19450 }
19451 var flushPromise;
19452 if (this.batcher.stopped) flushPromise = this.batcher.clear();
19453 else if (!skipFlush) flushPromise = this.batcher.flush();
19454 this.batcher.stop();
19455 clearTimeout(this.idleTimeoutId);
19456 clearTimeout(this.maxTimeoutId);
19457 return flushPromise;
19458 };
19459 SessionRecording.prototype.isRrwebStopped = function() {
19460 return this._stopRecording === null;
19461 };
19462 /**
19463 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
19464 * we stop recording and dump any queued events if the user has opted out.
19465 */
19466 SessionRecording.prototype.flushEventsWithOptOut = function(data, options, cb) {
19467 var onOptOut = function(code) {
19468 if (code === 0) {
19469 this.stopRecording();
19470 cb({ error: "Tracking has been opted out, stopping recording." });
19471 }
19472 }.bind(this);
19473 this._flushEvents(data, options, cb, onOptOut);
19474 };
19475 /**
19476 * @returns {SerializedRecording}
19477 */
19478 SessionRecording.prototype.serialize = function() {
19479 var tabId;
19480 try {
19481 tabId = this._mixpanel.get_tab_id();
19482 } catch (e) {
19483 this.reportError("Error getting tab ID for serialization ", e);
19484 tabId = null;
19485 }
19486 return {
19487 "replayId": this.replayId,
19488 "seqNo": this.seqNo,
19489 "replayStartTime": this.replayStartTime,
19490 "batchStartUrl": this.batchStartUrl,
19491 "replayStartUrl": this.replayStartUrl,
19492 "idleExpires": this.idleExpires,
19493 "maxExpires": this.maxExpires,
19494 "tabId": tabId
19495 };
19496 };
19497 /**
19498 * @static
19499 * @param {SerializedRecording} serializedRecording
19500 * @param {SessionRecordingOptions} options
19501 * @returns {SessionRecording}
19502 */
19503 SessionRecording.deserialize = function(serializedRecording, options) {
19504 return new SessionRecording(_$1.extend({}, options, {
19505 replayId: serializedRecording["replayId"],
19506 batchStartUrl: serializedRecording["batchStartUrl"],
19507 replayStartUrl: serializedRecording["replayStartUrl"],
19508 idleExpires: serializedRecording["idleExpires"],
19509 maxExpires: serializedRecording["maxExpires"],
19510 replayStartTime: serializedRecording["replayStartTime"],
19511 seqNo: serializedRecording["seqNo"],
19512 sharedLockStorage: options.sharedLockStorage
19513 }));
19514 };
19515 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
19516 var onSuccess = function(response, responseBody) {
19517 if (response.status === 200 && this.replayId === currentReplayId) {
19518 this.seqNo++;
19519 this.batchStartUrl = _$1.info.currentUrl();
19520 }
19521 this._onBatchSent();
19522 callback({
19523 status: 0,
19524 httpStatusCode: response.status,
19525 responseBody,
19526 retryAfter: response.headers.get("Retry-After")
19527 });
19528 }.bind(this);
19529 var apiHost = this._mixpanel.get_api_host && this._mixpanel.get_api_host("record") || this.getConfig("api_host");
19530 win["fetch"](apiHost + "/" + this.getConfig("api_routes")["record"] + "?" + new URLSearchParams(reqParams), {
19531 "method": "POST",
19532 "headers": {
19533 "Authorization": "Basic " + btoa(this.getConfig("token") + ":"),
19534 "Content-Type": "application/octet-stream"
19535 },
19536 "body": reqBody
19537 }).then(function(response) {
19538 response.json().then(function(responseBody) {
19539 onSuccess(response, responseBody);
19540 }).catch(function(error) {
19541 callback({ error });
19542 });
19543 }).catch(function(error) {
19544 callback({
19545 error,
19546 httpStatusCode: 0
19547 });
19548 });
19549 };
19550 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function(data, options, callback) {
19551 var numEvents = data.length;
19552 if (numEvents > 0) {
19553 var replayId = this.replayId;
19554 var batchStartTime = Infinity;
19555 var batchEndTime = -Infinity;
19556 var hasFullSnapshot = false;
19557 for (var i = 0; i < numEvents; i++) {
19558 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
19559 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
19560 if (data[i].type === EventType.FullSnapshot) hasFullSnapshot = true;
19561 }
19562 if (this.seqNo === 0) {
19563 if (!hasFullSnapshot) {
19564 callback({ error: "First batch does not contain a full snapshot. Aborting recording." });
19565 this.stopRecording(true);
19566 return;
19567 }
19568 this.replayStartTime = batchStartTime;
19569 } else if (!this.replayStartTime) {
19570 this.reportError("Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.");
19571 this.replayStartTime = batchStartTime;
19572 }
19573 var replayLengthMs = batchEndTime - this.replayStartTime;
19574 var reqParams = {
19575 "$current_url": this.batchStartUrl,
19576 "$lib_version": Config.LIB_VERSION,
19577 "batch_start_time": batchStartTime / 1e3,
19578 "mp_lib": "web",
19579 "replay_id": replayId,
19580 "replay_length_ms": replayLengthMs,
19581 "replay_start_time": this.replayStartTime / 1e3,
19582 "replay_start_url": this.replayStartUrl,
19583 "seq": this.seqNo
19584 };
19585 var eventsJson = JSON.stringify(data);
19586 Object.assign(reqParams, this.getUserIdInfo());
19587 if (CompressionStream) {
19588 var gzipStream = new Blob([eventsJson], { type: "application/json" }).stream().pipeThrough(new CompressionStream("gzip"));
19589 new Response(gzipStream).blob().then(function(compressedBlob) {
19590 reqParams["format"] = "gzip";
19591 this._sendRequest(replayId, reqParams, compressedBlob, callback);
19592 }.bind(this));
19593 } else {
19594 reqParams["format"] = "body";
19595 this._sendRequest(replayId, reqParams, eventsJson, callback);
19596 }
19597 }
19598 });
19599 SessionRecording.prototype.reportError = function(msg, err) {
19600 logger$3.error.apply(logger$3.error, arguments);
19601 try {
19602 if (!err && !(msg instanceof Error)) msg = new Error(msg);
19603 this.getConfig("error_reporter")(msg, err);
19604 } catch (err) {
19605 logger$3.error(err);
19606 }
19607 };
19608 /**
19609 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
19610 * Makes sure that only one tab can be recording at a time.
19611 */
19612 var RecordingRegistry = function(options) {
19613 /** @type {IDBStorageWrapper} */
19614 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
19615 this.errorReporter = options.errorReporter;
19616 this.mixpanelInstance = options.mixpanelInstance;
19617 this.sharedLockStorage = options.sharedLockStorage;
19618 };
19619 RecordingRegistry.prototype.isPersistenceEnabled = function() {
19620 return !this.mixpanelInstance.get_config("disable_persistence");
19621 };
19622 RecordingRegistry.prototype.handleError = function(err) {
19623 this.errorReporter("IndexedDB error: ", err);
19624 };
19625 /**
19626 * @param {import('./session-recording').SerializedRecording} serializedRecording
19627 */
19628 RecordingRegistry.prototype.setActiveRecording = function(serializedRecording) {
19629 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve();
19630 var tabId = serializedRecording["tabId"];
19631 if (!tabId) {
19632 console.warn("No tab ID is set, cannot persist recording metadata.");
19633 return PromisePolyfill.resolve();
19634 }
19635 return this.idb.init().then(function() {
19636 return this.idb.setItem(tabId, serializedRecording);
19637 }.bind(this)).catch(this.handleError.bind(this));
19638 };
19639 /**
19640 * @returns {Promise<import('./session-recording').SerializedRecording>}
19641 */
19642 RecordingRegistry.prototype.getActiveRecording = function() {
19643 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve(null);
19644 return this.idb.init().then(function() {
19645 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
19646 }.bind(this)).then(function(serializedRecording) {
19647 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
19648 }.bind(this)).catch(this.handleError.bind(this));
19649 };
19650 RecordingRegistry.prototype.clearActiveRecording = function() {
19651 if (this.isPersistenceEnabled()) return this.markActiveRecordingExpired();
19652 else return this.deleteActiveRecording();
19653 };
19654 RecordingRegistry.prototype.markActiveRecordingExpired = function() {
19655 return this.getActiveRecording().then(function(serializedRecording) {
19656 if (serializedRecording) {
19657 serializedRecording["maxExpires"] = 0;
19658 return this.setActiveRecording(serializedRecording);
19659 }
19660 }.bind(this)).catch(this.handleError.bind(this));
19661 };
19662 RecordingRegistry.prototype.deleteActiveRecording = function() {
19663 if (this.idb.isInitialized()) return this.idb.removeItem(this.mixpanelInstance.get_tab_id()).catch(this.handleError.bind(this));
19664 else return PromisePolyfill.resolve();
19665 };
19666 /**
19667 * Flush any inactive recordings from the registry to minimize data loss.
19668 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
19669 */
19670 RecordingRegistry.prototype.flushInactiveRecordings = function() {
19671 if (!this.isPersistenceEnabled()) return PromisePolyfill.resolve([]);
19672 return this.idb.init().then(function() {
19673 return this.idb.getAll();
19674 }.bind(this)).then(function(serializedRecordings) {
19675 var unloadPromises = serializedRecordings.filter(function(serializedRecording) {
19676 return isRecordingExpired(serializedRecording);
19677 }).map(function(serializedRecording) {
19678 return SessionRecording.deserialize(serializedRecording, {
19679 mixpanelInstance: this.mixpanelInstance,
19680 sharedLockStorage: this.sharedLockStorage
19681 }).unloadPersistedData().then(function() {
19682 return this.idb.removeItem(serializedRecording["tabId"]);
19683 }.bind(this)).catch(this.handleError.bind(this));
19684 }.bind(this));
19685 return PromisePolyfill.all(unloadPromises);
19686 }.bind(this)).catch(this.handleError.bind(this));
19687 };
19688 var logger$2 = console_with_prefix("recorder");
19689 /**
19690 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
19691 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
19692 */
19693 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
19694 this.mixpanelInstance = mixpanelInstance;
19695 this.rrwebRecord = rrwebRecord || record;
19696 this.sharedLockStorage = sharedLockStorage;
19697 /**
19698 * @member {import('./registry').RecordingRegistry}
19699 */
19700 this.recordingRegistry = new RecordingRegistry({
19701 mixpanelInstance: this.mixpanelInstance,
19702 errorReporter: logger$2.error,
19703 sharedLockStorage
19704 });
19705 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
19706 this.activeRecording = null;
19707 this.stopRecordingInProgress = false;
19708 };
19709 MixpanelRecorder.prototype.startRecording = function(options) {
19710 options = options || {};
19711 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
19712 logger$2.log("Recording already in progress, skipping startRecording.");
19713 return;
19714 }
19715 var onIdleTimeout = function() {
19716 logger$2.log("Idle timeout reached, restarting recording.");
19717 this.resetRecording();
19718 }.bind(this);
19719 var onMaxLengthReached = function() {
19720 logger$2.log("Max recording length reached, stopping recording.");
19721 this.resetRecording();
19722 }.bind(this);
19723 var onBatchSent = function() {
19724 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
19725 this["__flushPromise"] = this.activeRecording.batcher._flushPromise;
19726 }.bind(this);
19727 /**
19728 * @type {import('./session-recording').SessionRecordingOptions}
19729 */
19730 var sessionRecordingOptions = {
19731 mixpanelInstance: this.mixpanelInstance,
19732 onBatchSent,
19733 onIdleTimeout,
19734 onMaxLengthReached,
19735 replayId: _$1.UUID(),
19736 rrwebRecord: this.rrwebRecord,
19737 sharedLockStorage: this.sharedLockStorage
19738 };
19739 if (options.activeSerializedRecording) this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
19740 else this.activeRecording = new SessionRecording(sessionRecordingOptions);
19741 this.activeRecording.startRecording(options.shouldStopBatcher);
19742 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
19743 };
19744 MixpanelRecorder.prototype.stopRecording = function() {
19745 this.stopRecordingInProgress = true;
19746 return this._stopCurrentRecording(false, true).then(function() {
19747 return this.recordingRegistry.clearActiveRecording();
19748 }.bind(this)).then(function() {
19749 this.stopRecordingInProgress = false;
19750 }.bind(this));
19751 };
19752 MixpanelRecorder.prototype.pauseRecording = function() {
19753 return this._stopCurrentRecording(false);
19754 };
19755 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
19756 if (this.activeRecording) {
19757 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
19758 if (disableActiveRecording) this.activeRecording = null;
19759 return stopRecordingPromise;
19760 }
19761 return PromisePolyfill.resolve();
19762 };
19763 MixpanelRecorder.prototype.resumeRecording = function(startNewIfInactive) {
19764 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
19765 this.activeRecording.startRecording(false);
19766 return PromisePolyfill.resolve(null);
19767 }
19768 return this.recordingRegistry.getActiveRecording().then(function(activeSerializedRecording) {
19769 if (activeSerializedRecording && !this.stopRecordingInProgress) return this.startRecording({ activeSerializedRecording });
19770 else if (startNewIfInactive) return this.startRecording({ shouldStopBatcher: false });
19771 else {
19772 logger$2.log("No resumable recording found.");
19773 return null;
19774 }
19775 }.bind(this));
19776 };
19777 MixpanelRecorder.prototype.resetRecording = function() {
19778 this.stopRecording();
19779 this.startRecording({ shouldStopBatcher: true });
19780 };
19781 MixpanelRecorder.prototype.getActiveReplayId = function() {
19782 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) return this.activeRecording.replayId;
19783 else return null;
19784 };
19785 Object.defineProperty(MixpanelRecorder.prototype, "replayId", { get: function() {
19786 return this.getActiveReplayId();
19787 } });
19788 win["__mp_recorder"] = MixpanelRecorder;
19789 var EV_CHANGE = "change";
19790 var EV_CLICK = "click";
19791 var EV_HASHCHANGE = "hashchange";
19792 var EV_INPUT = "input";
19793 var EV_LOAD = "load";
19794 var EV_MP_LOCATION_CHANGE = "mp_locationchange";
19795 var EV_POPSTATE = "popstate";
19796 var EV_SCROLLEND = "scrollend";
19797 var EV_SCROLL = "scroll";
19798 var EV_SELECT = "select";
19799 var EV_SUBMIT = "submit";
19800 var EV_TOGGLE = "toggle";
19801 var EV_VISIBILITYCHANGE = "visibilitychange";
19802 var CLICK_EVENT_PROPS = [
19803 "clientX",
19804 "clientY",
19805 "offsetX",
19806 "offsetY",
19807 "pageX",
19808 "pageY",
19809 "screenX",
19810 "screenY",
19811 "x",
19812 "y"
19813 ];
19814 var OPT_IN_CLASSES = ["mp-include"];
19815 var OPT_OUT_CLASSES = ["mp-no-track"];
19816 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(["mp-sensitive"]);
19817 var TRACKED_ATTRS = [
19818 "aria-label",
19819 "aria-labelledby",
19820 "aria-describedby",
19821 "href",
19822 "name",
19823 "role",
19824 "title",
19825 "type"
19826 ];
19827 var INTERACTIVE_ARIA_ROLES = {
19828 "button": true,
19829 "checkbox": true,
19830 "combobox": true,
19831 "grid": true,
19832 "link": true,
19833 "listbox": true,
19834 "menu": true,
19835 "menubar": true,
19836 "menuitem": true,
19837 "menuitemcheckbox": true,
19838 "menuitemradio": true,
19839 "navigation": true,
19840 "option": true,
19841 "radio": true,
19842 "radiogroup": true,
19843 "searchbox": true,
19844 "slider": true,
19845 "spinbutton": true,
19846 "switch": true,
19847 "tab": true,
19848 "tablist": true,
19849 "textbox": true,
19850 "tree": true,
19851 "treegrid": true,
19852 "treeitem": true
19853 };
19854 var ALWAYS_NON_INTERACTIVE_TAGS = {
19855 "base": true,
19856 "head": true,
19857 "html": true,
19858 "link": true,
19859 "meta": true,
19860 "script": true,
19861 "style": true,
19862 "title": true,
19863 "br": true,
19864 "hr": true,
19865 "wbr": true,
19866 "noscript": true,
19867 "picture": true,
19868 "source": true,
19869 "template": true,
19870 "track": true
19871 };
19872 var TEXT_CONTAINER_TAGS = {
19873 "article": true,
19874 "div": true,
19875 "h1": true,
19876 "h2": true,
19877 "h3": true,
19878 "h4": true,
19879 "h5": true,
19880 "h6": true,
19881 "p": true,
19882 "section": true,
19883 "span": true
19884 };
19885 var EVENT_HANDLER_ATTRIBUTES = [
19886 "onclick",
19887 "onmousedown",
19888 "onmouseup",
19889 "onpointerdown",
19890 "onpointerup",
19891 "ontouchend",
19892 "ontouchstart"
19893 ];
19894 var MAX_DEPTH = 5;
19895 var logger$1 = console_with_prefix("autocapture");
19896 function getClasses(el) {
19897 var classes = {};
19898 var classList = getClassName(el).split(" ");
19899 for (var i = 0; i < classList.length; i++) {
19900 var cls = classList[i];
19901 if (cls) classes[cls] = true;
19902 }
19903 return classes;
19904 }
19905 function getClassName(el) {
19906 switch (typeof el.className) {
19907 case "string": return el.className;
19908 case "object": return el.className.baseVal || el.getAttribute("class") || "";
19909 default: return "";
19910 }
19911 }
19912 function getPreviousElementSibling(el) {
19913 if (el.previousElementSibling) return el.previousElementSibling;
19914 else {
19915 do
19916 el = el.previousSibling;
19917 while (el && !isElementNode(el));
19918 return el;
19919 }
19920 }
19921 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
19922 var props = {
19923 "$classes": getClassName(el).split(" "),
19924 "$tag_name": el.tagName.toLowerCase()
19925 };
19926 var elId = el.id;
19927 if (elId) props["$id"] = elId;
19928 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) _$1.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
19929 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
19930 var attrVal = el.getAttribute(attr);
19931 if (shouldTrackValue(attrVal)) props["$attr-" + attr] = attrVal;
19932 }
19933 });
19934 var nthChild = 1;
19935 var nthOfType = 1;
19936 var currentElem = el;
19937 while (currentElem = getPreviousElementSibling(currentElem)) {
19938 nthChild++;
19939 if (currentElem.tagName === el.tagName) nthOfType++;
19940 }
19941 props["$nth_child"] = nthChild;
19942 props["$nth_of_type"] = nthOfType;
19943 return props;
19944 }
19945 function getPropsForDOMEvent(ev, config) {
19946 var allowElementCallback = config.allowElementCallback;
19947 var allowSelectors = config.allowSelectors || [];
19948 var blockAttrs = config.blockAttrs || [];
19949 var blockElementCallback = config.blockElementCallback;
19950 var blockSelectors = config.blockSelectors || [];
19951 var captureTextContent = config.captureTextContent || false;
19952 var captureExtraAttrs = config.captureExtraAttrs || [];
19953 var capturedForHeatMap = config.capturedForHeatMap || false;
19954 var blockAttrsSet = {};
19955 _$1.each(blockAttrs, function(attr) {
19956 blockAttrsSet[attr] = true;
19957 });
19958 var props = null;
19959 var target = typeof ev.target === "undefined" ? ev.srcElement : ev.target;
19960 if (isTextNode(target)) target = target.parentNode;
19961 if (shouldTrackDomEvent(target, ev) && isElementAllowed(target, ev, allowElementCallback, allowSelectors) && !isElementBlocked(target, ev, blockElementCallback, blockSelectors)) {
19962 var targetElementList = [target];
19963 var curEl = target;
19964 while (curEl.parentNode && !isTag(curEl, "body")) {
19965 targetElementList.push(curEl.parentNode);
19966 curEl = curEl.parentNode;
19967 }
19968 var elementsJson = [];
19969 var href;
19970 var explicitNoTrack = false;
19971 _$1.each(targetElementList, function(el) {
19972 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
19973 if (!blockAttrsSet["href"] && el.tagName.toLowerCase() === "a") {
19974 href = el.getAttribute("href");
19975 href = shouldTrackDetails && shouldTrackValue(href) && href;
19976 }
19977 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) explicitNoTrack = true;
19978 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
19979 }, this);
19980 if (!explicitNoTrack) {
19981 var docElement = document$1["documentElement"];
19982 props = {
19983 "$event_type": ev.type,
19984 "$host": win.location.host,
19985 "$pathname": win.location.pathname,
19986 "$elements": elementsJson,
19987 "$el_attr__href": href,
19988 "$viewportHeight": Math.max(docElement["clientHeight"], win["innerHeight"] || 0),
19989 "$viewportWidth": Math.max(docElement["clientWidth"], win["innerWidth"] || 0),
19990 "$pageHeight": document$1["body"]["offsetHeight"] || 0,
19991 "$pageWidth": document$1["body"]["offsetWidth"] || 0
19992 };
19993 _$1.each(captureExtraAttrs, function(attr) {
19994 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
19995 var attrVal = target.getAttribute(attr);
19996 if (shouldTrackValue(attrVal)) props["$el_attr__" + attr] = attrVal;
19997 }
19998 });
19999 if (captureTextContent) {
20000 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
20001 if (elementText && elementText.length) props["$el_text"] = elementText;
20002 }
20003 if (ev.type === EV_CLICK) {
20004 _$1.each(CLICK_EVENT_PROPS, function(prop) {
20005 if (prop in ev) props["$" + prop] = ev[prop];
20006 });
20007 if (capturedForHeatMap) props["$captured_for_heatmap"] = true;
20008 target = guessRealClickTarget(ev);
20009 }
20010 if (captureTextContent) {
20011 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
20012 if (elementText && elementText.length) props["$el_text"] = elementText;
20013 }
20014 if (target) {
20015 if (!isElementAllowed(target, ev, allowElementCallback, allowSelectors) || isElementBlocked(target, ev, blockElementCallback, blockSelectors)) return null;
20016 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
20017 props["$target"] = targetProps;
20018 props["$el_classes"] = targetProps["$classes"];
20019 _$1.extend(props, _$1.strip_empty_properties({
20020 "$el_id": targetProps["$id"],
20021 "$el_tag_name": targetProps["$tag_name"]
20022 }));
20023 }
20024 }
20025 }
20026 return props;
20027 }
20028 /**
20029 * Get the direct text content of an element, protecting against sensitive data collection.
20030 * Concats textContent of each of the element's text node children; this avoids potential
20031 * collection of sensitive data that could happen if we used element.textContent and the
20032 * element had sensitive child elements, since element.textContent includes child content.
20033 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
20034 * @param {Element} el - element to get the text of
20035 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
20036 * @returns {string} the element's direct text content
20037 */
20038 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
20039 var elText = "";
20040 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) _$1.each(el.childNodes, function(child) {
20041 if (isTextNode(child) && child.textContent) elText += _$1.trim(child.textContent).split(/(\s+)/).filter(shouldTrackValue).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255);
20042 });
20043 return _$1.trim(elText);
20044 }
20045 function guessRealClickTarget(ev) {
20046 var target = ev.target;
20047 var composedPath = ev["composedPath"]();
20048 for (var i = 0; i < composedPath.length; i++) {
20049 var node = composedPath[i];
20050 if (isTag(node, "a") || isTag(node, "button") || isTag(node, "input") || isTag(node, "select") || node.getAttribute && node.getAttribute("role") === "button") {
20051 target = node;
20052 break;
20053 }
20054 if (node === target) break;
20055 }
20056 return target;
20057 }
20058 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
20059 if (allowElementCallback) try {
20060 if (!allowElementCallback(el, ev)) return false;
20061 } catch (err) {
20062 logger$1.critical("Error while checking element in allowElementCallback", err);
20063 return false;
20064 }
20065 if (!allowSelectors.length) return true;
20066 for (var i = 0; i < allowSelectors.length; i++) {
20067 var sel = allowSelectors[i];
20068 try {
20069 if (el["matches"](sel)) return true;
20070 } catch (err) {
20071 logger$1.critical("Error while checking selector: " + sel, err);
20072 }
20073 }
20074 return false;
20075 }
20076 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
20077 var i;
20078 if (blockElementCallback) try {
20079 if (blockElementCallback(el, ev)) return true;
20080 } catch (err) {
20081 logger$1.critical("Error while checking element in blockElementCallback", err);
20082 return true;
20083 }
20084 if (blockSelectors && blockSelectors.length) for (i = 0; i < blockSelectors.length; i++) {
20085 var sel = blockSelectors[i];
20086 try {
20087 if (el["matches"](sel)) return true;
20088 } catch (err) {
20089 logger$1.critical("Error while checking selector: " + sel, err);
20090 }
20091 }
20092 var classes = getClasses(el);
20093 for (i = 0; i < OPT_OUT_CLASSES.length; i++) if (classes[OPT_OUT_CLASSES[i]]) return true;
20094 return false;
20095 }
20096 function isElementNode(node) {
20097 return node && node.nodeType === 1;
20098 }
20099 function isTag(el, tag) {
20100 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
20101 }
20102 function isTextNode(node) {
20103 return node && node.nodeType === 3;
20104 }
20105 function minDOMApisSupported() {
20106 try {
20107 return !!document$1.createElement("div")["matches"];
20108 } catch (err) {
20109 return false;
20110 }
20111 }
20112 function weakSetSupported() {
20113 return typeof WeakSet !== "undefined";
20114 }
20115 function shouldTrackDomEvent(el, ev) {
20116 if (!el || isTag(el, "html") || !isElementNode(el)) return false;
20117 switch (el.tagName.toLowerCase()) {
20118 case "form": return ev.type === EV_SUBMIT;
20119 case "input": if (["button", "submit"].indexOf(el.getAttribute("type")) === -1) return ev.type === EV_CHANGE;
20120 else return ev.type === EV_CLICK;
20121 case "select":
20122 case "textarea": return ev.type === EV_CHANGE;
20123 default: return ev.type === EV_CLICK;
20124 }
20125 }
20126 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
20127 var i;
20128 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) return false;
20129 for (var curEl = el; curEl.parentNode && !isTag(curEl, "body"); curEl = curEl.parentNode) {
20130 var classes = getClasses(curEl);
20131 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) if (classes[SENSITIVE_DATA_CLASSES[i]]) return false;
20132 }
20133 var elClasses = getClasses(el);
20134 for (i = 0; i < OPT_IN_CLASSES.length; i++) if (elClasses[OPT_IN_CLASSES[i]]) return true;
20135 if (isTag(el, "input") || isTag(el, "select") || isTag(el, "textarea") || el.getAttribute("contenteditable") === "true") return false;
20136 var type = el.type || "";
20137 if (typeof type === "string") switch (type.toLowerCase()) {
20138 case "hidden": return false;
20139 case "password": return false;
20140 }
20141 var name = el.name || el.id || "";
20142 if (typeof name === "string") {
20143 if (/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(name.replace(/[^a-zA-Z0-9]/g, ""))) return false;
20144 }
20145 return true;
20146 }
20147 function shouldTrackValue(value) {
20148 if (value === null || _$1.isUndefined(value)) return false;
20149 if (typeof value === "string") {
20150 value = _$1.trim(value);
20151 if (/^(?:(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}))$/.test((value || "").replace(/[- ]/g, ""))) return false;
20152 if (/(^\d{3}-?\d{2}-?\d{4}$)/.test(value)) return false;
20153 }
20154 return true;
20155 }
20156 /**
20157 * Creates a cross-browser compatible scroll end function with appropriate event listener.
20158 * For browsers that support scrollend, returns the original function with scrollend event.
20159 * For browsers without scrollend support, returns a debounced function that triggers
20160 * 100ms after the last scroll event to simulate scrollend behavior.
20161 * @param {Function} originalFunction - The function to call when scrolling ends
20162 * @returns {Object} Object containing listener function and eventType string
20163 * @returns {Function} returns.listener - The wrapped function to use as event listener
20164 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
20165 */
20166 function getPolyfillScrollEndFunction(originalFunction) {
20167 var supportsScrollEnd = "onscrollend" in win;
20168 var polyfillFunction = safewrap(originalFunction);
20169 var polyfillEvent = EV_SCROLLEND;
20170 if (!supportsScrollEnd) {
20171 var scrollTimer = null;
20172 var scrollDelayMs = 100;
20173 polyfillFunction = safewrap(function() {
20174 clearTimeout(scrollTimer);
20175 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
20176 });
20177 polyfillEvent = EV_SCROLL;
20178 }
20179 return {
20180 listener: polyfillFunction,
20181 eventType: polyfillEvent
20182 };
20183 }
20184 function hasInlineEventHandlers(element) {
20185 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) return true;
20186 return false;
20187 }
20188 function hasInteractiveAriaRole(element) {
20189 var role = element.getAttribute("role");
20190 if (!role) return false;
20191 return INTERACTIVE_ARIA_ROLES[role.trim().split(/\s+/)[0].toLowerCase()];
20192 }
20193 function hasAnyInteractivityIndicators(element) {
20194 var tagName = element.tagName.toLowerCase();
20195 if (tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea" || tagName === "details" || tagName === "dialog") return true;
20196 if (element.isContentEditable) return true;
20197 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) return true;
20198 if (hasInlineEventHandlers(element)) return true;
20199 if (hasInteractiveAriaRole(element)) return true;
20200 if (tagName === "a" && element.hasAttribute("href")) return true;
20201 if (element.hasAttribute("tabindex")) return true;
20202 return false;
20203 }
20204 function isDefinitelyNonInteractive(element) {
20205 if (!element || !element.tagName) return true;
20206 var tagName = element.tagName.toLowerCase();
20207 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) return true;
20208 if (hasAnyInteractivityIndicators(element)) return false;
20209 var parent = element.parentElement;
20210 var depth = 0;
20211 while (parent && depth < MAX_DEPTH) {
20212 if (hasAnyInteractivityIndicators(parent)) return false;
20213 if (parent.getRootNode && parent.getRootNode() !== document$1) {
20214 var root = parent.getRootNode();
20215 if (root.host && hasAnyInteractivityIndicators(root.host)) return false;
20216 }
20217 parent = parent.parentElement;
20218 depth++;
20219 }
20220 if (TEXT_CONTAINER_TAGS[tagName]) return true;
20221 return false;
20222 }
20223 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
20224 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1e3;
20225 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
20226 function RageClickTracker() {
20227 this.clicks = [];
20228 }
20229 RageClickTracker.prototype.isRageClick = function(x, y, options) {
20230 options = options || {};
20231 var thresholdPx = options["threshold_px"] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
20232 var timeoutMs = options["timeout_ms"] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
20233 var clickCount = options["click_count"] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
20234 var timestamp = Date.now();
20235 var lastClick = this.clicks[this.clicks.length - 1];
20236 if (lastClick && timestamp - lastClick.timestamp < timeoutMs && Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx) {
20237 this.clicks.push({
20238 x,
20239 y,
20240 timestamp
20241 });
20242 if (this.clicks.length >= clickCount) {
20243 this.clicks = [];
20244 return true;
20245 }
20246 } else this.clicks = [{
20247 x,
20248 y,
20249 timestamp
20250 }];
20251 return false;
20252 };
20253 function ShadowDOMObserver(changeCallback, observerConfig) {
20254 this.changeCallback = changeCallback || function() {};
20255 this.observerConfig = observerConfig;
20256 this.observedShadowRoots = null;
20257 this.shadowObservers = [];
20258 }
20259 ShadowDOMObserver.prototype.getEventTarget = function(event) {
20260 if (!this.observedShadowRoots) return;
20261 var path = this.getComposedPath(event);
20262 if (path && path.length) return path[0];
20263 return event["target"] || event["srcElement"];
20264 };
20265 ShadowDOMObserver.prototype.getComposedPath = function(event) {
20266 if ("composedPath" in event) return event["composedPath"]();
20267 return [];
20268 };
20269 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
20270 if (!this.observedShadowRoots) return;
20271 var path = this.getComposedPath(event);
20272 for (var i = 0; i < path.length; i++) {
20273 var element = path[i];
20274 if (element && element.shadowRoot) this.observeShadowRoot(element.shadowRoot);
20275 }
20276 };
20277 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
20278 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) return;
20279 var self = this;
20280 try {
20281 this.observedShadowRoots.add(shadowRoot);
20282 var observer = new window.MutationObserver(function() {
20283 self.changeCallback();
20284 });
20285 observer.observe(shadowRoot, this.observerConfig);
20286 this.shadowObservers.push(observer);
20287 } catch (e) {
20288 logger$1.critical("Error while observing shadow root", e);
20289 }
20290 };
20291 ShadowDOMObserver.prototype.start = function() {
20292 if (this.observedShadowRoots) return;
20293 if (!weakSetSupported()) {
20294 logger$1.critical("Shadow DOM observation unavailable: WeakSet not supported");
20295 return;
20296 }
20297 this.observedShadowRoots = /* @__PURE__ */ new WeakSet();
20298 };
20299 ShadowDOMObserver.prototype.stop = function() {
20300 if (!this.observedShadowRoots) return;
20301 for (var i = 0; i < this.shadowObservers.length; i++) try {
20302 this.shadowObservers[i].disconnect();
20303 } catch (e) {
20304 logger$1.critical("Error while disconnecting shadow DOM observer", e);
20305 }
20306 this.shadowObservers = [];
20307 this.observedShadowRoots = null;
20308 };
20309 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
20310 /** @const */ var INTERACTION_EVENTS = [
20311 EV_CHANGE,
20312 EV_INPUT,
20313 EV_SUBMIT,
20314 EV_SELECT,
20315 EV_TOGGLE
20316 ];
20317 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
20318 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
20319 /** @const */ var MUTATION_OBSERVER_CONFIG = {
20320 characterData: true,
20321 childList: true,
20322 subtree: true,
20323 attributes: true,
20324 attributeFilter: [
20325 "style",
20326 "class",
20327 "hidden",
20328 "checked",
20329 "selected",
20330 "value",
20331 "display",
20332 "visibility"
20333 ]
20334 };
20335 function DeadClickTracker(onDeadClickCallback) {
20336 this.eventListeners = [];
20337 this.mutationObserver = null;
20338 this.shadowDOMObserver = null;
20339 this.isTracking = false;
20340 this.lastChangeEventTimestamp = 0;
20341 this.pendingClicks = [];
20342 this.onDeadClickCallback = onDeadClickCallback;
20343 this.processingActive = false;
20344 this.processingTimeout = null;
20345 }
20346 DeadClickTracker.prototype.addClick = function(event) {
20347 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
20348 if (!element) element = event["target"] || event["srcElement"];
20349 if (!element || isDefinitelyNonInteractive(element)) return false;
20350 if (this.shadowDOMObserver) this.shadowDOMObserver.observeFromEvent(event);
20351 this.pendingClicks.push({
20352 element,
20353 event,
20354 timestamp: Date.now()
20355 });
20356 return true;
20357 };
20358 DeadClickTracker.prototype.trackClick = function(event, config) {
20359 if (!this.isTracking) return false;
20360 var added = this.addClick(event);
20361 if (added) this.triggerProcessing(config);
20362 return added;
20363 };
20364 DeadClickTracker.prototype.getDeadClicks = function(config) {
20365 if (this.pendingClicks.length === 0) return [];
20366 var timeoutMs = config["timeout_ms"];
20367 var now = Date.now();
20368 var clicksToEvaluate = this.pendingClicks.slice();
20369 this.pendingClicks = [];
20370 var deadClicks = [];
20371 for (var i = 0; i < clicksToEvaluate.length; i++) {
20372 var click = clicksToEvaluate[i];
20373 if (now - click.timestamp >= timeoutMs) {
20374 if (!this.hasChangesAfter(click.timestamp)) deadClicks.push(click);
20375 } else this.pendingClicks.push(click);
20376 }
20377 return deadClicks;
20378 };
20379 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
20380 return this.lastChangeEventTimestamp >= timestamp - 100;
20381 };
20382 DeadClickTracker.prototype.recordChangeEvent = function() {
20383 this.lastChangeEventTimestamp = Date.now();
20384 };
20385 DeadClickTracker.prototype.triggerProcessing = function(config) {
20386 if (this.processingActive) return;
20387 this.processingActive = true;
20388 this.processRecursively(config);
20389 };
20390 DeadClickTracker.prototype.processRecursively = function(config) {
20391 if (!this.isTracking || !this.onDeadClickCallback) {
20392 this.processingActive = false;
20393 return;
20394 }
20395 var timeoutMs = config["timeout_ms"];
20396 var self = this;
20397 this.processingTimeout = setTimeout(function() {
20398 if (!self.processingActive) return;
20399 var deadClicks = self.getDeadClicks(config);
20400 for (var i = 0; i < deadClicks.length; i++) self.onDeadClickCallback(deadClicks[i].event);
20401 if (self.pendingClicks.length > 0) self.processRecursively(config);
20402 else self.processingActive = false;
20403 }, timeoutMs);
20404 };
20405 DeadClickTracker.prototype.startTracking = function() {
20406 if (this.isTracking) return;
20407 this.isTracking = true;
20408 var self = this;
20409 INTERACTION_EVENTS.forEach(function(event) {
20410 var handler = function() {
20411 self.recordChangeEvent();
20412 };
20413 document.addEventListener(event, handler, {
20414 capture: true,
20415 passive: true
20416 });
20417 self.eventListeners.push({
20418 target: document,
20419 event,
20420 handler,
20421 options: {
20422 capture: true,
20423 passive: true
20424 }
20425 });
20426 });
20427 NAVIGATION_EVENTS.forEach(function(event) {
20428 var handler = function() {
20429 self.recordChangeEvent();
20430 };
20431 window.addEventListener(event, handler);
20432 self.eventListeners.push({
20433 target: window,
20434 event,
20435 handler
20436 });
20437 });
20438 LAYOUT_EVENTS.forEach(function(event) {
20439 var handler = function() {
20440 self.recordChangeEvent();
20441 };
20442 window.addEventListener(event, handler, { passive: true });
20443 self.eventListeners.push({
20444 target: window,
20445 event,
20446 handler,
20447 options: { passive: true }
20448 });
20449 });
20450 var selectionHandler = function() {
20451 self.recordChangeEvent();
20452 };
20453 document.addEventListener("selectionchange", selectionHandler);
20454 self.eventListeners.push({
20455 target: document,
20456 event: "selectionchange",
20457 handler: selectionHandler
20458 });
20459 if (window.MutationObserver) try {
20460 this.mutationObserver = new window.MutationObserver(function() {
20461 self.recordChangeEvent();
20462 });
20463 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
20464 } catch (e) {
20465 logger$1.critical("Error while setting up mutation observer", e);
20466 }
20467 if (window.customElements) try {
20468 this.shadowDOMObserver = new ShadowDOMObserver(function() {
20469 self.recordChangeEvent();
20470 }, MUTATION_OBSERVER_CONFIG);
20471 this.shadowDOMObserver.start();
20472 } catch (e) {
20473 logger$1.critical("Error while setting up shadow DOM observer", e);
20474 this.shadowDOMObserver = null;
20475 }
20476 };
20477 DeadClickTracker.prototype.stopTracking = function() {
20478 if (!this.isTracking) return;
20479 this.isTracking = false;
20480 this.pendingClicks = [];
20481 this.lastChangeEventTimestamp = 0;
20482 this.processingActive = false;
20483 if (this.processingTimeout) {
20484 clearTimeout(this.processingTimeout);
20485 this.processingTimeout = null;
20486 }
20487 for (var i = 0; i < this.eventListeners.length; i++) {
20488 var listener = this.eventListeners[i];
20489 try {
20490 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
20491 } catch (e) {
20492 logger$1.critical("Error while removing event listener", e);
20493 }
20494 }
20495 this.eventListeners = [];
20496 if (this.mutationObserver) {
20497 try {
20498 this.mutationObserver.disconnect();
20499 } catch (e) {
20500 logger$1.critical("Error while disconnecting mutation observer", e);
20501 }
20502 this.mutationObserver = null;
20503 }
20504 if (this.shadowDOMObserver) {
20505 try {
20506 this.shadowDOMObserver.stop();
20507 } catch (e) {
20508 logger$1.critical("Error while stopping shadow DOM observer", e);
20509 }
20510 this.shadowDOMObserver = null;
20511 }
20512 };
20513 var AUTOCAPTURE_CONFIG_KEY = "autocapture";
20514 var LEGACY_PAGEVIEW_CONFIG_KEY = "track_pageview";
20515 var PAGEVIEW_OPTION_FULL_URL = "full-url";
20516 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = "url-with-path-and-query-string";
20517 var PAGEVIEW_OPTION_URL_WITH_PATH = "url-with-path";
20518 var CONFIG_ALLOW_ELEMENT_CALLBACK = "allow_element_callback";
20519 var CONFIG_ALLOW_SELECTORS = "allow_selectors";
20520 var CONFIG_ALLOW_URL_REGEXES = "allow_url_regexes";
20521 var CONFIG_BLOCK_ATTRS = "block_attrs";
20522 var CONFIG_BLOCK_ELEMENT_CALLBACK = "block_element_callback";
20523 var CONFIG_BLOCK_SELECTORS = "block_selectors";
20524 var CONFIG_BLOCK_URL_REGEXES = "block_url_regexes";
20525 var CONFIG_CAPTURE_EXTRA_ATTRS = "capture_extra_attrs";
20526 var CONFIG_CAPTURE_TEXT_CONTENT = "capture_text_content";
20527 var CONFIG_SCROLL_CAPTURE_ALL = "scroll_capture_all";
20528 var CONFIG_SCROLL_CHECKPOINTS = "scroll_depth_percent_checkpoints";
20529 var CONFIG_TRACK_CLICK = "click";
20530 var CONFIG_TRACK_DEAD_CLICK = "dead_click";
20531 var CONFIG_TRACK_INPUT = "input";
20532 var CONFIG_TRACK_PAGEVIEW = "pageview";
20533 var CONFIG_TRACK_RAGE_CLICK = "rage_click";
20534 var CONFIG_TRACK_SCROLL = "scroll";
20535 var CONFIG_TRACK_PAGE_LEAVE = "page_leave";
20536 var CONFIG_TRACK_SUBMIT = "submit";
20537 var CONFIG_DEFAULTS$1 = {};
20538 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
20539 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
20540 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
20541 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
20542 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
20543 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
20544 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
20545 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
20546 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
20547 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [
20548 25,
20549 50,
20550 75,
20551 100
20552 ];
20553 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
20554 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
20555 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
20556 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
20557 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
20558 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
20559 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
20560 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
20561 var DEFAULT_PROPS = { "$mp_autocapture": true };
20562 var MP_EV_CLICK = "$mp_click";
20563 var MP_EV_DEAD_CLICK = "$mp_dead_click";
20564 var MP_EV_INPUT = "$mp_input_change";
20565 var MP_EV_RAGE_CLICK = "$mp_rage_click";
20566 var MP_EV_SCROLL = "$mp_scroll";
20567 var MP_EV_SUBMIT = "$mp_submit";
20568 var MP_EV_PAGE_LEAVE = "$mp_page_leave";
20569 /**
20570 * Autocapture: manages automatic event tracking
20571 * @constructor
20572 */
20573 var Autocapture = function(mp) {
20574 this.mp = mp;
20575 this.maxScrollViewDepth = 0;
20576 this.hasTrackedScrollSession = false;
20577 this.previousScrollHeight = 0;
20578 };
20579 Autocapture.prototype.init = function() {
20580 if (!minDOMApisSupported()) {
20581 logger$1.critical("Autocapture unavailable: missing required DOM APIs");
20582 return;
20583 }
20584 this.initPageListeners();
20585 this.initPageviewTracking();
20586 this.initClickTracking();
20587 this.initDeadClickTracking();
20588 this.initInputTracking();
20589 this.initScrollTracking();
20590 this.initSubmitTracking();
20591 this.initRageClickTracking();
20592 this.initPageLeaveTracking();
20593 };
20594 Autocapture.prototype.getFullConfig = function() {
20595 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
20596 if (!autocaptureConfig) return {};
20597 else if (_$1.isObject(autocaptureConfig)) return _$1.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
20598 else return CONFIG_DEFAULTS$1;
20599 };
20600 Autocapture.prototype.getConfig = function(key) {
20601 return this.getFullConfig()[key];
20602 };
20603 Autocapture.prototype.currentUrlBlocked = function() {
20604 var i;
20605 var currentUrl = _$1.info.currentUrl();
20606 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
20607 if (allowUrlRegexes.length) {
20608 var allowed = false;
20609 for (i = 0; i < allowUrlRegexes.length; i++) {
20610 var allowRegex = allowUrlRegexes[i];
20611 try {
20612 if (currentUrl.match(allowRegex)) {
20613 allowed = true;
20614 break;
20615 }
20616 } catch (err) {
20617 logger$1.critical("Error while checking block URL regex: " + allowRegex, err);
20618 return true;
20619 }
20620 }
20621 if (!allowed) return true;
20622 }
20623 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
20624 if (!blockUrlRegexes || !blockUrlRegexes.length) return false;
20625 for (i = 0; i < blockUrlRegexes.length; i++) try {
20626 if (currentUrl.match(blockUrlRegexes[i])) return true;
20627 } catch (err) {
20628 logger$1.critical("Error while checking block URL regex: " + blockUrlRegexes[i], err);
20629 return true;
20630 }
20631 return false;
20632 };
20633 Autocapture.prototype.pageviewTrackingConfig = function() {
20634 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) return this.getConfig(CONFIG_TRACK_PAGEVIEW);
20635 else return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
20636 };
20637 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
20638 if (this.currentUrlBlocked()) return;
20639 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK) || mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK) || mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK));
20640 var props = getPropsForDOMEvent(ev, {
20641 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
20642 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
20643 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
20644 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
20645 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
20646 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
20647 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
20648 capturedForHeatMap: isCapturedForHeatMap
20649 });
20650 if (props) {
20651 _$1.extend(props, DEFAULT_PROPS);
20652 this.mp.track(mpEventName, props);
20653 }
20654 };
20655 Autocapture.prototype.initPageListeners = function() {
20656 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
20657 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
20658 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config("record_heatmap_data")) return;
20659 this.listenerPopstate = function() {
20660 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20661 };
20662 this.listenerHashchange = function() {
20663 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20664 };
20665 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
20666 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
20667 var nativePushState = win.history.pushState;
20668 if (typeof nativePushState === "function") win.history.pushState = function(state, unused, url) {
20669 nativePushState.call(win.history, state, unused, url);
20670 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20671 };
20672 var nativeReplaceState = win.history.replaceState;
20673 if (typeof nativeReplaceState === "function") win.history.replaceState = function(state, unused, url) {
20674 nativeReplaceState.call(win.history, state, unused, url);
20675 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
20676 };
20677 };
20678 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
20679 var config = this.getConfig(configKey);
20680 if (!config) return null;
20681 if (config === true) return {};
20682 if (typeof config === "object") return config;
20683 return {};
20684 };
20685 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
20686 if (this.hasTrackedScrollSession) return;
20687 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) return;
20688 this.hasTrackedScrollSession = true;
20689 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20690 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
20691 var foldLinePercentage = Math.round(viewportHeight / currentScrollHeight * 100);
20692 if (currentScrollHeight <= viewportHeight) {
20693 scrollPercentage = 100;
20694 foldLinePercentage = 100;
20695 }
20696 var props = _$1.extend({
20697 "$max_scroll_view_depth": this.maxScrollViewDepth,
20698 "$max_scroll_percentage": scrollPercentage,
20699 "$fold_line_percentage": foldLinePercentage,
20700 "$scroll_height": currentScrollHeight,
20701 "$event_type": ev.type,
20702 "$current_url": currentUrl || _$1.info.currentUrl(),
20703 "$viewportHeight": viewportHeight,
20704 "$viewportWidth": Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
20705 "$captured_for_heatmap": this.mp.is_recording_heatmap_data()
20706 }, DEFAULT_PROPS);
20707 this.mp.track(MP_EV_PAGE_LEAVE, props, { transport: "sendBeacon" });
20708 };
20709 Autocapture.prototype._initScrollDepthTracking = function() {
20710 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
20711 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
20712 if (!this.mp.get_config("record_heatmap_data")) return;
20713 logger$1.log("Initializing scroll depth tracking");
20714 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20715 var scrollEndPolyfill = getPolyfillScrollEndFunction(function() {
20716 if (this.currentUrlBlocked()) return;
20717 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
20718 if (scrollViewHeight > this.maxScrollViewDepth) this.maxScrollViewDepth = scrollViewHeight;
20719 this.previousScrollHeight = document$1.body.scrollHeight;
20720 }.bind(this));
20721 this.listenerScrollDepth = scrollEndPolyfill.listener;
20722 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
20723 };
20724 Autocapture.prototype.initClickTracking = function() {
20725 win.removeEventListener(EV_CLICK, this.listenerClick);
20726 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config("record_heatmap_data")) return;
20727 logger$1.log("Initializing click tracking");
20728 this.listenerClick = function(ev) {
20729 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) return;
20730 this.trackDomEvent(ev, MP_EV_CLICK);
20731 }.bind(this);
20732 win.addEventListener(EV_CLICK, this.listenerClick);
20733 };
20734 Autocapture.prototype.initDeadClickTracking = function() {
20735 if (!this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK) && !this.mp.get_config("record_heatmap_data")) {
20736 this.stopDeadClickTracking();
20737 return;
20738 }
20739 logger$1.log("Initializing dead click tracking");
20740 if (!this._deadClickTracker) {
20741 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
20742 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
20743 }.bind(this));
20744 this._deadClickTracker.startTracking();
20745 }
20746 if (!this.listenerDeadClick) {
20747 this.listenerDeadClick = function(ev) {
20748 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
20749 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) return;
20750 if (this.currentUrlBlocked()) return;
20751 var normalizedConfig = currentDeadClickConfig || {};
20752 if (!normalizedConfig["timeout_ms"]) normalizedConfig["timeout_ms"] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
20753 this._deadClickTracker.trackClick(ev, normalizedConfig);
20754 }.bind(this);
20755 win.addEventListener(EV_CLICK, this.listenerDeadClick);
20756 }
20757 };
20758 Autocapture.prototype.initInputTracking = function() {
20759 win.removeEventListener(EV_CHANGE, this.listenerChange);
20760 if (!this.getConfig(CONFIG_TRACK_INPUT)) return;
20761 logger$1.log("Initializing input tracking");
20762 this.listenerChange = function(ev) {
20763 if (!this.getConfig(CONFIG_TRACK_INPUT)) return;
20764 this.trackDomEvent(ev, MP_EV_INPUT);
20765 }.bind(this);
20766 win.addEventListener(EV_CHANGE, this.listenerChange);
20767 };
20768 Autocapture.prototype.initPageviewTracking = function() {
20769 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
20770 if (!this.pageviewTrackingConfig()) return;
20771 logger$1.log("Initializing pageview tracking");
20772 var previousTrackedUrl = "";
20773 var tracked = false;
20774 if (!this.currentUrlBlocked()) tracked = this.mp.track_pageview(DEFAULT_PROPS);
20775 if (tracked) previousTrackedUrl = _$1.info.currentUrl();
20776 this.listenerLocationchange = safewrap(function() {
20777 if (this.currentUrlBlocked()) return;
20778 var currentUrl = _$1.info.currentUrl();
20779 var shouldTrack = false;
20780 var didPathChange = currentUrl.split("#")[0].split("?")[0] !== previousTrackedUrl.split("#")[0].split("?")[0];
20781 var trackPageviewOption = this.pageviewTrackingConfig();
20782 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) shouldTrack = currentUrl !== previousTrackedUrl;
20783 else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) shouldTrack = currentUrl.split("#")[0] !== previousTrackedUrl.split("#")[0];
20784 else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) shouldTrack = didPathChange;
20785 if (shouldTrack) {
20786 if (this.mp.track_pageview(DEFAULT_PROPS)) previousTrackedUrl = currentUrl;
20787 if (didPathChange) {
20788 this.lastScrollCheckpoint = 0;
20789 logger$1.log("Path change: re-initializing scroll depth checkpoints");
20790 }
20791 }
20792 }.bind(this));
20793 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
20794 };
20795 Autocapture.prototype.initRageClickTracking = function() {
20796 win.removeEventListener(EV_CLICK, this.listenerRageClick);
20797 if (!this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK) && !this.mp.get_config("record_heatmap_data")) return;
20798 logger$1.log("Initializing rage click tracking");
20799 if (!this._rageClickTracker) this._rageClickTracker = new RageClickTracker();
20800 this.listenerRageClick = function(ev) {
20801 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
20802 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) return;
20803 if (this.currentUrlBlocked()) return;
20804 if (this._rageClickTracker.isRageClick(ev["pageX"], ev["pageY"], currentRageClickConfig)) this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
20805 }.bind(this);
20806 win.addEventListener(EV_CLICK, this.listenerRageClick);
20807 };
20808 Autocapture.prototype.initScrollTracking = function() {
20809 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
20810 win.removeEventListener(EV_SCROLL, this.listenerScroll);
20811 if (!this.getConfig(CONFIG_TRACK_SCROLL)) return;
20812 logger$1.log("Initializing scroll tracking");
20813 this.lastScrollCheckpoint = 0;
20814 var scrollEndPolyfill = getPolyfillScrollEndFunction(function() {
20815 if (!this.getConfig(CONFIG_TRACK_SCROLL)) return;
20816 if (this.currentUrlBlocked()) return;
20817 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
20818 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || []).slice().sort(function(a, b) {
20819 return a - b;
20820 });
20821 var scrollTop = win.scrollY;
20822 var props = _$1.extend({ "$scroll_top": scrollTop }, DEFAULT_PROPS);
20823 try {
20824 var scrollHeight = document$1.body.scrollHeight;
20825 var scrollPercentage = Math.round(scrollTop / (scrollHeight - win.innerHeight) * 100);
20826 props["$scroll_height"] = scrollHeight;
20827 props["$scroll_percentage"] = scrollPercentage;
20828 if (scrollPercentage > this.lastScrollCheckpoint) for (var i = 0; i < scrollCheckpoints.length; i++) {
20829 var checkpoint = scrollCheckpoints[i];
20830 if (scrollPercentage >= checkpoint && this.lastScrollCheckpoint < checkpoint) {
20831 props["$scroll_checkpoint"] = checkpoint;
20832 this.lastScrollCheckpoint = checkpoint;
20833 shouldTrack = true;
20834 }
20835 }
20836 } catch (err) {
20837 logger$1.critical("Error while calculating scroll percentage", err);
20838 }
20839 if (shouldTrack) this.mp.track(MP_EV_SCROLL, props);
20840 }.bind(this));
20841 this.listenerScroll = scrollEndPolyfill.listener;
20842 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
20843 };
20844 Autocapture.prototype.initSubmitTracking = function() {
20845 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
20846 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) return;
20847 logger$1.log("Initializing submit tracking");
20848 this.listenerSubmit = function(ev) {
20849 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) return;
20850 this.trackDomEvent(ev, MP_EV_SUBMIT);
20851 }.bind(this);
20852 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
20853 };
20854 Autocapture.prototype.initPageLeaveTracking = function() {
20855 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
20856 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
20857 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
20858 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config("record_heatmap_data")) return;
20859 logger$1.log("Initializing page visibility tracking.");
20860 this._initScrollDepthTracking();
20861 var previousTrackedUrl = _$1.info.currentUrl();
20862 this.listenerPageLoad = function() {
20863 this.previousScrollHeight = document$1.body.scrollHeight;
20864 }.bind(this);
20865 win.addEventListener(EV_LOAD, this.listenerPageLoad);
20866 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
20867 if (this.currentUrlBlocked()) return;
20868 var currentUrl = _$1.info.currentUrl();
20869 if (currentUrl !== previousTrackedUrl) {
20870 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
20871 previousTrackedUrl = currentUrl;
20872 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
20873 this.previousScrollHeight = document$1.body.scrollHeight;
20874 this.hasTrackedScrollSession = false;
20875 }
20876 }.bind(this));
20877 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
20878 this.listenerPageLeaveVisibilitychange = function(ev) {
20879 if (document$1.hidden) this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
20880 }.bind(this);
20881 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
20882 };
20883 Autocapture.prototype.stopDeadClickTracking = function() {
20884 if (this.listenerDeadClick) {
20885 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
20886 this.listenerDeadClick = null;
20887 }
20888 if (this._deadClickTracker) {
20889 this._deadClickTracker.stopTracking();
20890 this._deadClickTracker = null;
20891 }
20892 };
20893 safewrapClass(Autocapture);
20894 var logger = console_with_prefix("flags");
20895 var FLAGS_CONFIG_KEY = "flags";
20896 var CONFIG_CONTEXT = "context";
20897 var CONFIG_DEFAULTS = {};
20898 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
20899 /**
20900 * FeatureFlagManager: support for Mixpanel's feature flagging product
20901 * @constructor
20902 */
20903 var FeatureFlagManager = function(initOptions) {
20904 this.fetch = win["fetch"];
20905 this.getFullApiRoute = initOptions.getFullApiRoute;
20906 this.getMpConfig = initOptions.getConfigFunc;
20907 this.setMpConfig = initOptions.setConfigFunc;
20908 this.getMpProperty = initOptions.getPropertyFunc;
20909 this.track = initOptions.trackingFunc;
20910 };
20911 FeatureFlagManager.prototype.init = function() {
20912 if (!this.minApisSupported()) {
20913 logger.critical("Feature Flags unavailable: missing minimum required APIs");
20914 return;
20915 }
20916 this.flags = null;
20917 this.fetchFlags();
20918 this.trackedFeatures = /* @__PURE__ */ new Set();
20919 };
20920 FeatureFlagManager.prototype.getFullConfig = function() {
20921 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
20922 if (!ffConfig) return {};
20923 else if (_$1.isObject(ffConfig)) return _$1.extend({}, CONFIG_DEFAULTS, ffConfig);
20924 else return CONFIG_DEFAULTS;
20925 };
20926 FeatureFlagManager.prototype.getConfig = function(key) {
20927 return this.getFullConfig()[key];
20928 };
20929 FeatureFlagManager.prototype.isSystemEnabled = function() {
20930 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
20931 };
20932 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
20933 if (!this.isSystemEnabled()) {
20934 logger.critical("Feature Flags not enabled, cannot update context");
20935 return Promise.resolve();
20936 }
20937 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
20938 if (!_$1.isObject(ffConfig)) ffConfig = {};
20939 var oldContext = options && options["replace"] ? {} : this.getConfig(CONFIG_CONTEXT);
20940 ffConfig[CONFIG_CONTEXT] = _$1.extend({}, oldContext, newContext);
20941 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
20942 return this.fetchFlags();
20943 };
20944 FeatureFlagManager.prototype.areFlagsReady = function() {
20945 if (!this.isSystemEnabled()) logger.error("Feature Flags not enabled");
20946 return !!this.flags;
20947 };
20948 FeatureFlagManager.prototype.fetchFlags = function() {
20949 if (!this.isSystemEnabled()) return Promise.resolve();
20950 var distinctId = this.getMpProperty("distinct_id");
20951 var deviceId = this.getMpProperty("$device_id");
20952 var traceparent = generateTraceparent();
20953 logger.log("Fetching flags for distinct ID: " + distinctId);
20954 var context = _$1.extend({
20955 "distinct_id": distinctId,
20956 "device_id": deviceId
20957 }, this.getConfig(CONFIG_CONTEXT));
20958 var searchParams = new URLSearchParams();
20959 searchParams.set("context", JSON.stringify(context));
20960 searchParams.set("token", this.getMpConfig("token"));
20961 searchParams.set("mp_lib", "web");
20962 searchParams.set("$lib_version", Config.LIB_VERSION);
20963 var url = this.getFullApiRoute() + "?" + searchParams.toString();
20964 this._fetchInProgressStartTime = Date.now();
20965 this.fetchPromise = this.fetch.call(win, url, {
20966 "method": "GET",
20967 "headers": {
20968 "Authorization": "Basic " + btoa(this.getMpConfig("token") + ":"),
20969 "traceparent": traceparent
20970 }
20971 }).then(function(response) {
20972 this.markFetchComplete();
20973 return response.json().then(function(responseBody) {
20974 var responseFlags = responseBody["flags"];
20975 if (!responseFlags) throw new Error("No flags in API response");
20976 var flags = /* @__PURE__ */ new Map();
20977 _$1.each(responseFlags, function(data, key) {
20978 flags.set(key, {
20979 "key": data["variant_key"],
20980 "value": data["variant_value"],
20981 "experiment_id": data["experiment_id"],
20982 "is_experiment_active": data["is_experiment_active"],
20983 "is_qa_tester": data["is_qa_tester"]
20984 });
20985 });
20986 this.flags = flags;
20987 this._traceparent = traceparent;
20988 }.bind(this)).catch(function(error) {
20989 this.markFetchComplete();
20990 logger.error(error);
20991 }.bind(this));
20992 }.bind(this)).catch(function(error) {
20993 this.markFetchComplete();
20994 logger.error(error);
20995 }.bind(this));
20996 return this.fetchPromise;
20997 };
20998 FeatureFlagManager.prototype.markFetchComplete = function() {
20999 if (!this._fetchInProgressStartTime) {
21000 logger.error("Fetch in progress started time not set, cannot mark fetch complete");
21001 return;
21002 }
21003 this._fetchStartTime = this._fetchInProgressStartTime;
21004 this._fetchCompleteTime = Date.now();
21005 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
21006 this._fetchInProgressStartTime = null;
21007 };
21008 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
21009 if (!this.fetchPromise) return new Promise(function(resolve) {
21010 logger.critical("Feature Flags not initialized");
21011 resolve(fallback);
21012 });
21013 return this.fetchPromise.then(function() {
21014 return this.getVariantSync(featureName, fallback);
21015 }.bind(this)).catch(function(error) {
21016 logger.error(error);
21017 return fallback;
21018 });
21019 };
21020 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
21021 if (!this.areFlagsReady()) {
21022 logger.log("Flags not loaded yet");
21023 return fallback;
21024 }
21025 var feature = this.flags.get(featureName);
21026 if (!feature) {
21027 logger.log("No flag found: \"" + featureName + "\"");
21028 return fallback;
21029 }
21030 this.trackFeatureCheck(featureName, feature);
21031 return feature;
21032 };
21033 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
21034 return this.getVariant(featureName, { "value": fallbackValue }).then(function(feature) {
21035 return feature["value"];
21036 }).catch(function(error) {
21037 logger.error(error);
21038 return fallbackValue;
21039 });
21040 };
21041 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
21042 logger.critical("mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.");
21043 return this.getVariantValue(featureName, fallbackValue);
21044 };
21045 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
21046 return this.getVariantSync(featureName, { "value": fallbackValue })["value"];
21047 };
21048 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
21049 return this.getVariantValue(featureName).then(function() {
21050 return this.isEnabledSync(featureName, fallbackValue);
21051 }.bind(this)).catch(function(error) {
21052 logger.error(error);
21053 return fallbackValue;
21054 });
21055 };
21056 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
21057 fallbackValue = fallbackValue || false;
21058 var val = this.getVariantValueSync(featureName, fallbackValue);
21059 if (val !== true && val !== false) {
21060 logger.error("Feature flag \"" + featureName + "\" value: " + val + " is not a boolean; returning fallback value: " + fallbackValue);
21061 val = fallbackValue;
21062 }
21063 return val;
21064 };
21065 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
21066 if (this.trackedFeatures.has(featureName)) return;
21067 this.trackedFeatures.add(featureName);
21068 var trackingProperties = {
21069 "Experiment name": featureName,
21070 "Variant name": feature["key"],
21071 "$experiment_type": "feature_flag",
21072 "Variant fetch start time": new Date(this._fetchStartTime).toISOString(),
21073 "Variant fetch complete time": new Date(this._fetchCompleteTime).toISOString(),
21074 "Variant fetch latency (ms)": this._fetchLatency,
21075 "Variant fetch traceparent": this._traceparent
21076 };
21077 if (feature["experiment_id"] !== "undefined") trackingProperties["$experiment_id"] = feature["experiment_id"];
21078 if (feature["is_experiment_active"] !== "undefined") trackingProperties["$is_experiment_active"] = feature["is_experiment_active"];
21079 if (feature["is_qa_tester"] !== "undefined") trackingProperties["$is_qa_tester"] = feature["is_qa_tester"];
21080 this.track("$experiment_started", trackingProperties);
21081 };
21082 FeatureFlagManager.prototype.minApisSupported = function() {
21083 return !!this.fetch && typeof Promise !== "undefined" && typeof Map !== "undefined" && typeof Set !== "undefined";
21084 };
21085 safewrapClass(FeatureFlagManager);
21086 FeatureFlagManager.prototype["are_flags_ready"] = FeatureFlagManager.prototype.areFlagsReady;
21087 FeatureFlagManager.prototype["get_variant"] = FeatureFlagManager.prototype.getVariant;
21088 FeatureFlagManager.prototype["get_variant_sync"] = FeatureFlagManager.prototype.getVariantSync;
21089 FeatureFlagManager.prototype["get_variant_value"] = FeatureFlagManager.prototype.getVariantValue;
21090 FeatureFlagManager.prototype["get_variant_value_sync"] = FeatureFlagManager.prototype.getVariantValueSync;
21091 FeatureFlagManager.prototype["is_enabled"] = FeatureFlagManager.prototype.isEnabled;
21092 FeatureFlagManager.prototype["is_enabled_sync"] = FeatureFlagManager.prototype.isEnabledSync;
21093 FeatureFlagManager.prototype["update_context"] = FeatureFlagManager.prototype.updateContext;
21094 FeatureFlagManager.prototype["get_feature_data"] = FeatureFlagManager.prototype.getFeatureData;
21095 /**
21096 * DomTracker Object
21097 * @constructor
21098 */
21099 var DomTracker = function() {};
21100 DomTracker.prototype.create_properties = function() {};
21101 DomTracker.prototype.event_handler = function() {};
21102 DomTracker.prototype.after_track_handler = function() {};
21103 DomTracker.prototype.init = function(mixpanel_instance) {
21104 this.mp = mixpanel_instance;
21105 return this;
21106 };
21107 /**
21108 * @param {Object|string} query
21109 * @param {string} event_name
21110 * @param {Object=} properties
21111 * @param {function=} user_callback
21112 */
21113 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
21114 var that = this;
21115 var elements = _$1.dom_query(query);
21116 if (elements.length === 0) {
21117 console$1.error("The DOM query (" + query + ") returned 0 elements");
21118 return;
21119 }
21120 _$1.each(elements, function(element) {
21121 _$1.register_event(element, this.override_event, function(e) {
21122 var options = {};
21123 var props = that.create_properties(properties, this);
21124 var timeout = that.mp.get_config("track_links_timeout");
21125 that.event_handler(e, this, options);
21126 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
21127 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
21128 });
21129 }, this);
21130 return true;
21131 };
21132 /**
21133 * @param {function} user_callback
21134 * @param {Object} props
21135 * @param {boolean=} timeout_occured
21136 */
21137 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
21138 timeout_occured = timeout_occured || false;
21139 var that = this;
21140 return function() {
21141 if (options.callback_fired) return;
21142 options.callback_fired = true;
21143 if (user_callback && user_callback(timeout_occured, props) === false) return;
21144 that.after_track_handler(props, options, timeout_occured);
21145 };
21146 };
21147 DomTracker.prototype.create_properties = function(properties, element) {
21148 var props;
21149 if (typeof properties === "function") props = properties(element);
21150 else props = _$1.extend({}, properties);
21151 return props;
21152 };
21153 /**
21154 * LinkTracker Object
21155 * @constructor
21156 * @extends DomTracker
21157 */
21158 var LinkTracker = function() {
21159 this.override_event = "click";
21160 };
21161 _$1.inherit(LinkTracker, DomTracker);
21162 LinkTracker.prototype.create_properties = function(properties, element) {
21163 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
21164 if (element.href) props["url"] = element.href;
21165 return props;
21166 };
21167 LinkTracker.prototype.event_handler = function(evt, element, options) {
21168 options.new_tab = evt.which === 2 || evt.metaKey || evt.ctrlKey || element.target === "_blank";
21169 options.href = element.href;
21170 if (!options.new_tab) evt.preventDefault();
21171 };
21172 LinkTracker.prototype.after_track_handler = function(props, options) {
21173 if (options.new_tab) return;
21174 setTimeout(function() {
21175 window.location = options.href;
21176 }, 0);
21177 };
21178 /**
21179 * FormTracker Object
21180 * @constructor
21181 * @extends DomTracker
21182 */
21183 var FormTracker = function() {
21184 this.override_event = "submit";
21185 };
21186 _$1.inherit(FormTracker, DomTracker);
21187 FormTracker.prototype.event_handler = function(evt, element, options) {
21188 options.element = element;
21189 evt.preventDefault();
21190 };
21191 FormTracker.prototype.after_track_handler = function(props, options) {
21192 setTimeout(function() {
21193 options.element.submit();
21194 }, 0);
21195 };
21196 /** @const */ var SET_ACTION = "$set";
21197 /** @const */ var SET_ONCE_ACTION = "$set_once";
21198 /** @const */ var UNSET_ACTION = "$unset";
21199 /** @const */ var ADD_ACTION = "$add";
21200 /** @const */ var APPEND_ACTION = "$append";
21201 /** @const */ var UNION_ACTION = "$union";
21202 /** @const */ var REMOVE_ACTION = "$remove";
21203 /** @const */ var DELETE_ACTION = "$delete";
21204 var apiActions = {
21205 set_action: function(prop, to) {
21206 var data = {};
21207 var $set = {};
21208 if (_$1.isObject(prop)) _$1.each(prop, function(v, k) {
21209 if (!this._is_reserved_property(k)) $set[k] = v;
21210 }, this);
21211 else $set[prop] = to;
21212 data[SET_ACTION] = $set;
21213 return data;
21214 },
21215 unset_action: function(prop) {
21216 var data = {};
21217 var $unset = [];
21218 if (!_$1.isArray(prop)) prop = [prop];
21219 _$1.each(prop, function(k) {
21220 if (!this._is_reserved_property(k)) $unset.push(k);
21221 }, this);
21222 data[UNSET_ACTION] = $unset;
21223 return data;
21224 },
21225 set_once_action: function(prop, to) {
21226 var data = {};
21227 var $set_once = {};
21228 if (_$1.isObject(prop)) _$1.each(prop, function(v, k) {
21229 if (!this._is_reserved_property(k)) $set_once[k] = v;
21230 }, this);
21231 else $set_once[prop] = to;
21232 data[SET_ONCE_ACTION] = $set_once;
21233 return data;
21234 },
21235 union_action: function(list_name, values) {
21236 var data = {};
21237 var $union = {};
21238 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21239 if (!this._is_reserved_property(k)) $union[k] = _$1.isArray(v) ? v : [v];
21240 }, this);
21241 else $union[list_name] = _$1.isArray(values) ? values : [values];
21242 data[UNION_ACTION] = $union;
21243 return data;
21244 },
21245 append_action: function(list_name, value) {
21246 var data = {};
21247 var $append = {};
21248 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21249 if (!this._is_reserved_property(k)) $append[k] = v;
21250 }, this);
21251 else $append[list_name] = value;
21252 data[APPEND_ACTION] = $append;
21253 return data;
21254 },
21255 remove_action: function(list_name, value) {
21256 var data = {};
21257 var $remove = {};
21258 if (_$1.isObject(list_name)) _$1.each(list_name, function(v, k) {
21259 if (!this._is_reserved_property(k)) $remove[k] = v;
21260 }, this);
21261 else $remove[list_name] = value;
21262 data[REMOVE_ACTION] = $remove;
21263 return data;
21264 },
21265 delete_action: function() {
21266 var data = {};
21267 data[DELETE_ACTION] = "";
21268 return data;
21269 }
21270 };
21271 /**
21272 * Mixpanel Group Object
21273 * @constructor
21274 */
21275 var MixpanelGroup = function() {};
21276 _$1.extend(MixpanelGroup.prototype, apiActions);
21277 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
21278 this._mixpanel = mixpanel_instance;
21279 this._group_key = group_key;
21280 this._group_id = group_id;
21281 };
21282 /**
21283 * Set properties on a group.
21284 *
21285 * ### Usage:
21286 *
21287 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
21288 *
21289 * // or set multiple properties at once
21290 * mixpanel.get_group('company', 'mixpanel').set({
21291 * 'Location': '405 Howard',
21292 * 'Founded' : 2009,
21293 * });
21294 * // properties can be strings, integers, dates, or lists
21295 *
21296 * @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.
21297 * @param {*} [to] A value to set on the given property name
21298 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21299 */
21300 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
21301 var data = this.set_action(prop, to);
21302 if (_$1.isObject(prop)) callback = to;
21303 return this._send_request(data, callback);
21304 });
21305 /**
21306 * Set properties on a group, only if they do not yet exist.
21307 * This will not overwrite previous group property values, unlike
21308 * group.set().
21309 *
21310 * ### Usage:
21311 *
21312 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
21313 *
21314 * // or set multiple properties at once
21315 * mixpanel.get_group('company', 'mixpanel').set_once({
21316 * 'Location': '405 Howard',
21317 * 'Founded' : 2009,
21318 * });
21319 * // properties can be strings, integers, lists or dates
21320 *
21321 * @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.
21322 * @param {*} [to] A value to set on the given property name
21323 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21324 */
21325 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
21326 var data = this.set_once_action(prop, to);
21327 if (_$1.isObject(prop)) callback = to;
21328 return this._send_request(data, callback);
21329 });
21330 /**
21331 * Unset properties on a group permanently.
21332 *
21333 * ### Usage:
21334 *
21335 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
21336 *
21337 * @param {String} prop The name of the property.
21338 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21339 */
21340 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
21341 var data = this.unset_action(prop);
21342 return this._send_request(data, callback);
21343 });
21344 /**
21345 * Merge a given list with a list-valued group property, excluding duplicate values.
21346 *
21347 * ### Usage:
21348 *
21349 * // merge a value to a list, creating it if needed
21350 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
21351 *
21352 * @param {String} list_name Name of the property.
21353 * @param {Array} values Values to merge with the given property
21354 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21355 */
21356 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
21357 if (_$1.isObject(list_name)) callback = values;
21358 var data = this.union_action(list_name, values);
21359 return this._send_request(data, callback);
21360 });
21361 /**
21362 * Permanently delete a group.
21363 *
21364 * ### Usage:
21365 *
21366 * mixpanel.get_group('company', 'mixpanel').delete();
21367 *
21368 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21369 */
21370 MixpanelGroup.prototype["delete"] = addOptOutCheckMixpanelGroup(function(callback) {
21371 var data = this.delete_action();
21372 return this._send_request(data, callback);
21373 });
21374 /**
21375 * Remove a property from a group. The value will be ignored if doesn't exist.
21376 *
21377 * ### Usage:
21378 *
21379 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
21380 *
21381 * @param {String} list_name Name of the property.
21382 * @param {Object} value Value to remove from the given group property
21383 * @param {Function} [callback] If provided, the callback will be called after the tracking event
21384 */
21385 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
21386 var data = this.remove_action(list_name, value);
21387 return this._send_request(data, callback);
21388 });
21389 MixpanelGroup.prototype._send_request = function(data, callback) {
21390 data["$group_key"] = this._group_key;
21391 data["$group_id"] = this._group_id;
21392 data["$token"] = this._get_config("token");
21393 var date_encoded_data = _$1.encodeDates(data);
21394 return this._mixpanel._track_or_batch({
21395 type: "groups",
21396 data: date_encoded_data,
21397 endpoint: this._mixpanel.get_api_host("groups") + "/" + this._get_config("api_routes")["groups"],
21398 batcher: this._mixpanel.request_batchers.groups
21399 }, callback);
21400 };
21401 MixpanelGroup.prototype._is_reserved_property = function(prop) {
21402 return prop === "$group_key" || prop === "$group_id";
21403 };
21404 MixpanelGroup.prototype._get_config = function(conf) {
21405 return this._mixpanel.get_config(conf);
21406 };
21407 MixpanelGroup.prototype.toString = function() {
21408 return this._mixpanel.toString() + ".group." + this._group_key + "." + this._group_id;
21409 };
21410 MixpanelGroup.prototype["remove"] = MixpanelGroup.prototype.remove;
21411 MixpanelGroup.prototype["set"] = MixpanelGroup.prototype.set;
21412 MixpanelGroup.prototype["set_once"] = MixpanelGroup.prototype.set_once;
21413 MixpanelGroup.prototype["union"] = MixpanelGroup.prototype.union;
21414 MixpanelGroup.prototype["unset"] = MixpanelGroup.prototype.unset;
21415 MixpanelGroup.prototype["toString"] = MixpanelGroup.prototype.toString;
21416 /**
21417 * Mixpanel People Object
21418 * @constructor
21419 */
21420 var MixpanelPeople = function() {};
21421 _$1.extend(MixpanelPeople.prototype, apiActions);
21422 MixpanelPeople.prototype._init = function(mixpanel_instance) {
21423 this._mixpanel = mixpanel_instance;
21424 };
21425 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
21426 var data = this.set_action(prop, to);
21427 if (_$1.isObject(prop)) callback = to;
21428 if (this._get_config("save_referrer")) this._mixpanel["persistence"].update_referrer_info(document.referrer);
21429 data[SET_ACTION] = _$1.extend({}, _$1.info.people_properties(), data[SET_ACTION]);
21430 return this._send_request(data, callback);
21431 });
21432 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
21433 var data = this.set_once_action(prop, to);
21434 if (_$1.isObject(prop)) callback = to;
21435 return this._send_request(data, callback);
21436 });
21437 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
21438 var data = this.unset_action(prop);
21439 return this._send_request(data, callback);
21440 });
21441 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
21442 var data = {};
21443 var $add = {};
21444 if (_$1.isObject(prop)) {
21445 _$1.each(prop, function(v, k) {
21446 if (!this._is_reserved_property(k)) if (isNaN(parseFloat(v))) {
21447 console$1.error("Invalid increment value passed to mixpanel.people.increment - must be a number");
21448 return;
21449 } else $add[k] = v;
21450 }, this);
21451 callback = by;
21452 } else {
21453 if (_$1.isUndefined(by)) by = 1;
21454 $add[prop] = by;
21455 }
21456 data[ADD_ACTION] = $add;
21457 return this._send_request(data, callback);
21458 });
21459 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
21460 if (_$1.isObject(list_name)) callback = value;
21461 var data = this.append_action(list_name, value);
21462 return this._send_request(data, callback);
21463 });
21464 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
21465 if (_$1.isObject(list_name)) callback = value;
21466 var data = this.remove_action(list_name, value);
21467 return this._send_request(data, callback);
21468 });
21469 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
21470 if (_$1.isObject(list_name)) callback = values;
21471 var data = this.union_action(list_name, values);
21472 return this._send_request(data, callback);
21473 });
21474 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
21475 console$1.error("mixpanel.people.track_charge() is deprecated and no longer has any effect.");
21476 });
21477 MixpanelPeople.prototype.clear_charges = function(callback) {
21478 return this.set("$transactions", [], callback);
21479 };
21480 MixpanelPeople.prototype.delete_user = function() {
21481 if (!this._identify_called()) {
21482 console$1.error("mixpanel.people.delete_user() requires you to call identify() first");
21483 return;
21484 }
21485 var data = { "$delete": this._mixpanel.get_distinct_id() };
21486 return this._send_request(data);
21487 };
21488 MixpanelPeople.prototype.toString = function() {
21489 return this._mixpanel.toString() + ".people";
21490 };
21491 MixpanelPeople.prototype._send_request = function(data, callback) {
21492 data["$token"] = this._get_config("token");
21493 data["$distinct_id"] = this._mixpanel.get_distinct_id();
21494 var device_id = this._mixpanel.get_property("$device_id");
21495 var user_id = this._mixpanel.get_property("$user_id");
21496 var had_persisted_distinct_id = this._mixpanel.get_property("$had_persisted_distinct_id");
21497 if (device_id) data["$device_id"] = device_id;
21498 if (user_id) data["$user_id"] = user_id;
21499 if (had_persisted_distinct_id) data["$had_persisted_distinct_id"] = had_persisted_distinct_id;
21500 var date_encoded_data = _$1.encodeDates(data);
21501 if (!this._identify_called()) {
21502 this._enqueue(data);
21503 if (!_$1.isUndefined(callback)) if (this._get_config("verbose")) callback({
21504 status: -1,
21505 error: null
21506 });
21507 else callback(-1);
21508 return _$1.truncate(date_encoded_data, 255);
21509 }
21510 return this._mixpanel._track_or_batch({
21511 type: "people",
21512 data: date_encoded_data,
21513 endpoint: this._mixpanel.get_api_host("people") + "/" + this._get_config("api_routes")["engage"],
21514 batcher: this._mixpanel.request_batchers.people
21515 }, callback);
21516 };
21517 MixpanelPeople.prototype._get_config = function(conf_var) {
21518 return this._mixpanel.get_config(conf_var);
21519 };
21520 MixpanelPeople.prototype._identify_called = function() {
21521 return this._mixpanel._flags.identify_called === true;
21522 };
21523 MixpanelPeople.prototype._enqueue = function(data) {
21524 if (SET_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(SET_ACTION, data);
21525 else if (SET_ONCE_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(SET_ONCE_ACTION, data);
21526 else if (UNSET_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(UNSET_ACTION, data);
21527 else if (ADD_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(ADD_ACTION, data);
21528 else if (APPEND_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(APPEND_ACTION, data);
21529 else if (REMOVE_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(REMOVE_ACTION, data);
21530 else if (UNION_ACTION in data) this._mixpanel["persistence"]._add_to_people_queue(UNION_ACTION, data);
21531 else console$1.error("Invalid call to _enqueue():", data);
21532 };
21533 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
21534 var _this = this;
21535 var queued_data = _$1.extend({}, this._mixpanel["persistence"].load_queue(action));
21536 var action_params = queued_data;
21537 if (!_$1.isUndefined(queued_data) && _$1.isObject(queued_data) && !_$1.isEmptyObject(queued_data)) {
21538 _this._mixpanel["persistence"]._pop_from_people_queue(action, queued_data);
21539 _this._mixpanel["persistence"].save();
21540 if (queue_to_params_fn) action_params = queue_to_params_fn(queued_data);
21541 action_method.call(_this, action_params, function(response, data) {
21542 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(action, queued_data);
21543 if (!_$1.isUndefined(callback)) callback(response, data);
21544 });
21545 }
21546 };
21547 MixpanelPeople.prototype._flush = function(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback) {
21548 var _this = this;
21549 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
21550 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
21551 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) {
21552 return _$1.keys(queue);
21553 });
21554 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
21555 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
21556 var $append_queue = this._mixpanel["persistence"].load_queue(APPEND_ACTION);
21557 if (!_$1.isUndefined($append_queue) && _$1.isArray($append_queue) && $append_queue.length) {
21558 var $append_item;
21559 var append_callback = function(response, data) {
21560 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(APPEND_ACTION, $append_item);
21561 if (!_$1.isUndefined(_append_callback)) _append_callback(response, data);
21562 };
21563 for (var i = $append_queue.length - 1; i >= 0; i--) {
21564 $append_queue = this._mixpanel["persistence"].load_queue(APPEND_ACTION);
21565 $append_item = $append_queue.pop();
21566 _this._mixpanel["persistence"].save();
21567 if (!_$1.isEmptyObject($append_item)) _this.append($append_item, append_callback);
21568 }
21569 }
21570 var $remove_queue = this._mixpanel["persistence"].load_queue(REMOVE_ACTION);
21571 if (!_$1.isUndefined($remove_queue) && _$1.isArray($remove_queue) && $remove_queue.length) {
21572 var $remove_item;
21573 var remove_callback = function(response, data) {
21574 if (response === 0) _this._mixpanel["persistence"]._add_to_people_queue(REMOVE_ACTION, $remove_item);
21575 if (!_$1.isUndefined(_remove_callback)) _remove_callback(response, data);
21576 };
21577 for (var j = $remove_queue.length - 1; j >= 0; j--) {
21578 $remove_queue = this._mixpanel["persistence"].load_queue(REMOVE_ACTION);
21579 $remove_item = $remove_queue.pop();
21580 _this._mixpanel["persistence"].save();
21581 if (!_$1.isEmptyObject($remove_item)) _this.remove($remove_item, remove_callback);
21582 }
21583 }
21584 };
21585 MixpanelPeople.prototype._is_reserved_property = function(prop) {
21586 return prop === "$distinct_id" || prop === "$token" || prop === "$device_id" || prop === "$user_id" || prop === "$had_persisted_distinct_id";
21587 };
21588 MixpanelPeople.prototype["set"] = MixpanelPeople.prototype.set;
21589 MixpanelPeople.prototype["set_once"] = MixpanelPeople.prototype.set_once;
21590 MixpanelPeople.prototype["unset"] = MixpanelPeople.prototype.unset;
21591 MixpanelPeople.prototype["increment"] = MixpanelPeople.prototype.increment;
21592 MixpanelPeople.prototype["append"] = MixpanelPeople.prototype.append;
21593 MixpanelPeople.prototype["remove"] = MixpanelPeople.prototype.remove;
21594 MixpanelPeople.prototype["union"] = MixpanelPeople.prototype.union;
21595 MixpanelPeople.prototype["track_charge"] = MixpanelPeople.prototype.track_charge;
21596 MixpanelPeople.prototype["clear_charges"] = MixpanelPeople.prototype.clear_charges;
21597 MixpanelPeople.prototype["delete_user"] = MixpanelPeople.prototype.delete_user;
21598 MixpanelPeople.prototype["toString"] = MixpanelPeople.prototype.toString;
21599 /** @const */ var SET_QUEUE_KEY = "__mps";
21600 /** @const */ var SET_ONCE_QUEUE_KEY = "__mpso";
21601 /** @const */ var UNSET_QUEUE_KEY = "__mpus";
21602 /** @const */ var ADD_QUEUE_KEY = "__mpa";
21603 /** @const */ var APPEND_QUEUE_KEY = "__mpap";
21604 /** @const */ var REMOVE_QUEUE_KEY = "__mpr";
21605 /** @const */ var UNION_QUEUE_KEY = "__mpu";
21606 /** @const */ var PEOPLE_DISTINCT_ID_KEY = "$people_distinct_id";
21607 /** @const */ var ALIAS_ID_KEY = "__alias";
21608 /** @const */ var EVENT_TIMERS_KEY = "__timers";
21609 /** @const */ var RESERVED_PROPERTIES = [
21610 SET_QUEUE_KEY,
21611 SET_ONCE_QUEUE_KEY,
21612 UNSET_QUEUE_KEY,
21613 ADD_QUEUE_KEY,
21614 APPEND_QUEUE_KEY,
21615 REMOVE_QUEUE_KEY,
21616 UNION_QUEUE_KEY,
21617 PEOPLE_DISTINCT_ID_KEY,
21618 ALIAS_ID_KEY,
21619 EVENT_TIMERS_KEY
21620 ];
21621 /**
21622 * Mixpanel Persistence Object
21623 * @constructor
21624 */
21625 var MixpanelPersistence = function(config) {
21626 this["props"] = {};
21627 this.campaign_params_saved = false;
21628 if (config["persistence_name"]) this.name = "mp_" + config["persistence_name"];
21629 else this.name = "mp_" + config["token"] + "_mixpanel";
21630 var storage_type = config["persistence"];
21631 if (storage_type !== "cookie" && storage_type !== "localStorage") {
21632 console$1.critical("Unknown persistence type " + storage_type + "; falling back to cookie");
21633 storage_type = config["persistence"] = "cookie";
21634 }
21635 if (storage_type === "localStorage" && _$1.localStorage.is_supported()) this.storage = _$1.localStorage;
21636 else this.storage = _$1.cookie;
21637 this.load();
21638 this.update_config(config);
21639 this.upgrade();
21640 this.save();
21641 };
21642 MixpanelPersistence.prototype.properties = function() {
21643 var p = {};
21644 this.load();
21645 _$1.each(this["props"], function(v, k) {
21646 if (!_$1.include(RESERVED_PROPERTIES, k)) p[k] = v;
21647 });
21648 return p;
21649 };
21650 MixpanelPersistence.prototype.load = function() {
21651 if (this.disabled) return;
21652 var entry = this.storage.parse(this.name);
21653 if (entry) this["props"] = _$1.extend({}, entry);
21654 };
21655 MixpanelPersistence.prototype.upgrade = function() {
21656 var old_cookie;
21657 var old_localstorage;
21658 if (this.storage === _$1.localStorage) {
21659 old_cookie = _$1.cookie.parse(this.name);
21660 _$1.cookie.remove(this.name);
21661 _$1.cookie.remove(this.name, true);
21662 if (old_cookie) this.register_once(old_cookie);
21663 } else if (this.storage === _$1.cookie) {
21664 old_localstorage = _$1.localStorage.parse(this.name);
21665 _$1.localStorage.remove(this.name);
21666 if (old_localstorage) this.register_once(old_localstorage);
21667 }
21668 };
21669 MixpanelPersistence.prototype.save = function() {
21670 if (this.disabled) return;
21671 this.storage.set(this.name, JSONStringify(this["props"]), this.expire_days, this.cross_subdomain, this.secure, this.cross_site, this.cookie_domain);
21672 };
21673 MixpanelPersistence.prototype.load_prop = function(key) {
21674 this.load();
21675 return this["props"][key];
21676 };
21677 MixpanelPersistence.prototype.remove = function() {
21678 this.storage.remove(this.name, false, this.cookie_domain);
21679 this.storage.remove(this.name, true, this.cookie_domain);
21680 };
21681 MixpanelPersistence.prototype.clear = function() {
21682 this.remove();
21683 this["props"] = {};
21684 };
21685 /**
21686 * @param {Object} props
21687 * @param {*=} default_value
21688 * @param {number=} days
21689 */
21690 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
21691 if (_$1.isObject(props)) {
21692 if (typeof default_value === "undefined") default_value = "None";
21693 this.expire_days = typeof days === "undefined" ? this.default_expiry : days;
21694 this.load();
21695 _$1.each(props, function(val, prop) {
21696 if (!this["props"].hasOwnProperty(prop) || this["props"][prop] === default_value) this["props"][prop] = val;
21697 }, this);
21698 this.save();
21699 return true;
21700 }
21701 return false;
21702 };
21703 /**
21704 * @param {Object} props
21705 * @param {number=} days
21706 */
21707 MixpanelPersistence.prototype.register = function(props, days) {
21708 if (_$1.isObject(props)) {
21709 this.expire_days = typeof days === "undefined" ? this.default_expiry : days;
21710 this.load();
21711 _$1.extend(this["props"], props);
21712 this.save();
21713 return true;
21714 }
21715 return false;
21716 };
21717 MixpanelPersistence.prototype.unregister = function(prop) {
21718 this.load();
21719 if (prop in this["props"]) {
21720 delete this["props"][prop];
21721 this.save();
21722 }
21723 };
21724 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
21725 this.register(_$1.info.searchInfo(referrer));
21726 };
21727 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
21728 this.register_once({
21729 "$initial_referrer": referrer || "$direct",
21730 "$initial_referring_domain": _$1.info.referringDomain(referrer) || "$direct"
21731 }, "");
21732 };
21733 MixpanelPersistence.prototype.get_referrer_info = function() {
21734 return _$1.strip_empty_properties({
21735 "$initial_referrer": this["props"]["$initial_referrer"],
21736 "$initial_referring_domain": this["props"]["$initial_referring_domain"]
21737 });
21738 };
21739 MixpanelPersistence.prototype.update_config = function(config) {
21740 this.default_expiry = this.expire_days = config["cookie_expiration"];
21741 this.set_disabled(config["disable_persistence"]);
21742 this.set_cookie_domain(config["cookie_domain"]);
21743 this.set_cross_site(config["cross_site_cookie"]);
21744 this.set_cross_subdomain(config["cross_subdomain_cookie"]);
21745 this.set_secure(config["secure_cookie"]);
21746 };
21747 MixpanelPersistence.prototype.set_disabled = function(disabled) {
21748 this.disabled = disabled;
21749 if (this.disabled) this.remove();
21750 else this.save();
21751 };
21752 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
21753 if (cookie_domain !== this.cookie_domain) {
21754 this.remove();
21755 this.cookie_domain = cookie_domain;
21756 this.save();
21757 }
21758 };
21759 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
21760 if (cross_site !== this.cross_site) {
21761 this.cross_site = cross_site;
21762 this.remove();
21763 this.save();
21764 }
21765 };
21766 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
21767 if (cross_subdomain !== this.cross_subdomain) {
21768 this.cross_subdomain = cross_subdomain;
21769 this.remove();
21770 this.save();
21771 }
21772 };
21773 MixpanelPersistence.prototype.get_cross_subdomain = function() {
21774 return this.cross_subdomain;
21775 };
21776 MixpanelPersistence.prototype.set_secure = function(secure) {
21777 if (secure !== this.secure) {
21778 this.secure = secure ? true : false;
21779 this.remove();
21780 this.save();
21781 }
21782 };
21783 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
21784 var q_key = this._get_queue_key(queue);
21785 var q_data = data[queue];
21786 var set_q = this._get_or_create_queue(SET_ACTION);
21787 var set_once_q = this._get_or_create_queue(SET_ONCE_ACTION);
21788 var unset_q = this._get_or_create_queue(UNSET_ACTION);
21789 var add_q = this._get_or_create_queue(ADD_ACTION);
21790 var union_q = this._get_or_create_queue(UNION_ACTION);
21791 var remove_q = this._get_or_create_queue(REMOVE_ACTION, []);
21792 var append_q = this._get_or_create_queue(APPEND_ACTION, []);
21793 if (q_key === SET_QUEUE_KEY) {
21794 _$1.extend(set_q, q_data);
21795 this._pop_from_people_queue(ADD_ACTION, q_data);
21796 this._pop_from_people_queue(UNION_ACTION, q_data);
21797 this._pop_from_people_queue(UNSET_ACTION, q_data);
21798 } else if (q_key === SET_ONCE_QUEUE_KEY) {
21799 _$1.each(q_data, function(v, k) {
21800 if (!(k in set_once_q)) set_once_q[k] = v;
21801 });
21802 this._pop_from_people_queue(UNSET_ACTION, q_data);
21803 } else if (q_key === UNSET_QUEUE_KEY) _$1.each(q_data, function(prop) {
21804 _$1.each([
21805 set_q,
21806 set_once_q,
21807 add_q,
21808 union_q
21809 ], function(enqueued_obj) {
21810 if (prop in enqueued_obj) delete enqueued_obj[prop];
21811 });
21812 _$1.each(append_q, function(append_obj) {
21813 if (prop in append_obj) delete append_obj[prop];
21814 });
21815 unset_q[prop] = true;
21816 });
21817 else if (q_key === ADD_QUEUE_KEY) {
21818 _$1.each(q_data, function(v, k) {
21819 if (k in set_q) set_q[k] += v;
21820 else {
21821 if (!(k in add_q)) add_q[k] = 0;
21822 add_q[k] += v;
21823 }
21824 }, this);
21825 this._pop_from_people_queue(UNSET_ACTION, q_data);
21826 } else if (q_key === UNION_QUEUE_KEY) {
21827 _$1.each(q_data, function(v, k) {
21828 if (_$1.isArray(v)) {
21829 if (!(k in union_q)) union_q[k] = [];
21830 _$1.each(v, function(item) {
21831 if (!_$1.include(union_q[k], item)) union_q[k].push(item);
21832 });
21833 }
21834 });
21835 this._pop_from_people_queue(UNSET_ACTION, q_data);
21836 } else if (q_key === REMOVE_QUEUE_KEY) {
21837 remove_q.push(q_data);
21838 this._pop_from_people_queue(APPEND_ACTION, q_data);
21839 } else if (q_key === APPEND_QUEUE_KEY) {
21840 append_q.push(q_data);
21841 this._pop_from_people_queue(UNSET_ACTION, q_data);
21842 }
21843 console$1.log("MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):");
21844 console$1.log(data);
21845 this.save();
21846 };
21847 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
21848 var q = this["props"][this._get_queue_key(queue)];
21849 if (!_$1.isUndefined(q)) _$1.each(data, function(v, k) {
21850 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) _$1.each(q, function(queued_action) {
21851 if (queued_action[k] === v) delete queued_action[k];
21852 });
21853 else delete q[k];
21854 }, this);
21855 };
21856 MixpanelPersistence.prototype.load_queue = function(queue) {
21857 return this.load_prop(this._get_queue_key(queue));
21858 };
21859 MixpanelPersistence.prototype._get_queue_key = function(queue) {
21860 if (queue === SET_ACTION) return SET_QUEUE_KEY;
21861 else if (queue === SET_ONCE_ACTION) return SET_ONCE_QUEUE_KEY;
21862 else if (queue === UNSET_ACTION) return UNSET_QUEUE_KEY;
21863 else if (queue === ADD_ACTION) return ADD_QUEUE_KEY;
21864 else if (queue === APPEND_ACTION) return APPEND_QUEUE_KEY;
21865 else if (queue === REMOVE_ACTION) return REMOVE_QUEUE_KEY;
21866 else if (queue === UNION_ACTION) return UNION_QUEUE_KEY;
21867 else console$1.error("Invalid queue:", queue);
21868 };
21869 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
21870 var key = this._get_queue_key(queue);
21871 default_val = _$1.isUndefined(default_val) ? {} : default_val;
21872 return this["props"][key] || (this["props"][key] = default_val);
21873 };
21874 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
21875 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
21876 timers[event_name] = timestamp;
21877 this["props"][EVENT_TIMERS_KEY] = timers;
21878 this.save();
21879 };
21880 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
21881 var timestamp = (this.load_prop(EVENT_TIMERS_KEY) || {})[event_name];
21882 if (!_$1.isUndefined(timestamp)) {
21883 delete this["props"][EVENT_TIMERS_KEY][event_name];
21884 this.save();
21885 }
21886 return timestamp;
21887 };
21888 var init_type;
21889 var load_extra_bundle = function(src, _onload) {
21890 throw new Error(src + " not available in this build.");
21891 };
21892 var mixpanel_master;
21893 var INIT_MODULE = 0;
21894 var INIT_SNIPPET = 1;
21895 var IDENTITY_FUNC = function(x) {
21896 return x;
21897 };
21898 /** @const */ var PRIMARY_INSTANCE_NAME = "mixpanel";
21899 /** @const */ var PAYLOAD_TYPE_BASE64 = "base64";
21900 /** @const */ var PAYLOAD_TYPE_JSON = "json";
21901 /** @const */ var DEVICE_ID_PREFIX = "$device:";
21902 var USE_XHR = win.XMLHttpRequest && "withCredentials" in new XMLHttpRequest();
21903 var ENQUEUE_REQUESTS = !USE_XHR && userAgent.indexOf("MSIE") === -1 && userAgent.indexOf("Mozilla") === -1;
21904 var sendBeacon = null;
21905 if (navigator["sendBeacon"]) sendBeacon = function() {
21906 return navigator["sendBeacon"].apply(navigator, arguments);
21907 };
21908 var DEFAULT_API_ROUTES = {
21909 "track": "track/",
21910 "engage": "engage/",
21911 "groups": "groups/",
21912 "record": "record/",
21913 "flags": "flags/"
21914 };
21915 var DEFAULT_CONFIG = {
21916 "api_host": "https://api-js.mixpanel.com",
21917 "api_hosts": {},
21918 "api_routes": DEFAULT_API_ROUTES,
21919 "api_extra_query_params": {},
21920 "api_method": "POST",
21921 "api_transport": "XHR",
21922 "api_payload_format": PAYLOAD_TYPE_BASE64,
21923 "app_host": "https://mixpanel.com",
21924 "autocapture": false,
21925 "cdn": "https://cdn.mxpnl.com",
21926 "cross_site_cookie": false,
21927 "cross_subdomain_cookie": true,
21928 "error_reporter": NOOP_FUNC,
21929 "flags": false,
21930 "persistence": "cookie",
21931 "persistence_name": "",
21932 "cookie_domain": "",
21933 "cookie_name": "",
21934 "loaded": NOOP_FUNC,
21935 "mp_loader": null,
21936 "track_marketing": true,
21937 "track_pageview": false,
21938 "skip_first_touch_marketing": false,
21939 "store_google": true,
21940 "stop_utm_persistence": false,
21941 "save_referrer": true,
21942 "test": false,
21943 "verbose": false,
21944 "img": false,
21945 "debug": false,
21946 "track_links_timeout": 300,
21947 "cookie_expiration": 365,
21948 "upgrade": false,
21949 "disable_persistence": false,
21950 "disable_cookie": false,
21951 "secure_cookie": false,
21952 "ip": true,
21953 "opt_out_tracking_by_default": false,
21954 "opt_out_persistence_by_default": false,
21955 "opt_out_tracking_persistence_type": "localStorage",
21956 "opt_out_tracking_cookie_prefix": null,
21957 "property_blacklist": [],
21958 "xhr_headers": {},
21959 "ignore_dnt": false,
21960 "batch_requests": true,
21961 "batch_size": 50,
21962 "batch_flush_interval_ms": 5e3,
21963 "batch_request_timeout_ms": 9e4,
21964 "batch_autostart": true,
21965 "hooks": {},
21966 "record_block_class": /* @__PURE__ */ new RegExp("^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$"),
21967 "record_block_selector": "img, video, audio",
21968 "record_canvas": false,
21969 "record_collect_fonts": false,
21970 "record_heatmap_data": false,
21971 "record_idle_timeout_ms": 1800 * 1e3,
21972 "record_mask_text_class": /* @__PURE__ */ new RegExp("^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$"),
21973 "record_mask_text_selector": "*",
21974 "record_max_ms": MAX_RECORDING_MS,
21975 "record_min_ms": 0,
21976 "record_sessions_percent": 0,
21977 "recorder_src": "https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js"
21978 };
21979 var DOM_LOADED = false;
21980 /**
21981 * Mixpanel Library Object
21982 * @constructor
21983 */
21984 var MixpanelLib = function() {};
21985 /**
21986 * create_mplib(token:string, config:object, name:string)
21987 *
21988 * This function is used by the init method of MixpanelLib objects
21989 * as well as the main initializer at the end of the JSLib (that
21990 * initializes document.mixpanel as well as any additional instances
21991 * declared before this file has loaded).
21992 */
21993 var create_mplib = function(token, config, name) {
21994 var instance;
21995 var target = name === PRIMARY_INSTANCE_NAME ? mixpanel_master : mixpanel_master[name];
21996 if (target && init_type === INIT_MODULE) instance = target;
21997 else {
21998 if (target && !_$1.isArray(target)) {
21999 console$1.error("You have already initialized " + name);
22000 return;
22001 }
22002 instance = new MixpanelLib();
22003 }
22004 instance._cached_groups = {};
22005 instance._init(token, config, name);
22006 instance["people"] = new MixpanelPeople();
22007 instance["people"]._init(instance);
22008 if (!instance.get_config("skip_first_touch_marketing")) {
22009 var utm_params = _$1.info.campaignParams(null);
22010 var initial_utm_params = {};
22011 var has_utm = false;
22012 _$1.each(utm_params, function(utm_value, utm_key) {
22013 initial_utm_params["initial_" + utm_key] = utm_value;
22014 if (utm_value) has_utm = true;
22015 });
22016 if (has_utm) instance["people"].set_once(initial_utm_params);
22017 }
22018 Config.DEBUG = Config.DEBUG || instance.get_config("debug");
22019 if (!_$1.isUndefined(target) && _$1.isArray(target)) {
22020 instance._execute_array.call(instance["people"], target["people"]);
22021 instance._execute_array(target);
22022 }
22023 return instance;
22024 };
22025 /**
22026 * This function initializes a new instance of the Mixpanel tracking object.
22027 * All new instances are added to the main mixpanel object as sub properties (such as
22028 * mixpanel.library_name) and also returned by this function. To define a
22029 * second instance on the page, you would call:
22030 *
22031 * mixpanel.init('new token', { your: 'config' }, 'library_name');
22032 *
22033 * and use it like so:
22034 *
22035 * mixpanel.library_name.track(...);
22036 *
22037 * @param {String} token Your Mixpanel API token
22038 * @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>.
22039 * @param {String} [name] The name for the new mixpanel instance that you want created
22040 */
22041 MixpanelLib.prototype.init = function(token, config, name) {
22042 if (_$1.isUndefined(name)) {
22043 this.report_error("You must name your new library: init(token, config, name)");
22044 return;
22045 }
22046 if (name === PRIMARY_INSTANCE_NAME) {
22047 this.report_error("You must initialize the main mixpanel object right after you include the Mixpanel js snippet");
22048 return;
22049 }
22050 var instance = create_mplib(token, config, name);
22051 mixpanel_master[name] = instance;
22052 instance._loaded();
22053 return instance;
22054 };
22055 MixpanelLib.prototype._init = function(token, config, name) {
22056 config = config || {};
22057 this["__loaded"] = true;
22058 this["config"] = {};
22059 var variable_features = {};
22060 if (!("api_payload_format" in config)) {
22061 if ((config["api_host"] || DEFAULT_CONFIG["api_host"]).match(/\.mixpanel\.com/)) variable_features["api_payload_format"] = PAYLOAD_TYPE_JSON;
22062 }
22063 this.set_config(_$1.extend({}, DEFAULT_CONFIG, variable_features, config, {
22064 "name": name,
22065 "token": token,
22066 "callback_fn": (name === PRIMARY_INSTANCE_NAME ? name : PRIMARY_INSTANCE_NAME + "." + name) + "._jsc"
22067 }));
22068 this["_jsc"] = NOOP_FUNC;
22069 this.__dom_loaded_queue = [];
22070 this.__request_queue = [];
22071 this.__disabled_events = [];
22072 this._flags = {
22073 "disable_all_events": false,
22074 "identify_called": false
22075 };
22076 this.request_batchers = {};
22077 this._batch_requests = this.get_config("batch_requests");
22078 if (this._batch_requests) if (!_$1.localStorage.is_supported(true) || !USE_XHR) {
22079 this._batch_requests = false;
22080 console$1.log("Turning off Mixpanel request-queueing; needs XHR and localStorage support");
22081 _$1.each(this.get_batcher_configs(), function(batcher_config) {
22082 console$1.log("Clearing batch queue " + batcher_config.queue_key);
22083 _$1.localStorage.remove(batcher_config.queue_key);
22084 });
22085 } else {
22086 this.init_batchers();
22087 if (sendBeacon && win.addEventListener) {
22088 var flush_on_unload = _$1.bind(function() {
22089 if (!this.request_batchers.events.stopped) this.request_batchers.events.flush({ unloading: true });
22090 }, this);
22091 win.addEventListener("pagehide", function(ev) {
22092 if (ev["persisted"]) flush_on_unload();
22093 });
22094 win.addEventListener("visibilitychange", function() {
22095 if (document$1["visibilityState"] === "hidden") flush_on_unload();
22096 });
22097 }
22098 }
22099 this["persistence"] = this["cookie"] = new MixpanelPersistence(this["config"]);
22100 this.unpersisted_superprops = {};
22101 this._gdpr_init();
22102 var uuid = _$1.UUID();
22103 if (!this.get_distinct_id()) this.register_once({
22104 "distinct_id": DEVICE_ID_PREFIX + uuid,
22105 "$device_id": uuid
22106 }, "");
22107 this.flags = new FeatureFlagManager({
22108 getFullApiRoute: _$1.bind(function() {
22109 return this.get_api_host("flags") + "/" + this.get_config("api_routes")["flags"];
22110 }, this),
22111 getConfigFunc: _$1.bind(this.get_config, this),
22112 setConfigFunc: _$1.bind(this.set_config, this),
22113 getPropertyFunc: _$1.bind(this.get_property, this),
22114 trackingFunc: _$1.bind(this.track, this)
22115 });
22116 this.flags.init();
22117 this["flags"] = this.flags;
22118 this.autocapture = new Autocapture(this);
22119 this.autocapture.init();
22120 this._init_tab_id();
22121 this._check_and_start_session_recording();
22122 };
22123 /**
22124 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
22125 * This is primarily used for session recording, where data must be isolated to the current tab.
22126 */
22127 MixpanelLib.prototype._init_tab_id = function() {
22128 if (this.get_config("disable_persistence")) console$1.log("Tab ID initialization skipped due to disable_persistence config");
22129 else if (_$1.sessionStorage.is_supported()) try {
22130 var key_suffix = this.get_config("name") + "_" + this.get_config("token");
22131 var tab_id_key = "mp_tab_id_" + key_suffix;
22132 var should_generate_new_tab_id_key = "mp_gen_new_tab_id_" + key_suffix;
22133 if (_$1.sessionStorage.get(should_generate_new_tab_id_key) || !_$1.sessionStorage.get(tab_id_key)) _$1.sessionStorage.set(tab_id_key, "$tab-" + _$1.UUID());
22134 _$1.sessionStorage.set(should_generate_new_tab_id_key, "1");
22135 this.tab_id = _$1.sessionStorage.get(tab_id_key);
22136 win.addEventListener("beforeunload", function() {
22137 _$1.sessionStorage.remove(should_generate_new_tab_id_key);
22138 });
22139 } catch (err) {
22140 this.report_error("Error initializing tab id", err);
22141 }
22142 else this.report_error("Session storage is not supported, cannot keep track of unique tab ID.");
22143 };
22144 MixpanelLib.prototype.get_tab_id = function() {
22145 return this.tab_id || null;
22146 };
22147 MixpanelLib.prototype._should_load_recorder = function() {
22148 if (this.get_config("disable_persistence")) {
22149 console$1.log("Load recorder check skipped due to disable_persistence config");
22150 return Promise.resolve(false);
22151 }
22152 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
22153 var tab_id = this.get_tab_id();
22154 return recording_registry_idb.init().then(function() {
22155 return recording_registry_idb.getAll();
22156 }).then(function(recordings) {
22157 for (var i = 0; i < recordings.length; i++) if (isRecordingExpired(recordings[i]) || recordings[i]["tabId"] === tab_id) return true;
22158 return false;
22159 }).catch(_$1.bind(function(err) {
22160 this.report_error("Error checking recording registry", err);
22161 }, this));
22162 };
22163 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
22164 if (!win["MutationObserver"]) {
22165 console$1.critical("Browser does not support MutationObserver; skipping session recording");
22166 return;
22167 }
22168 var loadRecorder = _$1.bind(function(startNewIfInactive) {
22169 var handleLoadedRecorder = _$1.bind(function() {
22170 this._recorder = this._recorder || new win["__mp_recorder"](this);
22171 this._recorder["resumeRecording"](startNewIfInactive);
22172 }, this);
22173 if (_$1.isUndefined(win["__mp_recorder"])) load_extra_bundle(this.get_config("recorder_src"), handleLoadedRecorder);
22174 else handleLoadedRecorder();
22175 }, this);
22176 /**
22177 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
22178 * 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.
22179 */
22180 var is_sampled = this.get_config("record_sessions_percent") > 0 && Math.random() * 100 <= this.get_config("record_sessions_percent");
22181 if (force_start || is_sampled) loadRecorder(true);
22182 else this._should_load_recorder().then(function(shouldLoad) {
22183 if (shouldLoad) loadRecorder(false);
22184 });
22185 });
22186 MixpanelLib.prototype.start_session_recording = function() {
22187 this._check_and_start_session_recording(true);
22188 };
22189 MixpanelLib.prototype.stop_session_recording = function() {
22190 if (this._recorder) return this._recorder["stopRecording"]();
22191 return Promise.resolve();
22192 };
22193 MixpanelLib.prototype.pause_session_recording = function() {
22194 if (this._recorder) return this._recorder["pauseRecording"]();
22195 return Promise.resolve();
22196 };
22197 MixpanelLib.prototype.resume_session_recording = function() {
22198 if (this._recorder) return this._recorder["resumeRecording"]();
22199 return Promise.resolve();
22200 };
22201 MixpanelLib.prototype.is_recording_heatmap_data = function() {
22202 return this._get_session_replay_id() && this.get_config("record_heatmap_data");
22203 };
22204 MixpanelLib.prototype.get_session_recording_properties = function() {
22205 var props = {};
22206 var replay_id = this._get_session_replay_id();
22207 if (replay_id) props["$mp_replay_id"] = replay_id;
22208 return props;
22209 };
22210 MixpanelLib.prototype.get_session_replay_url = function() {
22211 var replay_url = null;
22212 var replay_id = this._get_session_replay_id();
22213 if (replay_id) replay_url = "https://mixpanel.com/projects/replay-redirect?" + _$1.HTTPBuildQuery({
22214 "replay_id": replay_id,
22215 "distinct_id": this.get_distinct_id(),
22216 "token": this.get_config("token")
22217 });
22218 return replay_url;
22219 };
22220 MixpanelLib.prototype._get_session_replay_id = function() {
22221 var replay_id = null;
22222 if (this._recorder) replay_id = this._recorder["replayId"];
22223 return replay_id || null;
22224 };
22225 MixpanelLib.prototype.__get_recorder = function() {
22226 return this._recorder;
22227 };
22228 MixpanelLib.prototype._loaded = function() {
22229 this.get_config("loaded")(this);
22230 this._set_default_superprops();
22231 this["people"].set_once(this["persistence"].get_referrer_info());
22232 if (this.get_config("store_google") && this.get_config("stop_utm_persistence")) {
22233 var utm_params = _$1.info.campaignParams(null);
22234 _$1.each(utm_params, function(_utm_value, utm_key) {
22235 this.unregister(utm_key);
22236 }.bind(this));
22237 }
22238 };
22239 MixpanelLib.prototype._set_default_superprops = function() {
22240 this["persistence"].update_search_keyword(document$1.referrer);
22241 if (this.get_config("store_google") && !this.get_config("stop_utm_persistence")) this.register(_$1.info.campaignParams());
22242 if (this.get_config("save_referrer")) this["persistence"].update_referrer_info(document$1.referrer);
22243 };
22244 MixpanelLib.prototype._dom_loaded = function() {
22245 _$1.each(this.__dom_loaded_queue, function(item) {
22246 this._track_dom.apply(this, item);
22247 }, this);
22248 if (!this.has_opted_out_tracking()) _$1.each(this.__request_queue, function(item) {
22249 this._send_request.apply(this, item);
22250 }, this);
22251 delete this.__dom_loaded_queue;
22252 delete this.__request_queue;
22253 };
22254 MixpanelLib.prototype._track_dom = function(DomClass, args) {
22255 if (this.get_config("img")) {
22256 this.report_error("You can't use DOM tracking functions with img = true.");
22257 return false;
22258 }
22259 if (!DOM_LOADED) {
22260 this.__dom_loaded_queue.push([DomClass, args]);
22261 return false;
22262 }
22263 var dt = new DomClass().init(this);
22264 return dt.track.apply(dt, args);
22265 };
22266 /**
22267 * _prepare_callback() should be called by callers of _send_request for use
22268 * as the callback argument.
22269 *
22270 * If there is no callback, this returns null.
22271 * If we are going to make XHR/XDR requests, this returns a function.
22272 * If we are going to use script tags, this returns a string to use as the
22273 * callback GET param.
22274 */
22275 MixpanelLib.prototype._prepare_callback = function(callback, data) {
22276 if (_$1.isUndefined(callback)) return null;
22277 if (USE_XHR) {
22278 var callback_function = function(response) {
22279 callback(response, data);
22280 };
22281 return callback_function;
22282 } else {
22283 var jsc = this["_jsc"];
22284 var randomized_cb = "" + Math.floor(Math.random() * 1e8);
22285 var callback_string = this.get_config("callback_fn") + "[" + randomized_cb + "]";
22286 jsc[randomized_cb] = function(response) {
22287 delete jsc[randomized_cb];
22288 callback(response, data);
22289 };
22290 return callback_string;
22291 }
22292 };
22293 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
22294 var succeeded = true;
22295 if (ENQUEUE_REQUESTS) {
22296 this.__request_queue.push(arguments);
22297 return succeeded;
22298 }
22299 var DEFAULT_OPTIONS = {
22300 method: this.get_config("api_method"),
22301 transport: this.get_config("api_transport"),
22302 verbose: this.get_config("verbose")
22303 };
22304 var body_data = null;
22305 if (!callback && (_$1.isFunction(options) || typeof options === "string")) {
22306 callback = options;
22307 options = null;
22308 }
22309 options = _$1.extend(DEFAULT_OPTIONS, options || {});
22310 if (!USE_XHR) options.method = "GET";
22311 var use_post = options.method === "POST";
22312 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === "sendbeacon";
22313 var verbose_mode = options.verbose;
22314 if (data["verbose"]) verbose_mode = true;
22315 if (this.get_config("test")) data["test"] = 1;
22316 if (verbose_mode) data["verbose"] = 1;
22317 if (this.get_config("img")) data["img"] = 1;
22318 if (!USE_XHR) {
22319 if (callback) data["callback"] = callback;
22320 else if (verbose_mode || this.get_config("test")) data["callback"] = "(function(){})";
22321 }
22322 data["ip"] = this.get_config("ip") ? 1 : 0;
22323 data["_"] = (/* @__PURE__ */ new Date()).getTime().toString();
22324 if (use_post) {
22325 body_data = "data=" + encodeURIComponent(data["data"]);
22326 delete data["data"];
22327 }
22328 _$1.extend(data, this.get_config("api_extra_query_params"));
22329 url += "?" + _$1.HTTPBuildQuery(data);
22330 var lib = this;
22331 if ("img" in data) {
22332 var img = document$1.createElement("img");
22333 img.src = url;
22334 document$1.body.appendChild(img);
22335 } else if (use_sendBeacon) {
22336 try {
22337 succeeded = sendBeacon(url, body_data);
22338 } catch (e) {
22339 lib.report_error(e);
22340 succeeded = false;
22341 }
22342 try {
22343 if (callback) callback(succeeded ? 1 : 0);
22344 } catch (e) {
22345 lib.report_error(e);
22346 }
22347 } else if (USE_XHR) try {
22348 var req = new XMLHttpRequest();
22349 req.open(options.method, url, true);
22350 var headers = this.get_config("xhr_headers");
22351 if (use_post) headers["Content-Type"] = "application/x-www-form-urlencoded";
22352 _$1.each(headers, function(headerValue, headerName) {
22353 req.setRequestHeader(headerName, headerValue);
22354 });
22355 if (options.timeout_ms && typeof req.timeout !== "undefined") {
22356 req.timeout = options.timeout_ms;
22357 var start_time = (/* @__PURE__ */ new Date()).getTime();
22358 }
22359 req.withCredentials = true;
22360 req.onreadystatechange = function() {
22361 if (req.readyState === 4) if (req.status === 200) {
22362 if (callback) if (verbose_mode) {
22363 var response;
22364 try {
22365 response = _$1.JSONDecode(req.responseText);
22366 } catch (e) {
22367 lib.report_error(e);
22368 if (options.ignore_json_errors) response = req.responseText;
22369 else return;
22370 }
22371 callback(response);
22372 } else callback(Number(req.responseText));
22373 } else {
22374 var error;
22375 if (req.timeout && !req.status && (/* @__PURE__ */ new Date()).getTime() - start_time >= req.timeout) error = "timeout";
22376 else error = "Bad HTTP status: " + req.status + " " + req.statusText;
22377 lib.report_error(error);
22378 if (callback) if (verbose_mode) {
22379 var response_headers = req["responseHeaders"] || {};
22380 callback({
22381 status: 0,
22382 httpStatusCode: req["status"],
22383 error,
22384 retryAfter: response_headers["Retry-After"]
22385 });
22386 } else callback(0);
22387 }
22388 };
22389 req.send(body_data);
22390 } catch (e) {
22391 lib.report_error(e);
22392 succeeded = false;
22393 }
22394 else {
22395 var script = document$1.createElement("script");
22396 script.type = "text/javascript";
22397 script.async = true;
22398 script.defer = true;
22399 script.src = url;
22400 var s = document$1.getElementsByTagName("script")[0];
22401 s.parentNode.insertBefore(script, s);
22402 }
22403 return succeeded;
22404 };
22405 /**
22406 * _execute_array() deals with processing any mixpanel function
22407 * calls that were called before the Mixpanel library were loaded
22408 * (and are thus stored in an array so they can be called later)
22409 *
22410 * Note: we fire off all the mixpanel function calls && user defined
22411 * functions BEFORE we fire off mixpanel tracking calls. This is so
22412 * identify/register/set_config calls can properly modify early
22413 * tracking calls.
22414 *
22415 * @param {Array} array
22416 */
22417 MixpanelLib.prototype._execute_array = function(array) {
22418 var fn_name;
22419 var alias_calls = [];
22420 var other_calls = [];
22421 var tracking_calls = [];
22422 _$1.each(array, function(item) {
22423 if (item) {
22424 fn_name = item[0];
22425 if (_$1.isArray(fn_name)) tracking_calls.push(item);
22426 else if (typeof item === "function") item.call(this);
22427 else if (_$1.isArray(item) && fn_name === "alias") alias_calls.push(item);
22428 else if (_$1.isArray(item) && fn_name.indexOf("track") !== -1 && typeof this[fn_name] === "function") tracking_calls.push(item);
22429 else other_calls.push(item);
22430 }
22431 }, this);
22432 var execute = function(calls, context) {
22433 _$1.each(calls, function(item) {
22434 if (_$1.isArray(item[0])) {
22435 var caller = context;
22436 _$1.each(item, function(call) {
22437 caller = caller[call[0]].apply(caller, call.slice(1));
22438 });
22439 } else this[item[0]].apply(this, item.slice(1));
22440 }, context);
22441 };
22442 execute(alias_calls, this);
22443 execute(other_calls, this);
22444 execute(tracking_calls, this);
22445 };
22446 MixpanelLib.prototype.are_batchers_initialized = function() {
22447 return !!this.request_batchers.events;
22448 };
22449 MixpanelLib.prototype.get_batcher_configs = function() {
22450 var queue_prefix = "__mpq_" + this.get_config("token");
22451 this._batcher_configs = this._batcher_configs || {
22452 events: {
22453 type: "events",
22454 api_name: "track",
22455 queue_key: queue_prefix + "_ev"
22456 },
22457 people: {
22458 type: "people",
22459 api_name: "engage",
22460 queue_key: queue_prefix + "_pp"
22461 },
22462 groups: {
22463 type: "groups",
22464 api_name: "groups",
22465 queue_key: queue_prefix + "_gr"
22466 }
22467 };
22468 return this._batcher_configs;
22469 };
22470 MixpanelLib.prototype.init_batchers = function() {
22471 if (!this.are_batchers_initialized()) {
22472 var batcher_for = _$1.bind(function(attrs) {
22473 return new RequestBatcher(attrs.queue_key, {
22474 libConfig: this["config"],
22475 errorReporter: this.get_config("error_reporter"),
22476 sendRequestFunc: _$1.bind(function(data, options, cb) {
22477 var api_routes = this.get_config("api_routes");
22478 this._send_request(this.get_api_host(attrs.api_name) + "/" + api_routes[attrs.api_name], this._encode_data_for_request(data), options, this._prepare_callback(cb, data));
22479 }, this),
22480 beforeSendHook: _$1.bind(function(item) {
22481 return this._run_hook("before_send_" + attrs.type, item);
22482 }, this),
22483 stopAllBatchingFunc: _$1.bind(this.stop_batch_senders, this),
22484 usePersistence: true
22485 });
22486 }, this);
22487 var batcher_configs = this.get_batcher_configs();
22488 this.request_batchers = {
22489 events: batcher_for(batcher_configs.events),
22490 people: batcher_for(batcher_configs.people),
22491 groups: batcher_for(batcher_configs.groups)
22492 };
22493 }
22494 if (this.get_config("batch_autostart")) this.start_batch_senders();
22495 };
22496 MixpanelLib.prototype.start_batch_senders = function() {
22497 this._batchers_were_started = true;
22498 if (this.are_batchers_initialized()) {
22499 this._batch_requests = true;
22500 _$1.each(this.request_batchers, function(batcher) {
22501 batcher.start();
22502 });
22503 }
22504 };
22505 MixpanelLib.prototype.stop_batch_senders = function() {
22506 this._batch_requests = false;
22507 _$1.each(this.request_batchers, function(batcher) {
22508 batcher.stop();
22509 batcher.clear();
22510 });
22511 };
22512 /**
22513 * push() keeps the standard async-array-push
22514 * behavior around after the lib is loaded.
22515 * This is only useful for external integrations that
22516 * do not wish to rely on our convenience methods
22517 * (created in the snippet).
22518 *
22519 * ### Usage:
22520 * mixpanel.push(['register', { a: 'b' }]);
22521 *
22522 * @param {Array} item A [function_name, args...] array to be executed
22523 */
22524 MixpanelLib.prototype.push = function(item) {
22525 this._execute_array([item]);
22526 };
22527 /**
22528 * Disable events on the Mixpanel object. If passed no arguments,
22529 * this function disables tracking of any event. If passed an
22530 * array of event names, those events will be disabled, but other
22531 * events will continue to be tracked.
22532 *
22533 * Note: this function does not stop other mixpanel functions from
22534 * firing, such as register() or people.set().
22535 *
22536 * @param {Array} [events] An array of event names to disable
22537 */
22538 MixpanelLib.prototype.disable = function(events) {
22539 if (typeof events === "undefined") this._flags.disable_all_events = true;
22540 else this.__disabled_events = this.__disabled_events.concat(events);
22541 };
22542 MixpanelLib.prototype._encode_data_for_request = function(data) {
22543 var encoded_data = JSONStringify(data);
22544 if (this.get_config("api_payload_format") === PAYLOAD_TYPE_BASE64) encoded_data = _$1.base64Encode(encoded_data);
22545 return { "data": encoded_data };
22546 };
22547 MixpanelLib.prototype._track_or_batch = function(options, callback) {
22548 var truncated_data = _$1.truncate(options.data, 255);
22549 var endpoint = options.endpoint;
22550 var batcher = options.batcher;
22551 var should_send_immediately = options.should_send_immediately;
22552 var send_request_options = options.send_request_options || {};
22553 callback = callback || NOOP_FUNC;
22554 var request_enqueued_or_initiated = true;
22555 var send_request_immediately = _$1.bind(function() {
22556 if (!send_request_options.skip_hooks) truncated_data = this._run_hook("before_send_" + options.type, truncated_data);
22557 if (truncated_data) {
22558 console$1.log("MIXPANEL REQUEST:");
22559 console$1.log(truncated_data);
22560 return this._send_request(endpoint, this._encode_data_for_request(truncated_data), send_request_options, this._prepare_callback(callback, truncated_data));
22561 } else return null;
22562 }, this);
22563 if (this._batch_requests && !should_send_immediately) batcher.enqueue(truncated_data).then(function(succeeded) {
22564 if (succeeded) callback(1, truncated_data);
22565 else send_request_immediately();
22566 });
22567 else request_enqueued_or_initiated = send_request_immediately();
22568 return request_enqueued_or_initiated && truncated_data;
22569 };
22570 /**
22571 * Track an event. This is the most important and
22572 * frequently used Mixpanel function.
22573 *
22574 * ### Usage:
22575 *
22576 * // track an event named 'Registered'
22577 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
22578 *
22579 * // track an event using navigator.sendBeacon
22580 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
22581 *
22582 * To track link clicks or form submissions, see track_links() or track_forms().
22583 *
22584 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
22585 * @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.
22586 * @param {Object} [options] Optional configuration for this track request.
22587 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
22588 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
22589 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
22590 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
22591 * with the tracking payload sent to the API server is returned; otherwise false.
22592 */
22593 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
22594 if (!callback && typeof options === "function") {
22595 callback = options;
22596 options = null;
22597 }
22598 options = options || {};
22599 var transport = options["transport"];
22600 if (transport) options.transport = transport;
22601 var should_send_immediately = options["send_immediately"];
22602 if (typeof callback !== "function") callback = NOOP_FUNC;
22603 if (_$1.isUndefined(event_name)) {
22604 this.report_error("No event name provided to mixpanel.track");
22605 return;
22606 }
22607 if (this._event_is_disabled(event_name)) {
22608 callback(0);
22609 return;
22610 }
22611 properties = _$1.extend({}, properties);
22612 properties["token"] = this.get_config("token");
22613 var start_timestamp = this["persistence"].remove_event_timer(event_name);
22614 if (!_$1.isUndefined(start_timestamp)) {
22615 var duration_in_ms = (/* @__PURE__ */ new Date()).getTime() - start_timestamp;
22616 properties["$duration"] = parseFloat((duration_in_ms / 1e3).toFixed(3));
22617 }
22618 this._set_default_superprops();
22619 var marketing_properties = this.get_config("track_marketing") ? _$1.info.marketingParams() : {};
22620 properties = _$1.extend({}, _$1.info.properties({ "mp_loader": this.get_config("mp_loader") }), marketing_properties, this["persistence"].properties(), this.unpersisted_superprops, this.get_session_recording_properties(), properties);
22621 var property_blacklist = this.get_config("property_blacklist");
22622 if (_$1.isArray(property_blacklist)) _$1.each(property_blacklist, function(blacklisted_prop) {
22623 delete properties[blacklisted_prop];
22624 });
22625 else this.report_error("Invalid value for property_blacklist config: " + property_blacklist);
22626 var data = {
22627 "event": event_name,
22628 "properties": properties
22629 };
22630 return this._track_or_batch({
22631 type: "events",
22632 data,
22633 endpoint: this.get_api_host("events") + "/" + this.get_config("api_routes")["track"],
22634 batcher: this.request_batchers.events,
22635 should_send_immediately,
22636 send_request_options: options
22637 }, callback);
22638 });
22639 /**
22640 * Register the current user into one/many groups.
22641 *
22642 * ### Usage:
22643 *
22644 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
22645 * mixpanel.set_group('company', 'mixpanel')
22646 * mixpanel.set_group('company', 128746312)
22647 *
22648 * @param {String} group_key Group key
22649 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
22650 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22651 *
22652 */
22653 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
22654 if (!_$1.isArray(group_ids)) group_ids = [group_ids];
22655 var prop = {};
22656 prop[group_key] = group_ids;
22657 this.register(prop);
22658 return this["people"].set(group_key, group_ids, callback);
22659 });
22660 /**
22661 * Add a new group for this user.
22662 *
22663 * ### Usage:
22664 *
22665 * mixpanel.add_group('company', 'mixpanel')
22666 *
22667 * @param {String} group_key Group key
22668 * @param {*} group_id A valid Mixpanel property type
22669 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22670 */
22671 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
22672 var old_values = this.get_property(group_key);
22673 var prop = {};
22674 if (old_values === void 0) {
22675 prop[group_key] = [group_id];
22676 this.register(prop);
22677 } else if (old_values.indexOf(group_id) === -1) {
22678 old_values.push(group_id);
22679 prop[group_key] = old_values;
22680 this.register(prop);
22681 }
22682 return this["people"].union(group_key, group_id, callback);
22683 });
22684 /**
22685 * Remove a group from this user.
22686 *
22687 * ### Usage:
22688 *
22689 * mixpanel.remove_group('company', 'mixpanel')
22690 *
22691 * @param {String} group_key Group key
22692 * @param {*} group_id A valid Mixpanel property type
22693 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22694 */
22695 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
22696 var old_value = this.get_property(group_key);
22697 if (old_value !== void 0) {
22698 var idx = old_value.indexOf(group_id);
22699 if (idx > -1) {
22700 old_value.splice(idx, 1);
22701 this.register({ group_key: old_value });
22702 }
22703 if (old_value.length === 0) this.unregister(group_key);
22704 }
22705 return this["people"].remove(group_key, group_id, callback);
22706 });
22707 /**
22708 * Track an event with specific groups.
22709 *
22710 * ### Usage:
22711 *
22712 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
22713 *
22714 * @param {String} event_name The name of the event (see `mixpanel.track()`)
22715 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
22716 * @param {Object=} groups An object mapping group name keys to one or more values
22717 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
22718 */
22719 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
22720 var tracking_props = _$1.extend({}, properties || {});
22721 _$1.each(groups, function(v, k) {
22722 if (v !== null && v !== void 0) tracking_props[k] = v;
22723 });
22724 return this.track(event_name, tracking_props, callback);
22725 });
22726 MixpanelLib.prototype._create_map_key = function(group_key, group_id) {
22727 return group_key + "_" + JSON.stringify(group_id);
22728 };
22729 MixpanelLib.prototype._remove_group_from_cache = function(group_key, group_id) {
22730 delete this._cached_groups[this._create_map_key(group_key, group_id)];
22731 };
22732 /**
22733 * Look up reference to a Mixpanel group
22734 *
22735 * ### Usage:
22736 *
22737 * mixpanel.get_group(group_key, group_id)
22738 *
22739 * @param {String} group_key Group key
22740 * @param {Object} group_id A valid Mixpanel property type
22741 * @returns {Object} A MixpanelGroup identifier
22742 */
22743 MixpanelLib.prototype.get_group = function(group_key, group_id) {
22744 var map_key = this._create_map_key(group_key, group_id);
22745 var group = this._cached_groups[map_key];
22746 if (group === void 0 || group._group_key !== group_key || group._group_id !== group_id) {
22747 group = new MixpanelGroup();
22748 group._init(this, group_key, group_id);
22749 this._cached_groups[map_key] = group;
22750 }
22751 return group;
22752 };
22753 /**
22754 * Track a default Mixpanel page view event, which includes extra default event properties to
22755 * improve page view data.
22756 *
22757 * ### Usage:
22758 *
22759 * // track a default $mp_web_page_view event
22760 * mixpanel.track_pageview();
22761 *
22762 * // track a page view event with additional event properties
22763 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
22764 *
22765 * // example approach to track page views on different page types as event properties
22766 * mixpanel.track_pageview({'page': 'pricing'});
22767 * mixpanel.track_pageview({'page': 'homepage'});
22768 *
22769 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
22770 * // individual pages on the same site or product. Use cases for custom event_name may be page
22771 * // views on different products or internal applications that are considered completely separate
22772 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
22773 *
22774 * ### Notes:
22775 *
22776 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
22777 * may be turned on for tracking page loads automatically.
22778 *
22779 * // track only page loads
22780 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
22781 *
22782 * // track when the URL changes in any manner
22783 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
22784 *
22785 * // track when the URL changes, ignoring any changes in the hash part
22786 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
22787 *
22788 * // track when the path changes, ignoring any query parameter or hash changes
22789 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
22790 *
22791 * @param {Object} [properties] An optional set of additional properties to send with the page view event
22792 * @param {Object} [options] Page view tracking options
22793 * @param {String} [options.event_name] - Alternate name for the tracking event
22794 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
22795 * with the tracking payload sent to the API server is returned; otherwise false.
22796 */
22797 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
22798 if (typeof properties !== "object") properties = {};
22799 options = options || {};
22800 var event_name = options["event_name"] || "$mp_web_page_view";
22801 var default_page_properties = _$1.extend(_$1.info.mpPageViewProperties(), _$1.info.campaignParams(), _$1.info.clickParams());
22802 var event_properties = _$1.extend({}, default_page_properties, properties);
22803 return this.track(event_name, event_properties);
22804 });
22805 /**
22806 * Track clicks on a set of document elements. Selector must be a
22807 * valid query. Elements must exist on the page at the time track_links is called.
22808 *
22809 * ### Usage:
22810 *
22811 * // track click for link id #nav
22812 * mixpanel.track_links('#nav', 'Clicked Nav Link');
22813 *
22814 * ### Notes:
22815 *
22816 * This function will wait up to 300 ms for the Mixpanel
22817 * servers to respond. If they have not responded by that time
22818 * it will head to the link without ensuring that your event
22819 * has been tracked. To configure this timeout please see the
22820 * set_config() documentation below.
22821 *
22822 * If you pass a function in as the properties argument, the
22823 * function will receive the DOMElement that triggered the
22824 * event as an argument. You are expected to return an object
22825 * from the function; any properties defined on this object
22826 * will be sent to mixpanel as event properties.
22827 *
22828 * @type {Function}
22829 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
22830 * @param {String} event_name The name of the event to track
22831 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
22832 */
22833 MixpanelLib.prototype.track_links = function() {
22834 return this._track_dom.call(this, LinkTracker, arguments);
22835 };
22836 /**
22837 * Track form submissions. Selector must be a valid query.
22838 *
22839 * ### Usage:
22840 *
22841 * // track submission for form id 'register'
22842 * mixpanel.track_forms('#register', 'Created Account');
22843 *
22844 * ### Notes:
22845 *
22846 * This function will wait up to 300 ms for the mixpanel
22847 * servers to respond, if they have not responded by that time
22848 * it will head to the link without ensuring that your event
22849 * has been tracked. To configure this timeout please see the
22850 * set_config() documentation below.
22851 *
22852 * If you pass a function in as the properties argument, the
22853 * function will receive the DOMElement that triggered the
22854 * event as an argument. You are expected to return an object
22855 * from the function; any properties defined on this object
22856 * will be sent to mixpanel as event properties.
22857 *
22858 * @type {Function}
22859 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
22860 * @param {String} event_name The name of the event to track
22861 * @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
22862 */
22863 MixpanelLib.prototype.track_forms = function() {
22864 return this._track_dom.call(this, FormTracker, arguments);
22865 };
22866 /**
22867 * Time an event by including the time between this call and a
22868 * later 'track' call for the same event in the properties sent
22869 * with the event.
22870 *
22871 * ### Usage:
22872 *
22873 * // time an event named 'Registered'
22874 * mixpanel.time_event('Registered');
22875 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
22876 *
22877 * When called for a particular event name, the next track call for that event
22878 * name will include the elapsed time between the 'time_event' and 'track'
22879 * calls. This value is stored as seconds in the '$duration' property.
22880 *
22881 * @param {String} event_name The name of the event.
22882 */
22883 MixpanelLib.prototype.time_event = function(event_name) {
22884 if (_$1.isUndefined(event_name)) {
22885 this.report_error("No event name provided to mixpanel.time_event");
22886 return;
22887 }
22888 if (this._event_is_disabled(event_name)) return;
22889 this["persistence"].set_event_timer(event_name, (/* @__PURE__ */ new Date()).getTime());
22890 };
22891 var REGISTER_DEFAULTS = { "persistent": true };
22892 /**
22893 * Helper to parse options param for register methods, maintaining
22894 * legacy support for plain "days" param instead of options object
22895 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
22896 * @returns {Object} options object
22897 */
22898 var options_for_register = function(days_or_options) {
22899 var options;
22900 if (_$1.isObject(days_or_options)) options = days_or_options;
22901 else if (!_$1.isUndefined(days_or_options)) options = { "days": days_or_options };
22902 else options = {};
22903 return _$1.extend({}, REGISTER_DEFAULTS, options);
22904 };
22905 /**
22906 * Register a set of super properties, which are included with all
22907 * events. This will overwrite previous super property values.
22908 *
22909 * ### Usage:
22910 *
22911 * // register 'Gender' as a super property
22912 * mixpanel.register({'Gender': 'Female'});
22913 *
22914 * // register several super properties when a user signs up
22915 * mixpanel.register({
22916 * 'Email': 'jdoe@example.com',
22917 * 'Account Type': 'Free'
22918 * });
22919 *
22920 * // register only for the current pageload
22921 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
22922 *
22923 * @param {Object} properties An associative array of properties to store about the user
22924 * @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)
22925 * @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)
22926 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
22927 */
22928 MixpanelLib.prototype.register = function(props, days_or_options) {
22929 var options = options_for_register(days_or_options);
22930 if (options["persistent"]) this["persistence"].register(props, options["days"]);
22931 else _$1.extend(this.unpersisted_superprops, props);
22932 };
22933 /**
22934 * Register a set of super properties only once. This will not
22935 * overwrite previous super property values, unlike register().
22936 *
22937 * ### Usage:
22938 *
22939 * // register a super property for the first time only
22940 * mixpanel.register_once({
22941 * 'First Login Date': new Date().toISOString()
22942 * });
22943 *
22944 * // register once, only for the current pageload
22945 * mixpanel.register_once({
22946 * 'First interaction time': new Date().toISOString()
22947 * }, 'None', {persistent: false});
22948 *
22949 * ### Notes:
22950 *
22951 * If default_value is specified, current super properties
22952 * with that value will be overwritten.
22953 *
22954 * @param {Object} properties An associative array of properties to store about the user
22955 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
22956 * @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)
22957 * @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)
22958 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
22959 */
22960 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
22961 var options = options_for_register(days_or_options);
22962 if (options["persistent"]) this["persistence"].register_once(props, default_value, options["days"]);
22963 else {
22964 if (typeof default_value === "undefined") default_value = "None";
22965 _$1.each(props, function(val, prop) {
22966 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) this.unpersisted_superprops[prop] = val;
22967 }, this);
22968 }
22969 };
22970 /**
22971 * Delete a super property stored with the current user.
22972 *
22973 * @param {String} property The name of the super property to remove
22974 * @param {Object} [options]
22975 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
22976 */
22977 MixpanelLib.prototype.unregister = function(property, options) {
22978 options = options_for_register(options);
22979 if (options["persistent"]) this["persistence"].unregister(property);
22980 else delete this.unpersisted_superprops[property];
22981 };
22982 MixpanelLib.prototype._register_single = function(prop, value) {
22983 var props = {};
22984 props[prop] = value;
22985 this.register(props);
22986 };
22987 /**
22988 * Identify a user with a unique ID to track user activity across
22989 * devices, tie a user to their events, and create a user profile.
22990 * If you never call this method, unique visitors are tracked using
22991 * a UUID generated the first time they visit the site.
22992 *
22993 * Call identify when you know the identity of the current user,
22994 * typically after login or signup. We recommend against using
22995 * identify for anonymous visitors to your site.
22996 *
22997 * ### Notes:
22998 * If your project has
22999 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
23000 * enabled, the identify method will connect pre- and
23001 * post-authentication events when appropriate.
23002 *
23003 * If your project does not have ID Merge enabled, identify will
23004 * change the user's local distinct_id to the unique ID you pass.
23005 * Events tracked prior to authentication will not be connected
23006 * to the same user identity. If ID Merge is disabled, alias can
23007 * be used to connect pre- and post-registration events.
23008 *
23009 * @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.
23010 */
23011 MixpanelLib.prototype.identify = function(new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback) {
23012 var previous_distinct_id = this.get_distinct_id();
23013 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
23014 if (typeof new_distinct_id === "string" && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
23015 this.report_error("distinct_id cannot have $device: prefix");
23016 return -1;
23017 }
23018 this.register({ "$user_id": new_distinct_id });
23019 }
23020 if (!this.get_property("$device_id")) {
23021 var device_id = previous_distinct_id;
23022 this.register_once({
23023 "$had_persisted_distinct_id": true,
23024 "$device_id": device_id
23025 }, "");
23026 }
23027 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
23028 this.unregister(ALIAS_ID_KEY);
23029 this.register({ "distinct_id": new_distinct_id });
23030 }
23031 this._flags.identify_called = true;
23032 this["people"]._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
23033 if (new_distinct_id !== previous_distinct_id) this.track("$identify", {
23034 "distinct_id": new_distinct_id,
23035 "$anon_distinct_id": previous_distinct_id
23036 }, { skip_hooks: true });
23037 if (new_distinct_id !== previous_distinct_id) this.flags.fetchFlags();
23038 };
23039 /**
23040 * Clears super properties and generates a new random distinct_id for this instance.
23041 * Useful for clearing data when a user logs out.
23042 */
23043 MixpanelLib.prototype.reset = function() {
23044 this.stop_session_recording();
23045 this["persistence"].clear();
23046 this._flags.identify_called = false;
23047 var uuid = _$1.UUID();
23048 this.register_once({
23049 "distinct_id": DEVICE_ID_PREFIX + uuid,
23050 "$device_id": uuid
23051 }, "");
23052 this._check_and_start_session_recording();
23053 };
23054 /**
23055 * Returns the current distinct id of the user. This is either the id automatically
23056 * generated by the library or the id that has been passed by a call to identify().
23057 *
23058 * ### Notes:
23059 *
23060 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
23061 * init() has a loaded function available to handle this automatically. For example:
23062 *
23063 * // set distinct_id after the mixpanel library has loaded
23064 * mixpanel.init('YOUR PROJECT TOKEN', {
23065 * loaded: function(mixpanel) {
23066 * distinct_id = mixpanel.get_distinct_id();
23067 * }
23068 * });
23069 */
23070 MixpanelLib.prototype.get_distinct_id = function() {
23071 return this.get_property("distinct_id");
23072 };
23073 /**
23074 * The alias method creates an alias which Mixpanel will use to
23075 * remap one id to another. Multiple aliases can point to the
23076 * same identifier.
23077 *
23078 * The following is a valid use of alias:
23079 *
23080 * mixpanel.alias('new_id', 'existing_id');
23081 * // You can add multiple id aliases to the existing ID
23082 * mixpanel.alias('newer_id', 'existing_id');
23083 *
23084 * Aliases can also be chained - the following is a valid example:
23085 *
23086 * mixpanel.alias('new_id', 'existing_id');
23087 * // chain newer_id - new_id - existing_id
23088 * mixpanel.alias('newer_id', 'new_id');
23089 *
23090 * Aliases cannot point to multiple identifiers - the following
23091 * example will not work:
23092 *
23093 * mixpanel.alias('new_id', 'existing_id');
23094 * // this is invalid as 'new_id' already points to 'existing_id'
23095 * mixpanel.alias('new_id', 'newer_id');
23096 *
23097 * ### Notes:
23098 *
23099 * If your project does not have
23100 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
23101 * enabled, the best practice is to call alias once when a unique
23102 * ID is first created for a user (e.g., when a user first registers
23103 * for an account). Do not use alias multiple times for a single
23104 * user without ID Merge enabled.
23105 *
23106 * @param {String} alias A unique identifier that you want to use for this user in the future.
23107 * @param {String} [original] The current identifier being used for this user.
23108 */
23109 MixpanelLib.prototype.alias = function(alias, original) {
23110 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
23111 this.report_error("Attempting to create alias for existing People user - aborting.");
23112 return -2;
23113 }
23114 var _this = this;
23115 if (_$1.isUndefined(original)) original = this.get_distinct_id();
23116 if (alias !== original) {
23117 this._register_single(ALIAS_ID_KEY, alias);
23118 return this.track("$create_alias", {
23119 "alias": alias,
23120 "distinct_id": original
23121 }, { skip_hooks: true }, function() {
23122 _this.identify(alias);
23123 });
23124 } else {
23125 this.report_error("alias matches current distinct_id - skipping api call.");
23126 this.identify(alias);
23127 return -1;
23128 }
23129 };
23130 /**
23131 * Provide a string to recognize the user by. The string passed to
23132 * this method will appear in the Mixpanel Streams product rather
23133 * than an automatically generated name. Name tags do not have to
23134 * be unique.
23135 *
23136 * This value will only be included in Streams data.
23137 *
23138 * @param {String} name_tag A human readable name for the user
23139 * @deprecated
23140 */
23141 MixpanelLib.prototype.name_tag = function(name_tag) {
23142 this._register_single("mp_name_tag", name_tag);
23143 };
23144 /**
23145 * Update the configuration of a mixpanel library instance.
23146 *
23147 * The default config is:
23148 *
23149 * {
23150 * // host for requests (customizable for e.g. a local proxy)
23151 * api_host: 'https://api-js.mixpanel.com',
23152 *
23153 * // endpoints for different types of requests
23154 * api_routes: {
23155 * track: 'track/',
23156 * engage: 'engage/',
23157 * groups: 'groups/',
23158 * }
23159 *
23160 * // HTTP method for tracking requests
23161 * api_method: 'POST'
23162 *
23163 * // transport for sending requests ('XHR' or 'sendBeacon')
23164 * // NB: sendBeacon should only be used for scenarios such as
23165 * // page unload where a "best-effort" attempt to send is
23166 * // acceptable; the sendBeacon API does not support callbacks
23167 * // or any way to know the result of the request. Mixpanel
23168 * // tracking via sendBeacon will not support any event-
23169 * // batching or retry mechanisms.
23170 * api_transport: 'XHR'
23171 *
23172 * // request-batching/queueing/retry
23173 * batch_requests: true,
23174 *
23175 * // maximum number of events/updates to send in a single
23176 * // network request
23177 * batch_size: 50,
23178 *
23179 * // milliseconds to wait between sending batch requests
23180 * batch_flush_interval_ms: 5000,
23181 *
23182 * // milliseconds to wait for network responses to batch requests
23183 * // before they are considered timed-out and retried
23184 * batch_request_timeout_ms: 90000,
23185 *
23186 * // override value for cookie domain, only useful for ensuring
23187 * // correct cross-subdomain cookies on unusual domains like
23188 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
23189 * // set cookies on a different domain than the current origin
23190 * cookie_domain: ''
23191 *
23192 * // super properties cookie expiration (in days)
23193 * cookie_expiration: 365
23194 *
23195 * // if true, cookie will be set with SameSite=None; Secure
23196 * // this is only useful in special situations, like embedded
23197 * // 3rd-party iframes that set up a Mixpanel instance
23198 * cross_site_cookie: false
23199 *
23200 * // super properties span subdomains
23201 * cross_subdomain_cookie: true
23202 *
23203 * // debug mode
23204 * debug: false
23205 *
23206 * // if this is true, the mixpanel cookie or localStorage entry
23207 * // will be deleted, and no user persistence will take place
23208 * disable_persistence: false
23209 *
23210 * // if this is true, Mixpanel will automatically determine
23211 * // City, Region and Country data using the IP address of
23212 * //the client
23213 * ip: true
23214 *
23215 * // opt users out of tracking by this Mixpanel instance by default
23216 * opt_out_tracking_by_default: false
23217 *
23218 * // opt users out of browser data storage by this Mixpanel instance by default
23219 * opt_out_persistence_by_default: false
23220 *
23221 * // persistence mechanism used by opt-in/opt-out methods - cookie
23222 * // or localStorage - falls back to cookie if localStorage is unavailable
23223 * opt_out_tracking_persistence_type: 'localStorage'
23224 *
23225 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
23226 * opt_out_tracking_cookie_prefix: null
23227 *
23228 * // type of persistent store for super properties (cookie/
23229 * // localStorage) if set to 'localStorage', any existing
23230 * // mixpanel cookie value with the same persistence_name
23231 * // will be transferred to localStorage and deleted
23232 * persistence: 'cookie'
23233 *
23234 * // name for super properties persistent store
23235 * persistence_name: ''
23236 *
23237 * // names of properties/superproperties which should never
23238 * // be sent with track() calls
23239 * property_blacklist: []
23240 *
23241 * // if this is true, mixpanel cookies will be marked as
23242 * // secure, meaning they will only be transmitted over https
23243 * secure_cookie: false
23244 *
23245 * // disables enriching user profiles with first touch marketing data
23246 * skip_first_touch_marketing: false
23247 *
23248 * // the amount of time track_links will
23249 * // wait for Mixpanel's servers to respond
23250 * track_links_timeout: 300
23251 *
23252 * // adds any UTM parameters and click IDs present on the page to any events fired
23253 * track_marketing: true
23254 *
23255 * // enables automatic page view tracking using default page view events through
23256 * // the track_pageview() method
23257 * track_pageview: false
23258 *
23259 * // if you set upgrade to be true, the library will check for
23260 * // a cookie from our old js library and import super
23261 * // properties from it, then the old cookie is deleted
23262 * // The upgrade config option only works in the initialization,
23263 * // so make sure you set it when you create the library.
23264 * upgrade: false
23265 *
23266 * // extra HTTP request headers to set for each API request, in
23267 * // the format {'Header-Name': value}
23268 * xhr_headers: {}
23269 *
23270 * // whether to ignore or respect the web browser's Do Not Track setting
23271 * ignore_dnt: false
23272 * }
23273 *
23274 *
23275 * @param {Object} config A dictionary of new configuration values to update
23276 */
23277 MixpanelLib.prototype.set_config = function(config) {
23278 if (_$1.isObject(config)) {
23279 _$1.extend(this["config"], config);
23280 if (config["batch_size"]) _$1.each(this.request_batchers, function(batcher) {
23281 batcher.resetBatchSize();
23282 });
23283 if (!this.get_config("persistence_name")) this["config"]["persistence_name"] = this["config"]["cookie_name"];
23284 if (!this.get_config("disable_persistence")) this["config"]["disable_persistence"] = this["config"]["disable_cookie"];
23285 if (this["persistence"]) this["persistence"].update_config(this["config"]);
23286 Config.DEBUG = Config.DEBUG || this.get_config("debug");
23287 if (("autocapture" in config || "record_heatmap_data" in config) && this.autocapture) this.autocapture.init();
23288 }
23289 };
23290 /**
23291 * returns the current config object for the library.
23292 */
23293 MixpanelLib.prototype.get_config = function(prop_name) {
23294 return this["config"][prop_name];
23295 };
23296 /**
23297 * Fetch a hook function from config, with safe default, and run it
23298 * against the given arguments
23299 * @param {string} hook_name which hook to retrieve
23300 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
23301 */
23302 MixpanelLib.prototype._run_hook = function(hook_name) {
23303 var ret = (this["config"]["hooks"][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
23304 if (typeof ret === "undefined") {
23305 this.report_error(hook_name + " hook did not return a value");
23306 ret = null;
23307 }
23308 return ret;
23309 };
23310 /**
23311 * Returns the value of the super property named property_name. If no such
23312 * property is set, get_property() will return the undefined value.
23313 *
23314 * ### Notes:
23315 *
23316 * get_property() can only be called after the Mixpanel library has finished loading.
23317 * init() has a loaded function available to handle this automatically. For example:
23318 *
23319 * // grab value for 'user_id' after the mixpanel library has loaded
23320 * mixpanel.init('YOUR PROJECT TOKEN', {
23321 * loaded: function(mixpanel) {
23322 * user_id = mixpanel.get_property('user_id');
23323 * }
23324 * });
23325 *
23326 * @param {String} property_name The name of the super property you want to retrieve
23327 */
23328 MixpanelLib.prototype.get_property = function(property_name) {
23329 return this["persistence"].load_prop([property_name]);
23330 };
23331 /**
23332 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
23333 *
23334 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
23335 * @returns {String} The API host to use for this endpoint
23336 */
23337 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
23338 return this.get_config("api_hosts")[endpoint_type] || this.get_config("api_host");
23339 };
23340 MixpanelLib.prototype.toString = function() {
23341 var name = this.get_config("name");
23342 if (name !== PRIMARY_INSTANCE_NAME) name = PRIMARY_INSTANCE_NAME + "." + name;
23343 return name;
23344 };
23345 MixpanelLib.prototype._event_is_disabled = function(event_name) {
23346 return _$1.isBlockedUA(userAgent) || this._flags.disable_all_events || _$1.include(this.__disabled_events, event_name);
23347 };
23348 MixpanelLib.prototype._gdpr_init = function() {
23349 if (this.get_config("opt_out_tracking_persistence_type") === "localStorage" && _$1.localStorage.is_supported()) {
23350 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({ "persistence_type": "cookie" })) this.opt_in_tracking({ "enable_persistence": false });
23351 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({ "persistence_type": "cookie" })) this.opt_out_tracking({ "clear_persistence": false });
23352 this.clear_opt_in_out_tracking({
23353 "persistence_type": "cookie",
23354 "enable_persistence": false
23355 });
23356 }
23357 if (this.has_opted_out_tracking()) this._gdpr_update_persistence({ "clear_persistence": true });
23358 else if (!this.has_opted_in_tracking() && (this.get_config("opt_out_tracking_by_default") || _$1.cookie.get("mp_optout"))) {
23359 _$1.cookie.remove("mp_optout");
23360 this.opt_out_tracking({ "clear_persistence": this.get_config("opt_out_persistence_by_default") });
23361 }
23362 };
23363 /**
23364 * Enable or disable persistence based on options
23365 * only enable/disable if persistence is not already in this state
23366 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
23367 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
23368 */
23369 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
23370 var disabled;
23371 if (options && options["clear_persistence"]) disabled = true;
23372 else if (options && options["enable_persistence"]) disabled = false;
23373 else return;
23374 if (!this.get_config("disable_persistence") && this["persistence"].disabled !== disabled) this["persistence"].set_disabled(disabled);
23375 if (disabled) {
23376 this.stop_batch_senders();
23377 this.stop_session_recording();
23378 } else if (this._batchers_were_started) this.start_batch_senders();
23379 };
23380 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
23381 options = _$1.extend({
23382 "track": _$1.bind(this.track, this),
23383 "persistence_type": this.get_config("opt_out_tracking_persistence_type"),
23384 "cookie_prefix": this.get_config("opt_out_tracking_cookie_prefix"),
23385 "cookie_expiration": this.get_config("cookie_expiration"),
23386 "cross_site_cookie": this.get_config("cross_site_cookie"),
23387 "cross_subdomain_cookie": this.get_config("cross_subdomain_cookie"),
23388 "cookie_domain": this.get_config("cookie_domain"),
23389 "secure_cookie": this.get_config("secure_cookie"),
23390 "ignore_dnt": this.get_config("ignore_dnt")
23391 }, options);
23392 if (!_$1.localStorage.is_supported()) options["persistence_type"] = "cookie";
23393 return func(this.get_config("token"), {
23394 track: options["track"],
23395 trackEventName: options["track_event_name"],
23396 trackProperties: options["track_properties"],
23397 persistenceType: options["persistence_type"],
23398 persistencePrefix: options["cookie_prefix"],
23399 cookieDomain: options["cookie_domain"],
23400 cookieExpiration: options["cookie_expiration"],
23401 crossSiteCookie: options["cross_site_cookie"],
23402 crossSubdomainCookie: options["cross_subdomain_cookie"],
23403 secureCookie: options["secure_cookie"],
23404 ignoreDnt: options["ignore_dnt"]
23405 });
23406 };
23407 /**
23408 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
23409 *
23410 * ### Usage:
23411 *
23412 * // opt user in
23413 * mixpanel.opt_in_tracking();
23414 *
23415 * // opt user in with specific event name, properties, cookie configuration
23416 * mixpanel.opt_in_tracking({
23417 * track_event_name: 'User opted in',
23418 * track_event_properties: {
23419 * 'Email': 'jdoe@example.com'
23420 * },
23421 * cookie_expiration: 30,
23422 * secure_cookie: true
23423 * });
23424 *
23425 * @param {Object} [options] A dictionary of config options to override
23426 * @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)
23427 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
23428 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
23429 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
23430 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23431 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23432 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23433 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23434 * @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)
23435 * @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)
23436 * @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)
23437 */
23438 MixpanelLib.prototype.opt_in_tracking = function(options) {
23439 options = _$1.extend({ "enable_persistence": true }, options);
23440 this._gdpr_call_func(optIn, options);
23441 this._gdpr_update_persistence(options);
23442 };
23443 /**
23444 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
23445 *
23446 * ### Usage:
23447 *
23448 * // opt user out
23449 * mixpanel.opt_out_tracking();
23450 *
23451 * // opt user out with different cookie configuration from Mixpanel instance
23452 * mixpanel.opt_out_tracking({
23453 * cookie_expiration: 30,
23454 * secure_cookie: true
23455 * });
23456 *
23457 * @param {Object} [options] A dictionary of config options to override
23458 * @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
23459 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
23460 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23461 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23462 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23463 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23464 * @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)
23465 * @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)
23466 * @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)
23467 */
23468 MixpanelLib.prototype.opt_out_tracking = function(options) {
23469 options = _$1.extend({
23470 "clear_persistence": true,
23471 "delete_user": true
23472 }, options);
23473 if (options["delete_user"] && this["people"] && this["people"]._identify_called()) {
23474 this["people"].delete_user();
23475 this["people"].clear_charges();
23476 }
23477 this._gdpr_call_func(optOut, options);
23478 this._gdpr_update_persistence(options);
23479 };
23480 /**
23481 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
23482 *
23483 * ### Usage:
23484 *
23485 * var has_opted_in = mixpanel.has_opted_in_tracking();
23486 * // use has_opted_in value
23487 *
23488 * @param {Object} [options] A dictionary of config options to override
23489 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23490 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23491 * @returns {boolean} current opt-in status
23492 */
23493 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
23494 return this._gdpr_call_func(hasOptedIn, options);
23495 };
23496 /**
23497 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
23498 *
23499 * ### Usage:
23500 *
23501 * var has_opted_out = mixpanel.has_opted_out_tracking();
23502 * // use has_opted_out value
23503 *
23504 * @param {Object} [options] A dictionary of config options to override
23505 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23506 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23507 * @returns {boolean} current opt-out status
23508 */
23509 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
23510 return this._gdpr_call_func(hasOptedOut, options);
23511 };
23512 /**
23513 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
23514 *
23515 * ### Usage:
23516 *
23517 * // clear user's opt-in/out status
23518 * mixpanel.clear_opt_in_out_tracking();
23519 *
23520 * // clear user's opt-in/out status with specific cookie configuration - should match
23521 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
23522 * mixpanel.clear_opt_in_out_tracking({
23523 * cookie_expiration: 30,
23524 * secure_cookie: true
23525 * });
23526 *
23527 * @param {Object} [options] A dictionary of config options to override
23528 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
23529 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
23530 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
23531 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
23532 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
23533 * @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)
23534 * @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)
23535 * @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)
23536 */
23537 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
23538 options = _$1.extend({ "enable_persistence": true }, options);
23539 this._gdpr_call_func(clearOptInOut, options);
23540 this._gdpr_update_persistence(options);
23541 };
23542 MixpanelLib.prototype.report_error = function(msg, err) {
23543 console$1.error.apply(console$1.error, arguments);
23544 try {
23545 if (!err && !(msg instanceof Error)) msg = new Error(msg);
23546 this.get_config("error_reporter")(msg, err);
23547 } catch (err) {
23548 console$1.error(err);
23549 }
23550 };
23551 MixpanelLib.prototype["init"] = MixpanelLib.prototype.init;
23552 MixpanelLib.prototype["reset"] = MixpanelLib.prototype.reset;
23553 MixpanelLib.prototype["disable"] = MixpanelLib.prototype.disable;
23554 MixpanelLib.prototype["time_event"] = MixpanelLib.prototype.time_event;
23555 MixpanelLib.prototype["track"] = MixpanelLib.prototype.track;
23556 MixpanelLib.prototype["track_links"] = MixpanelLib.prototype.track_links;
23557 MixpanelLib.prototype["track_forms"] = MixpanelLib.prototype.track_forms;
23558 MixpanelLib.prototype["track_pageview"] = MixpanelLib.prototype.track_pageview;
23559 MixpanelLib.prototype["register"] = MixpanelLib.prototype.register;
23560 MixpanelLib.prototype["register_once"] = MixpanelLib.prototype.register_once;
23561 MixpanelLib.prototype["unregister"] = MixpanelLib.prototype.unregister;
23562 MixpanelLib.prototype["identify"] = MixpanelLib.prototype.identify;
23563 MixpanelLib.prototype["alias"] = MixpanelLib.prototype.alias;
23564 MixpanelLib.prototype["name_tag"] = MixpanelLib.prototype.name_tag;
23565 MixpanelLib.prototype["set_config"] = MixpanelLib.prototype.set_config;
23566 MixpanelLib.prototype["get_config"] = MixpanelLib.prototype.get_config;
23567 MixpanelLib.prototype["get_api_host"] = MixpanelLib.prototype.get_api_host;
23568 MixpanelLib.prototype["get_property"] = MixpanelLib.prototype.get_property;
23569 MixpanelLib.prototype["get_distinct_id"] = MixpanelLib.prototype.get_distinct_id;
23570 MixpanelLib.prototype["toString"] = MixpanelLib.prototype.toString;
23571 MixpanelLib.prototype["opt_out_tracking"] = MixpanelLib.prototype.opt_out_tracking;
23572 MixpanelLib.prototype["opt_in_tracking"] = MixpanelLib.prototype.opt_in_tracking;
23573 MixpanelLib.prototype["has_opted_out_tracking"] = MixpanelLib.prototype.has_opted_out_tracking;
23574 MixpanelLib.prototype["has_opted_in_tracking"] = MixpanelLib.prototype.has_opted_in_tracking;
23575 MixpanelLib.prototype["clear_opt_in_out_tracking"] = MixpanelLib.prototype.clear_opt_in_out_tracking;
23576 MixpanelLib.prototype["get_group"] = MixpanelLib.prototype.get_group;
23577 MixpanelLib.prototype["set_group"] = MixpanelLib.prototype.set_group;
23578 MixpanelLib.prototype["add_group"] = MixpanelLib.prototype.add_group;
23579 MixpanelLib.prototype["remove_group"] = MixpanelLib.prototype.remove_group;
23580 MixpanelLib.prototype["track_with_groups"] = MixpanelLib.prototype.track_with_groups;
23581 MixpanelLib.prototype["start_batch_senders"] = MixpanelLib.prototype.start_batch_senders;
23582 MixpanelLib.prototype["stop_batch_senders"] = MixpanelLib.prototype.stop_batch_senders;
23583 MixpanelLib.prototype["start_session_recording"] = MixpanelLib.prototype.start_session_recording;
23584 MixpanelLib.prototype["stop_session_recording"] = MixpanelLib.prototype.stop_session_recording;
23585 MixpanelLib.prototype["pause_session_recording"] = MixpanelLib.prototype.pause_session_recording;
23586 MixpanelLib.prototype["resume_session_recording"] = MixpanelLib.prototype.resume_session_recording;
23587 MixpanelLib.prototype["get_session_recording_properties"] = MixpanelLib.prototype.get_session_recording_properties;
23588 MixpanelLib.prototype["get_session_replay_url"] = MixpanelLib.prototype.get_session_replay_url;
23589 MixpanelLib.prototype["get_tab_id"] = MixpanelLib.prototype.get_tab_id;
23590 MixpanelLib.prototype["DEFAULT_API_ROUTES"] = DEFAULT_API_ROUTES;
23591 MixpanelLib.prototype["__get_recorder"] = MixpanelLib.prototype.__get_recorder;
23592 MixpanelPersistence.prototype["properties"] = MixpanelPersistence.prototype.properties;
23593 MixpanelPersistence.prototype["update_search_keyword"] = MixpanelPersistence.prototype.update_search_keyword;
23594 MixpanelPersistence.prototype["update_referrer_info"] = MixpanelPersistence.prototype.update_referrer_info;
23595 MixpanelPersistence.prototype["get_cross_subdomain"] = MixpanelPersistence.prototype.get_cross_subdomain;
23596 MixpanelPersistence.prototype["clear"] = MixpanelPersistence.prototype.clear;
23597 var instances = {};
23598 var extend_mp = function() {
23599 _$1.each(instances, function(instance, name) {
23600 if (name !== PRIMARY_INSTANCE_NAME) mixpanel_master[name] = instance;
23601 });
23602 mixpanel_master["_"] = _$1;
23603 };
23604 var override_mp_init_func = function() {
23605 mixpanel_master["init"] = function(token, config, name) {
23606 if (name) {
23607 if (!mixpanel_master[name]) {
23608 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
23609 mixpanel_master[name]._loaded();
23610 }
23611 return mixpanel_master[name];
23612 } else {
23613 var instance = mixpanel_master;
23614 if (instances[PRIMARY_INSTANCE_NAME]) instance = instances[PRIMARY_INSTANCE_NAME];
23615 else if (token) {
23616 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
23617 instance._loaded();
23618 instances[PRIMARY_INSTANCE_NAME] = instance;
23619 }
23620 mixpanel_master = instance;
23621 if (init_type === INIT_SNIPPET) win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
23622 extend_mp();
23623 }
23624 };
23625 };
23626 var add_dom_loaded_handler = function() {
23627 function dom_loaded_handler() {
23628 if (dom_loaded_handler.done) return;
23629 dom_loaded_handler.done = true;
23630 DOM_LOADED = true;
23631 ENQUEUE_REQUESTS = false;
23632 _$1.each(instances, function(inst) {
23633 inst._dom_loaded();
23634 });
23635 }
23636 function do_scroll_check() {
23637 try {
23638 document$1.documentElement.doScroll("left");
23639 } catch (e) {
23640 setTimeout(do_scroll_check, 1);
23641 return;
23642 }
23643 dom_loaded_handler();
23644 }
23645 if (document$1.addEventListener) if (document$1.readyState === "complete") dom_loaded_handler();
23646 else document$1.addEventListener("DOMContentLoaded", dom_loaded_handler, false);
23647 else if (document$1.attachEvent) {
23648 document$1.attachEvent("onreadystatechange", dom_loaded_handler);
23649 var toplevel = false;
23650 try {
23651 toplevel = win.frameElement === null;
23652 } catch (e) {}
23653 if (document$1.documentElement.doScroll && toplevel) do_scroll_check();
23654 }
23655 _$1.register_event(win, "load", dom_loaded_handler, true);
23656 };
23657 function init_as_module(bundle_loader) {
23658 load_extra_bundle = bundle_loader;
23659 init_type = INIT_MODULE;
23660 mixpanel_master = new MixpanelLib();
23661 override_mp_init_func();
23662 mixpanel_master["init"]();
23663 add_dom_loaded_handler();
23664 return mixpanel_master;
23665 }
23666 function loadNoop(_src, onload) {
23667 onload();
23668 }
23669 var mixpanel = init_as_module(loadNoop);
23670
23671 //#endregion
23672 //#region assets/dev/js/utils/tiers.js
23673 var TIERS_PRIORITY = Object.freeze([
23674 "free",
23675 "essential",
23676 "essential-oct2023",
23677 "advanced",
23678 "expert",
23679 "agency"
23680 ]);
23681 /**
23682 * @type {Readonly<{
23683 * free: string;
23684 * essential: string;
23685 * 'essential-oct2023': string;
23686 * advanced: string;
23687 * expert: string;
23688 * agency: string;
23689 * }>}
23690 */
23691 var TIERS = Object.freeze(TIERS_PRIORITY.reduce(function(acc, tier) {
23692 acc[tier] = tier;
23693 return acc;
23694 }, {}));
23695
23696 //#endregion
23697 //#region core/common/modules/events-manager/assets/js/module.js
23698 init_defineProperty();
23699 function ownKeys(e, r) {
23700 var t = Object.keys(e);
23701 if (Object.getOwnPropertySymbols) {
23702 var o = Object.getOwnPropertySymbols(e);
23703 r && (o = o.filter(function(r) {
23704 return Object.getOwnPropertyDescriptor(e, r).enumerable;
23705 })), t.push.apply(t, o);
23706 }
23707 return t;
23708 }
23709 function _objectSpread(e) {
23710 for (var r = 1; r < arguments.length; r++) {
23711 var t = null != arguments[r] ? arguments[r] : {};
23712 r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
23713 _defineProperty(e, r, t[r]);
23714 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
23715 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
23716 });
23717 }
23718 return e;
23719 }
23720 function _callSuper$1(t, o, e) {
23721 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
23722 }
23723 __name(_callSuper$1, "_callSuper");
23724 function _isNativeReflectConstruct$1() {
23725 try {
23726 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
23727 } catch (t) {}
23728 return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() {
23729 return !!t;
23730 })();
23731 }
23732 __name(_isNativeReflectConstruct$1, "_isNativeReflectConstruct");
23733 /** @type {typeof mixpanel | null} */
23734 var mixpanelInstance = null;
23735 var _default = /*#__PURE__*/ function(_elementorModules$Mod) {
23736 function _default() {
23737 var _this;
23738 _classCallCheck(this, _default);
23739 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
23740 _this = _callSuper$1(this, _default, [].concat(args));
23741 _defineProperty(_this, "trackingEnabled", false);
23742 _defineProperty(_this, "availableExperiments", []);
23743 return _this;
23744 }
23745 _inherits$1(_default, _elementorModules$Mod);
23746 return _createClass(_default, [
23747 {
23748 key: "onInit",
23749 value: function onInit() {
23750 var _this2 = this;
23751 this.config = eventsConfig;
23752 if (!this.canSendEvents()) return;
23753 this.initializeMixpanel(function() {
23754 return _this2.enableTracking();
23755 });
23756 }
23757 },
23758 {
23759 key: "initializeMixpanel",
23760 value: function initializeMixpanel(onLoaded) {
23761 if (mixpanelInstance && mixpanelInstance.isInitialized) onLoaded(mixpanelInstance);
23762 else {
23763 var _elementorCommon$conf;
23764 var _elementorCommon$conf2;
23765 var _elementorCommon$conf3;
23766 var _elementorCommon$conf4;
23767 var _elementorCommon$conf5;
23768 var _elementorCommon$conf6;
23769 var _elementorCommon$conf7;
23770 mixpanelInstance = mixpanel.init((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.token, {
23771 persistence: "localStorage",
23772 persistence_name: "elementor-builder-editor",
23773 debug: (_elementorCommon$conf2 = (_elementorCommon$conf3 = elementorCommon.config.editor_events) === null || _elementorCommon$conf3 === void 0 ? void 0 : _elementorCommon$conf3.debug) !== null && _elementorCommon$conf2 !== void 0 ? _elementorCommon$conf2 : false,
23774 autocapture: false,
23775 flags: true,
23776 api_host: (_elementorCommon$conf4 = elementorCommon.config.editor_events) === null || _elementorCommon$conf4 === void 0 ? void 0 : _elementorCommon$conf4.proxy_api_host,
23777 lib_base_path: (_elementorCommon$conf5 = elementorCommon.config.editor_events) === null || _elementorCommon$conf5 === void 0 ? void 0 : _elementorCommon$conf5.proxy_lib_base_path,
23778 loaded: onLoaded,
23779 record_sessions_percent: (_elementorCommon$conf6 = (_elementorCommon$conf7 = elementorCommon.config.editor_events) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.session_recording_percent) !== null && _elementorCommon$conf6 !== void 0 ? _elementorCommon$conf6 : 0,
23780 record_idle_timeout_ms: 60 * 1e3,
23781 record_min_ms: 5 * 1e3,
23782 record_mask_text_selector: "",
23783 remote_settings_mode: "strict"
23784 }, "elementor-builder-editor");
23785 }
23786 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
23787 }
23788 },
23789 {
23790 key: "enableTracking",
23791 value: function enableTracking() {
23792 var _elementorCommon$conf8;
23793 if (!this.isMixpanelReady()) return;
23794 var userId = (_elementorCommon$conf8 = elementorCommon.config.editor_events) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.user_id;
23795 mixpanelInstance.register({ appType: "Editor" });
23796 if (userId) {
23797 var _elementorCommon$conf9;
23798 mixpanelInstance.identify(userId);
23799 mixpanelInstance.people.set_once({
23800 $user_id: userId,
23801 $last_login: (/* @__PURE__ */ new Date()).toISOString(),
23802 $plan_type: ((_elementorCommon$conf9 = elementorCommon.config.library_connect) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.plan_type) || TIERS.free
23803 });
23804 }
23805 this.trackingEnabled = true;
23806 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
23807 }
23808 },
23809 {
23810 key: "dispatchEvent",
23811 value: function dispatchEvent(name, data) {
23812 var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
23813 if (!this.canSendEvents()) return;
23814 try {
23815 var _elementorCommon$conf0;
23816 var _elementorCommon$conf1;
23817 var _elementorCommon$conf10;
23818 var _elementorCommon$conf11;
23819 var _elementorCommon$conf12;
23820 var _elementorCommon$conf13;
23821 var _elementorCommon$conf14;
23822 var _elementorCommon$conf15;
23823 var _elementorCommon$conf16;
23824 if (!this.trackingEnabled) this.enableTracking();
23825 var eventData = _objectSpread({
23826 user_id: ((_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.user_id) || null,
23827 user_roles: ((_elementorCommon$conf1 = elementorCommon.config.library_connect) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.user_roles) || [],
23828 subscription_id: ((_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.subscription_id) || null,
23829 user_tier: ((_elementorCommon$conf11 = elementorCommon.config.library_connect) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.current_access_tier) || null,
23830 url: (_elementorCommon$conf12 = elementorCommon.config.editor_events) === null || _elementorCommon$conf12 === void 0 ? void 0 : _elementorCommon$conf12.site_url,
23831 wp_version: (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.wp_version,
23832 client_id: (_elementorCommon$conf14 = elementorCommon.config.editor_events) === null || _elementorCommon$conf14 === void 0 ? void 0 : _elementorCommon$conf14.site_key,
23833 app_version: (_elementorCommon$conf15 = elementorCommon.config.editor_events) === null || _elementorCommon$conf15 === void 0 ? void 0 : _elementorCommon$conf15.elementor_version,
23834 site_language: (_elementorCommon$conf16 = elementorCommon.config.editor_events) === null || _elementorCommon$conf16 === void 0 ? void 0 : _elementorCommon$conf16.site_language,
23835 experiments: this.availableExperiments
23836 }, data);
23837 mixpanelInstance.track(name, eventData, options);
23838 } catch (error) {
23839 var _elementorCommon$conf17;
23840 if ((_elementorCommon$conf17 = elementorCommon.config.editor_events) !== null && _elementorCommon$conf17 !== void 0 && _elementorCommon$conf17.debug) console.error("Events Manager dispatch failed:", error);
23841 }
23842 }
23843 },
23844 {
23845 key: "featureFlagIsActive",
23846 value: function() {
23847 var _featureFlagIsActive = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee(flagName) {
23848 var _mixpanelInstance;
23849 var isEnabled;
23850 return import_regenerator.default.wrap(function(_context) {
23851 while (1) switch (_context.prev = _context.next) {
23852 case 0:
23853 if (!("function" !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
23854 _context.next = 1;
23855 break;
23856 }
23857 return _context.abrupt("return", false);
23858 case 1:
23859 _context.next = 2;
23860 return mixpanelInstance.flags.is_enabled(flagName, false);
23861 case 2:
23862 isEnabled = _context.sent;
23863 return _context.abrupt("return", true === isEnabled);
23864 case 3:
23865 case "end": return _context.stop();
23866 }
23867 }, _callee);
23868 }));
23869 function featureFlagIsActive(_x) {
23870 return _featureFlagIsActive.apply(this, arguments);
23871 }
23872 return featureFlagIsActive;
23873 }()
23874 },
23875 {
23876 key: "getExperimentVariant",
23877 value: function() {
23878 var _getExperimentVariant = _asyncToGenerator(/*#__PURE__*/ import_regenerator.default.mark(function _callee2(experimentName) {
23879 var defaultValue;
23880 var _elementorCommon$conf18;
23881 var _elementorCommon$conf19;
23882 var isAbTestingEnabled;
23883 var variant;
23884 var _args2 = arguments;
23885 return import_regenerator.default.wrap(function(_context2) {
23886 while (1) switch (_context2.prev = _context2.next) {
23887 case 0:
23888 defaultValue = _args2.length > 1 && _args2[1] !== void 0 ? _args2[1] : "control";
23889 _context2.prev = 1;
23890 if (this.canSendEvents()) {
23891 _context2.next = 2;
23892 break;
23893 }
23894 return _context2.abrupt("return", defaultValue);
23895 case 2:
23896 isAbTestingEnabled = (_elementorCommon$conf18 = (_elementorCommon$conf19 = elementorCommon.config.editor_events) === null || _elementorCommon$conf19 === void 0 ? void 0 : _elementorCommon$conf19.flags_enabled) !== null && _elementorCommon$conf18 !== void 0 ? _elementorCommon$conf18 : false;
23897 if (isAbTestingEnabled) {
23898 _context2.next = 3;
23899 break;
23900 }
23901 return _context2.abrupt("return", defaultValue);
23902 case 3:
23903 if (mixpanelInstance) {
23904 _context2.next = 4;
23905 break;
23906 }
23907 return _context2.abrupt("return", defaultValue);
23908 case 4:
23909 if (!this.trackingEnabled) this.enableTracking();
23910 if (mixpanelInstance.flags) {
23911 _context2.next = 5;
23912 break;
23913 }
23914 return _context2.abrupt("return", defaultValue);
23915 case 5:
23916 if (!("function" !== typeof mixpanelInstance.flags.get_variant_value)) {
23917 _context2.next = 6;
23918 break;
23919 }
23920 return _context2.abrupt("return", defaultValue);
23921 case 6:
23922 _context2.next = 7;
23923 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
23924 case 7:
23925 variant = _context2.sent;
23926 if (!(void 0 === variant || null === variant)) {
23927 _context2.next = 8;
23928 break;
23929 }
23930 return _context2.abrupt("return", defaultValue);
23931 case 8: return _context2.abrupt("return", variant);
23932 case 9:
23933 _context2.prev = 9;
23934 _context2["catch"](1);
23935 return _context2.abrupt("return", defaultValue);
23936 case 10:
23937 case "end": return _context2.stop();
23938 }
23939 }, _callee2, this, [[1, 9]]);
23940 }));
23941 function getExperimentVariant(_x2) {
23942 return _getExperimentVariant.apply(this, arguments);
23943 }
23944 return getExperimentVariant;
23945 }()
23946 },
23947 {
23948 key: "startExperiment",
23949 value: function startExperiment(experimentName, experimentVariant) {
23950 if (!this.trackingEnabled) return;
23951 mixpanelInstance.track("$experiment_started", {
23952 "Experiment name": experimentName,
23953 "Variant name": experimentVariant
23954 });
23955 }
23956 },
23957 {
23958 key: "isMixpanelReady",
23959 value: function isMixpanelReady() {
23960 if ("undefined" === typeof mixpanelInstance || !mixpanelInstance) return false;
23961 try {
23962 var distinctId = mixpanelInstance.get_distinct_id();
23963 return distinctId !== void 0 && distinctId !== null;
23964 } catch (error) {
23965 return false;
23966 }
23967 }
23968 },
23969 {
23970 key: "canSendEvents",
23971 value: function canSendEvents() {
23972 var _elementorCommon;
23973 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);
23974 }
23975 },
23976 {
23977 key: "getMixpanelInstance",
23978 value: function getMixpanelInstance() {
23979 return this.isMixpanelReady() ? mixpanelInstance : void 0;
23980 }
23981 }
23982 ]);
23983 }(elementorModules.Module);
23984
23985 //#endregion
23986 //#region assets/dev/js/utils/notifications.js
23987 var require_notifications = /* @__PURE__ */ __commonJSMin(((exports, module) => {
23988 init_defineProperty();
23989 function ownKeys(e, r) {
23990 var t = Object.keys(e);
23991 if (Object.getOwnPropertySymbols) {
23992 var o = Object.getOwnPropertySymbols(e);
23993 r && (o = o.filter(function(r) {
23994 return Object.getOwnPropertyDescriptor(e, r).enumerable;
23995 })), t.push.apply(t, o);
23996 }
23997 return t;
23998 }
23999 function _objectSpread(e) {
24000 for (var r = 1; r < arguments.length; r++) {
24001 var t = null != arguments[r] ? arguments[r] : {};
24002 r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
24003 _defineProperty(e, r, t[r]);
24004 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
24005 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
24006 });
24007 }
24008 return e;
24009 }
24010 module.exports = elementorModules.Module.extend({
24011 initToast: function initToast() {
24012 var toast = elementorCommon.dialogsManager.createWidget("buttons", {
24013 id: "elementor-toast",
24014 position: {
24015 my: "center bottom",
24016 at: "center bottom-10",
24017 of: "#elementor-panel-inner",
24018 autoRefresh: true
24019 },
24020 hide: {
24021 onClick: true,
24022 auto: true,
24023 autoDelay: 1e4
24024 },
24025 effects: {
24026 show: function show() {
24027 var $widget = toast.getElements("widget");
24028 $widget.show();
24029 toast.refreshPosition();
24030 var top = parseInt($widget.css("top"), 10);
24031 $widget.hide().css("top", top + 100);
24032 $widget.animate({
24033 opacity: "show",
24034 height: "show",
24035 paddingBottom: "show",
24036 paddingTop: "show",
24037 top
24038 }, {
24039 easing: "linear",
24040 duration: 300
24041 });
24042 },
24043 hide: function hide() {
24044 var $widget = toast.getElements("widget");
24045 var top = parseInt($widget.css("top"), 10);
24046 $widget.animate({
24047 opacity: "hide",
24048 height: "hide",
24049 paddingBottom: "hide",
24050 paddingTop: "hide",
24051 top: top + 100
24052 }, {
24053 easing: "linear",
24054 duration: 300
24055 });
24056 }
24057 },
24058 button: { tag: "button" }
24059 });
24060 toast.getElements("widget").attr({
24061 role: "status",
24062 "aria-live": "polite",
24063 "aria-atomic": "true"
24064 });
24065 this.getToast = function() {
24066 return toast;
24067 };
24068 },
24069 showToast: function showToast(options) {
24070 var toast = this.getToast();
24071 toast.setMessage(options.message);
24072 toast.getElements("buttonsWrapper").empty();
24073 toast.focusedButton = null;
24074 toast.buttons = [];
24075 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
24076 if (!isPositionValid) this.positionToWindow();
24077 if (options !== null && options !== void 0 && options.position && isPositionValid) toast.setSettings("position", options.position);
24078 if (options.buttons) options.buttons.forEach(function(button) {
24079 toast.addButton(button);
24080 });
24081 if (options.classes) toast.getElements("widget").addClass(options.classes);
24082 if (options.sticky) toast.setSettings({ hide: {
24083 auto: false,
24084 onClick: false
24085 } });
24086 return toast.show();
24087 },
24088 isPositionValid: function isPositionValid(position) {
24089 var _position$of;
24090 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;
24091 if (!positionToCheck) return false;
24092 return !!document.querySelector(positionToCheck);
24093 },
24094 positionToWindow: function positionToWindow() {
24095 var toast = this.getToast();
24096 var position = _objectSpread(_objectSpread({}, toast.getSettings("position")), {}, {
24097 my: "right top",
24098 at: "right-10 top+42",
24099 of: ""
24100 });
24101 toast.setSettings("position", position);
24102 toast.getElements("widget").addClass("dialog-position-window");
24103 },
24104 onInit: function onInit() {
24105 this.initToast();
24106 }
24107 });
24108 }));
24109
24110 //#endregion
24111 //#region core/common/assets/js/common.js
24112 var import_notifications = /* @__PURE__ */ __toESM(require_notifications());
24113 function _callSuper(t, o, e) {
24114 return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
24115 }
24116 function _isNativeReflectConstruct() {
24117 try {
24118 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
24119 } catch (t) {}
24120 return (_isNativeReflectConstruct = function _isNativeReflectConstruct() {
24121 return !!t;
24122 })();
24123 }
24124 function _superPropGet(t, o, e, r) {
24125 var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e);
24126 return 2 & r && "function" == typeof p ? function(t) {
24127 return p.apply(e, t);
24128 } : p;
24129 }
24130 var ElementorCommonApp = /*#__PURE__*/ function(_elementorModules$Vie) {
24131 function ElementorCommonApp() {
24132 _classCallCheck(this, ElementorCommonApp);
24133 return _callSuper(this, ElementorCommonApp, arguments);
24134 }
24135 _inherits$1(ElementorCommonApp, _elementorModules$Vie);
24136 return _createClass(ElementorCommonApp, [
24137 {
24138 key: "setMarionetteTemplateCompiler",
24139 value: function setMarionetteTemplateCompiler() {
24140 Marionette.TemplateCache.prototype.loadTemplate = function(templateId) {
24141 var $template = "#" === templateId.charAt(0) ? Backbone.$("script" + templateId) : Backbone.$(templateId);
24142 if (!$template.length) throw new Marionette.Error({
24143 name: "NoTemplateError",
24144 message: "Could not find template: \"" + templateId + "\""
24145 });
24146 return $template.html();
24147 };
24148 Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate, options) {
24149 options = {
24150 evaluate: /<#([\s\S]+?)#>/g,
24151 interpolate: /{{{([\s\S]+?)}}}/g,
24152 escape: /{{([^}]+?)}}(?!})/g
24153 };
24154 return _.template(rawTemplate, options);
24155 };
24156 }
24157 },
24158 {
24159 key: "getDefaultElements",
24160 value: function getDefaultElements() {
24161 return {
24162 $window: jQuery(window),
24163 $document: jQuery(document),
24164 $body: jQuery(document.body)
24165 };
24166 }
24167 },
24168 {
24169 key: "initComponents",
24170 value: function initComponents() {
24171 this.events = new Events();
24172 this.eventsManager = new _default();
24173 this.debug = new import_debug.default();
24174 this.helpers = new Helpers();
24175 this.storage = new _default$11();
24176 this.dialogsManager = new DialogsManager.Instance();
24177 this.notifications = new import_notifications.default();
24178 this.api = window.$e;
24179 $e.components.register(new Component());
24180 elementorCommon.elements.$window.on("elementor:init-components", function() {
24181 $e.components.register(new Component$1());
24182 });
24183 this.initModules();
24184 }
24185 },
24186 {
24187 key: "initModules",
24188 value: function initModules() {
24189 var _this = this;
24190 var activeModules = this.config.activeModules;
24191 var modules = {
24192 ajax: _default$10,
24193 finder: _default$2,
24194 connect: _default$1
24195 };
24196 activeModules.forEach(function(name) {
24197 if (modules[name]) _this[name] = new modules[name](_this.config[name]);
24198 });
24199 }
24200 },
24201 {
24202 key: "compileArrayTemplateArgs",
24203 value: function compileArrayTemplateArgs(template, templateArgs) {
24204 return template.replace(/%(?:(\d+)\$)?s/g, function(match, number) {
24205 if (!number) number = 1;
24206 number--;
24207 return void 0 !== templateArgs[number] ? templateArgs[number] : match;
24208 });
24209 }
24210 },
24211 {
24212 key: "compileObjectTemplateArgs",
24213 value: function compileObjectTemplateArgs(template, templateArgs) {
24214 return template.replace(/{{(?:([ \w]+))}}/g, function(match, name) {
24215 return templateArgs[name] ? templateArgs[name] : match;
24216 });
24217 }
24218 },
24219 {
24220 key: "compileTemplate",
24221 value: function compileTemplate(template, templateArgs) {
24222 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
24223 }
24224 },
24225 {
24226 key: "translate",
24227 value: function translate(stringKey, context, templateArgs, i18nStack) {
24228 if (context) i18nStack = this.config[context].i18n;
24229 if (!i18nStack) i18nStack = this.config.i18n;
24230 var string = i18nStack[stringKey];
24231 if (void 0 === string) string = stringKey;
24232 if (templateArgs) string = this.compileTemplate(string, templateArgs);
24233 return string;
24234 }
24235 },
24236 {
24237 key: "onInit",
24238 value: function onInit() {
24239 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
24240 this.config = elementorCommonConfig;
24241 this.setMarionetteTemplateCompiler();
24242 }
24243 }
24244 ]);
24245 }(elementorModules.ViewModule);
24246 window.elementorCommon = new ElementorCommonApp();
24247 elementorCommon.initComponents();
24248
24249 //#endregion
24250 })(elementorVendors.reduxToolkit, wp.i18n);
24251 //# sourceMappingURL=common.js.map