(() => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // node_modules/lodash.debounce/index.js var require_lodash = __commonJS({ "node_modules/lodash.debounce/index.js"(exports, module) { var FUNC_ERROR_TEXT = "Expected a function"; var NAN = 0 / 0; var symbolTag = "[object Symbol]"; var reTrim = /^\s+|\s+$/g; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsOctal = /^0o[0-7]+$/i; var freeParseInt = parseInt; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); var objectProto = Object.prototype; var objectToString = objectProto.toString; var nativeMax = Math.max; var nativeMin = Math.min; var now = function() { return root.Date.now(); }; function debounce6(func, wait, options2) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options2)) { leading = !!options2.leading; maxing = "maxWait" in options2; maxWait = maxing ? nativeMax(toNumber(options2.maxWait) || 0, wait) : maxWait; trailing = "trailing" in options2 ? !!options2.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { lastInvokeTime = time; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall; return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush() { return timerId === void 0 ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } function isObject(value) { var type = typeof value; return !!value && (type == "object" || type == "function"); } function isObjectLike(value) { return !!value && typeof value == "object"; } function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; } function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other2 = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other2) ? other2 + "" : other2; } if (typeof value != "string") { return value === 0 ? value : +value; } value = value.replace(reTrim, ""); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } module.exports = debounce6; } }); // node_modules/namespace-emitter/index.js var require_namespace_emitter = __commonJS({ "node_modules/namespace-emitter/index.js"(exports, module) { module.exports = function createNamespaceEmitter() { var emitter = {}; var _fns = emitter._fns = {}; emitter.emit = function emit(event, arg1, arg2, arg3, arg4, arg5, arg6) { var toEmit = getListeners(event); if (toEmit.length) { emitAll(event, toEmit, [arg1, arg2, arg3, arg4, arg5, arg6]); } }; emitter.on = function on(event, fn2) { if (!_fns[event]) { _fns[event] = []; } _fns[event].push(fn2); }; emitter.once = function once(event, fn2) { function one() { fn2.apply(this, arguments); emitter.off(event, one); } this.on(event, one); }; emitter.off = function off(event, fn2) { var keep = []; if (event && fn2) { var fns = this._fns[event]; var i4 = 0; var l4 = fns ? fns.length : 0; for (i4; i4 < l4; i4++) { if (fns[i4] !== fn2) { keep.push(fns[i4]); } } } keep.length ? this._fns[event] = keep : delete this._fns[event]; }; function getListeners(e4) { var out = _fns[e4] ? _fns[e4] : []; var idx = e4.indexOf(":"); var args = idx === -1 ? [e4] : [e4.substring(0, idx), e4.substring(idx + 1)]; var keys = Object.keys(_fns); var i4 = 0; var l4 = keys.length; for (i4; i4 < l4; i4++) { var key = keys[i4]; if (key === "*") { out = out.concat(_fns[key]); } if (args.length === 2 && args[0] === key) { out = out.concat(_fns[key]); break; } } return out; } function emitAll(e4, fns, args) { var i4 = 0; var l4 = fns.length; for (i4; i4 < l4; i4++) { if (!fns[i4]) break; fns[i4].event = e4; fns[i4].apply(fns[i4], args); } } return emitter; }; } }); // node_modules/lodash/isObject.js var require_isObject = __commonJS({ "node_modules/lodash/isObject.js"(exports, module) { function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } module.exports = isObject; } }); // node_modules/lodash/_freeGlobal.js var require_freeGlobal = __commonJS({ "node_modules/lodash/_freeGlobal.js"(exports, module) { var freeGlobal = typeof global == "object" && global && global.Object === Object && global; module.exports = freeGlobal; } }); // node_modules/lodash/_root.js var require_root = __commonJS({ "node_modules/lodash/_root.js"(exports, module) { var freeGlobal = require_freeGlobal(); var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); module.exports = root; } }); // node_modules/lodash/now.js var require_now = __commonJS({ "node_modules/lodash/now.js"(exports, module) { var root = require_root(); var now = function() { return root.Date.now(); }; module.exports = now; } }); // node_modules/lodash/_trimmedEndIndex.js var require_trimmedEndIndex = __commonJS({ "node_modules/lodash/_trimmedEndIndex.js"(exports, module) { var reWhitespace = /\s/; function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) { } return index; } module.exports = trimmedEndIndex; } }); // node_modules/lodash/_baseTrim.js var require_baseTrim = __commonJS({ "node_modules/lodash/_baseTrim.js"(exports, module) { var trimmedEndIndex = require_trimmedEndIndex(); var reTrimStart = /^\s+/; function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; } module.exports = baseTrim; } }); // node_modules/lodash/_Symbol.js var require_Symbol = __commonJS({ "node_modules/lodash/_Symbol.js"(exports, module) { var root = require_root(); var Symbol2 = root.Symbol; module.exports = Symbol2; } }); // node_modules/lodash/_getRawTag.js var require_getRawTag = __commonJS({ "node_modules/lodash/_getRawTag.js"(exports, module) { var Symbol2 = require_Symbol(); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; var nativeObjectToString = objectProto.toString; var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag2 = value[symToStringTag]; try { value[symToStringTag] = void 0; var unmasked = true; } catch (e4) { } var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag2; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; } }); // node_modules/lodash/_objectToString.js var require_objectToString = __commonJS({ "node_modules/lodash/_objectToString.js"(exports, module) { var objectProto = Object.prototype; var nativeObjectToString = objectProto.toString; function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; } }); // node_modules/lodash/_baseGetTag.js var require_baseGetTag = __commonJS({ "node_modules/lodash/_baseGetTag.js"(exports, module) { var Symbol2 = require_Symbol(); var getRawTag = require_getRawTag(); var objectToString = require_objectToString(); var nullTag = "[object Null]"; var undefinedTag = "[object Undefined]"; var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; function baseGetTag(value) { if (value == null) { return value === void 0 ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; } }); // node_modules/lodash/isObjectLike.js var require_isObjectLike = __commonJS({ "node_modules/lodash/isObjectLike.js"(exports, module) { function isObjectLike(value) { return value != null && typeof value == "object"; } module.exports = isObjectLike; } }); // node_modules/lodash/isSymbol.js var require_isSymbol = __commonJS({ "node_modules/lodash/isSymbol.js"(exports, module) { var baseGetTag = require_baseGetTag(); var isObjectLike = require_isObjectLike(); var symbolTag = "[object Symbol]"; function isSymbol(value) { return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; } module.exports = isSymbol; } }); // node_modules/lodash/toNumber.js var require_toNumber = __commonJS({ "node_modules/lodash/toNumber.js"(exports, module) { var baseTrim = require_baseTrim(); var isObject = require_isObject(); var isSymbol = require_isSymbol(); var NAN = 0 / 0; var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; var reIsBinary = /^0b[01]+$/i; var reIsOctal = /^0o[0-7]+$/i; var freeParseInt = parseInt; function toNumber(value) { if (typeof value == "number") { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other2 = typeof value.valueOf == "function" ? value.valueOf() : value; value = isObject(other2) ? other2 + "" : other2; } if (typeof value != "string") { return value === 0 ? value : +value; } value = baseTrim(value); var isBinary = reIsBinary.test(value); return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; } module.exports = toNumber; } }); // node_modules/lodash/debounce.js var require_debounce = __commonJS({ "node_modules/lodash/debounce.js"(exports, module) { var isObject = require_isObject(); var now = require_now(); var toNumber = require_toNumber(); var FUNC_ERROR_TEXT = "Expected a function"; var nativeMax = Math.max; var nativeMin = Math.min; function debounce6(func, wait, options2) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options2)) { leading = !!options2.leading; maxing = "maxWait" in options2; maxWait = maxing ? nativeMax(toNumber(options2.maxWait) || 0, wait) : maxWait; trailing = "trailing" in options2 ? !!options2.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { lastInvokeTime = time; timerId = setTimeout(timerExpired, wait); return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush() { return timerId === void 0 ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } module.exports = debounce6; } }); // node_modules/lodash/throttle.js var require_throttle = __commonJS({ "node_modules/lodash/throttle.js"(exports, module) { var debounce6 = require_debounce(); var isObject = require_isObject(); var FUNC_ERROR_TEXT = "Expected a function"; function throttle2(func, wait, options2) { var leading = true, trailing = true; if (typeof func != "function") { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options2)) { leading = "leading" in options2 ? !!options2.leading : leading; trailing = "trailing" in options2 ? !!options2.trailing : trailing; } return debounce6(func, wait, { "leading": leading, "maxWait": wait, "trailing": trailing }); } module.exports = throttle2; } }); // node_modules/@transloadit/prettier-bytes/dist/prettierBytes.js var require_prettierBytes = __commonJS({ "node_modules/@transloadit/prettier-bytes/dist/prettierBytes.js"(exports, module) { "use strict"; module.exports = function prettierBytes4(input) { if (typeof input !== "number" || Number.isNaN(input)) { throw new TypeError(`Expected a number, got ${typeof input}`); } const neg = input < 0; let num = Math.abs(input); if (neg) { num = -num; } if (num === 0) { return "0 B"; } const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; const exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1); const value = Number(num / 1024 ** exponent); const unit = units[exponent]; return `${value >= 10 || value % 1 === 0 ? Math.round(value) : value.toFixed(1)} ${unit}`; }; } }); // node_modules/wildcard/index.js var require_wildcard = __commonJS({ "node_modules/wildcard/index.js"(exports, module) { "use strict"; function WildcardMatcher(text2, separator2) { this.text = text2 = text2 || ""; this.hasWild = ~text2.indexOf("*"); this.separator = separator2; this.parts = text2.split(separator2); } WildcardMatcher.prototype.match = function(input) { var matches = true; var parts = this.parts; var ii; var partsCount = parts.length; var testParts; if (typeof input == "string" || input instanceof String) { if (!this.hasWild && this.text != input) { matches = false; } else { testParts = (input || "").split(this.separator); for (ii = 0; matches && ii < partsCount; ii++) { if (parts[ii] === "*") { continue; } else if (ii < testParts.length) { matches = parts[ii] === testParts[ii]; } else { matches = false; } } matches = matches && testParts; } } else if (typeof input.splice == "function") { matches = []; for (ii = input.length; ii--; ) { if (this.match(input[ii])) { matches[matches.length] = input[ii]; } } } else if (typeof input == "object") { matches = {}; for (var key in input) { if (this.match(key)) { matches[key] = input[key]; } } } return matches; }; module.exports = function(text2, test, separator2) { var matcher = new WildcardMatcher(text2, separator2 || /[\/\.]/); if (typeof test != "undefined") { return matcher.match(test); } return matcher; }; } }); // node_modules/mime-match/index.js var require_mime_match = __commonJS({ "node_modules/mime-match/index.js"(exports, module) { var wildcard = require_wildcard(); var reMimePartSplit = /[\/\+\.]/; module.exports = function(target, pattern) { function test(pattern2) { var result = wildcard(pattern2, target, reMimePartSplit); return result && result.length >= 2; } return pattern ? test(pattern.split(";")[0]) : test; }; } }); // node_modules/classnames/index.js var require_classnames = __commonJS({ "node_modules/classnames/index.js"(exports, module) { (function() { "use strict"; var hasOwn = {}.hasOwnProperty; function classNames15() { var classes = ""; for (var i4 = 0; i4 < arguments.length; i4++) { var arg = arguments[i4]; if (arg) { classes = appendClass(classes, parseValue(arg)); } } return classes; } function parseValue(arg) { if (typeof arg === "string" || typeof arg === "number") { return arg; } if (typeof arg !== "object") { return ""; } if (Array.isArray(arg)) { return classNames15.apply(null, arg); } if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) { return arg.toString(); } var classes = ""; for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes = appendClass(classes, key); } } return classes; } function appendClass(value, newClass) { if (!newClass) { return value; } if (value) { return value + " " + newClass; } return value + newClass; } if (typeof module !== "undefined" && module.exports) { classNames15.default = classNames15; module.exports = classNames15; } else if (typeof define === "function" && typeof define.amd === "object" && define.amd) { define("classnames", [], function() { return classNames15; }); } else { window.classNames = classNames15; } })(); } }); // node_modules/eventemitter3/index.js var require_eventemitter3 = __commonJS({ "node_modules/eventemitter3/index.js"(exports, module) { "use strict"; var has = Object.prototype.hasOwnProperty; var prefix = "~"; function Events() { } if (Object.create) { Events.prototype = /* @__PURE__ */ Object.create(null); if (!new Events().__proto__) prefix = false; } function EE(fn2, context, once) { this.fn = fn2; this.context = context; this.once = once || false; } function addListener(emitter, event, fn2, context, once) { if (typeof fn2 !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn2, context || emitter, once), evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } function EventEmitter2() { this._events = new Events(); this._eventsCount = 0; } EventEmitter2.prototype.eventNames = function eventNames() { var names = [], events, name; if (this._eventsCount === 0) return names; for (name in events = this._events) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; EventEmitter2.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i4 = 0, l4 = handlers.length, ee3 = new Array(l4); i4 < l4; i4++) { ee3[i4] = handlers[i4].fn; } return ee3; }; EventEmitter2.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter2.prototype.emit = function emit(event, a1, a22, a32, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i4; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a22), true; case 4: return listeners.fn.call(listeners.context, a1, a22, a32), true; case 5: return listeners.fn.call(listeners.context, a1, a22, a32, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a22, a32, a4, a5), true; } for (i4 = 1, args = new Array(len - 1); i4 < len; i4++) { args[i4 - 1] = arguments[i4]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length, j4; for (i4 = 0; i4 < length; i4++) { if (listeners[i4].once) this.removeListener(event, listeners[i4].fn, void 0, true); switch (len) { case 1: listeners[i4].fn.call(listeners[i4].context); break; case 2: listeners[i4].fn.call(listeners[i4].context, a1); break; case 3: listeners[i4].fn.call(listeners[i4].context, a1, a22); break; case 4: listeners[i4].fn.call(listeners[i4].context, a1, a22, a32); break; default: if (!args) for (j4 = 1, args = new Array(len - 1); j4 < len; j4++) { args[j4 - 1] = arguments[j4]; } listeners[i4].fn.apply(listeners[i4].context, args); } } } return true; }; EventEmitter2.prototype.on = function on(event, fn2, context) { return addListener(this, event, fn2, context, false); }; EventEmitter2.prototype.once = function once(event, fn2, context) { return addListener(this, event, fn2, context, true); }; EventEmitter2.prototype.removeListener = function removeListener(event, fn2, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn2) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn2 && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i4 = 0, events = [], length = listeners.length; i4 < length; i4++) { if (listeners[i4].fn !== fn2 || once && !listeners[i4].once || context && listeners[i4].context !== context) { events.push(listeners[i4]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; EventEmitter2.prefixed = prefix; EventEmitter2.EventEmitter = EventEmitter2; if ("undefined" !== typeof module) { module.exports = EventEmitter2; } } }); // node_modules/cropperjs/dist/cropper.js var require_cropper = __commonJS({ "node_modules/cropperjs/dist/cropper.js"(exports, module) { (function(global2, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Cropper = factory()); })(exports, function() { "use strict"; function ownKeys(e4, r4) { var t4 = Object.keys(e4); if (Object.getOwnPropertySymbols) { var o4 = Object.getOwnPropertySymbols(e4); r4 && (o4 = o4.filter(function(r5) { return Object.getOwnPropertyDescriptor(e4, r5).enumerable; })), t4.push.apply(t4, o4); } return t4; } function _objectSpread2(e4) { for (var r4 = 1; r4 < arguments.length; r4++) { var t4 = null != arguments[r4] ? arguments[r4] : {}; r4 % 2 ? ownKeys(Object(t4), true).forEach(function(r5) { _defineProperty(e4, r5, t4[r5]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e4, Object.getOwnPropertyDescriptors(t4)) : ownKeys(Object(t4)).forEach(function(r5) { Object.defineProperty(e4, r5, Object.getOwnPropertyDescriptor(t4, r5)); }); } return e4; } function _toPrimitive(t4, r4) { if ("object" != typeof t4 || !t4) return t4; var e4 = t4[Symbol.toPrimitive]; if (void 0 !== e4) { var i4 = e4.call(t4, r4 || "default"); if ("object" != typeof i4) return i4; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r4 ? String : Number)(t4); } function _toPropertyKey(t4) { var i4 = _toPrimitive(t4, "string"); return "symbol" == typeof i4 ? i4 : i4 + ""; } function _typeof(o4) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o5) { return typeof o5; } : function(o5) { return o5 && "function" == typeof Symbol && o5.constructor === Symbol && o5 !== Symbol.prototype ? "symbol" : typeof o5; }, _typeof(o4); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i4 = 0; i4 < props.length; i4++) { var descriptor = props[i4]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o4, minLen) { if (!o4) return; if (typeof o4 === "string") return _arrayLikeToArray(o4, minLen); var n3 = Object.prototype.toString.call(o4).slice(8, -1); if (n3 === "Object" && o4.constructor) n3 = o4.constructor.name; if (n3 === "Map" || n3 === "Set") return Array.from(o4); if (n3 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n3)) return _arrayLikeToArray(o4, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i4 = 0, arr2 = new Array(len); i4 < len; i4++) arr2[i4] = arr[i4]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var IS_BROWSER = typeof window !== "undefined" && typeof window.document !== "undefined"; var WINDOW = IS_BROWSER ? window : {}; var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? "ontouchstart" in WINDOW.document.documentElement : false; var HAS_POINTER_EVENT = IS_BROWSER ? "PointerEvent" in WINDOW : false; var NAMESPACE = "cropper"; var ACTION_ALL = "all"; var ACTION_CROP = "crop"; var ACTION_MOVE = "move"; var ACTION_ZOOM = "zoom"; var ACTION_EAST = "e"; var ACTION_WEST = "w"; var ACTION_SOUTH = "s"; var ACTION_NORTH = "n"; var ACTION_NORTH_EAST = "ne"; var ACTION_NORTH_WEST = "nw"; var ACTION_SOUTH_EAST = "se"; var ACTION_SOUTH_WEST = "sw"; var CLASS_CROP = "".concat(NAMESPACE, "-crop"); var CLASS_DISABLED = "".concat(NAMESPACE, "-disabled"); var CLASS_HIDDEN = "".concat(NAMESPACE, "-hidden"); var CLASS_HIDE = "".concat(NAMESPACE, "-hide"); var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible"); var CLASS_MODAL = "".concat(NAMESPACE, "-modal"); var CLASS_MOVE = "".concat(NAMESPACE, "-move"); var DATA_ACTION = "".concat(NAMESPACE, "Action"); var DATA_PREVIEW = "".concat(NAMESPACE, "Preview"); var DRAG_MODE_CROP = "crop"; var DRAG_MODE_MOVE = "move"; var DRAG_MODE_NONE = "none"; var EVENT_CROP = "crop"; var EVENT_CROP_END = "cropend"; var EVENT_CROP_MOVE = "cropmove"; var EVENT_CROP_START = "cropstart"; var EVENT_DBLCLICK = "dblclick"; var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? "touchstart" : "mousedown"; var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? "touchmove" : "mousemove"; var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? "touchend touchcancel" : "mouseup"; var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? "pointerdown" : EVENT_TOUCH_START; var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? "pointermove" : EVENT_TOUCH_MOVE; var EVENT_POINTER_UP = HAS_POINTER_EVENT ? "pointerup pointercancel" : EVENT_TOUCH_END; var EVENT_READY = "ready"; var EVENT_RESIZE = "resize"; var EVENT_WHEEL = "wheel"; var EVENT_ZOOM = "zoom"; var MIME_TYPE_JPEG = "image/jpeg"; var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/; var REGEXP_DATA_URL = /^data:/; var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/; var REGEXP_TAG_NAME = /^img|canvas$/i; var MIN_CONTAINER_WIDTH = 200; var MIN_CONTAINER_HEIGHT = 100; var DEFAULTS = { // Define the view mode of the cropper viewMode: 0, // 0, 1, 2, 3 // Define the dragging mode of the cropper dragMode: DRAG_MODE_CROP, // 'crop', 'move' or 'none' // Define the initial aspect ratio of the crop box initialAspectRatio: NaN, // Define the aspect ratio of the crop box aspectRatio: NaN, // An object with the previous cropping result data data: null, // A selector for adding extra containers to preview preview: "", // Re-render the cropper when resize the window responsive: true, // Restore the cropped area after resize the window restore: true, // Check if the current image is a cross-origin image checkCrossOrigin: true, // Check the current image's Exif Orientation information checkOrientation: true, // Show the black modal modal: true, // Show the dashed lines for guiding guides: true, // Show the center indicator for guiding center: true, // Show the white modal to highlight the crop box highlight: true, // Show the grid background background: true, // Enable to crop the image automatically when initialize autoCrop: true, // Define the percentage of automatic cropping area when initializes autoCropArea: 0.8, // Enable to move the image movable: true, // Enable to rotate the image rotatable: true, // Enable to scale the image scalable: true, // Enable to zoom the image zoomable: true, // Enable to zoom the image by dragging touch zoomOnTouch: true, // Enable to zoom the image by wheeling mouse zoomOnWheel: true, // Define zoom ratio when zoom the image by wheeling mouse wheelZoomRatio: 0.1, // Enable to move the crop box cropBoxMovable: true, // Enable to resize the crop box cropBoxResizable: true, // Toggle drag mode between "crop" and "move" when click twice on the cropper toggleDragModeOnDblclick: true, // Size limitation minCanvasWidth: 0, minCanvasHeight: 0, minCropBoxWidth: 0, minCropBoxHeight: 0, minContainerWidth: MIN_CONTAINER_WIDTH, minContainerHeight: MIN_CONTAINER_HEIGHT, // Shortcuts of events ready: null, cropstart: null, cropmove: null, cropend: null, crop: null, zoom: null }; var TEMPLATE = '
'; var isNaN = Number.isNaN || WINDOW.isNaN; function isNumber(value) { return typeof value === "number" && !isNaN(value); } var isPositiveNumber = function isPositiveNumber2(value) { return value > 0 && value < Infinity; }; function isUndefined(value) { return typeof value === "undefined"; } function isObject(value) { return _typeof(value) === "object" && value !== null; } var hasOwnProperty = Object.prototype.hasOwnProperty; function isPlainObject(value) { if (!isObject(value)) { return false; } try { var _constructor = value.constructor; var prototype = _constructor.prototype; return _constructor && prototype && hasOwnProperty.call(prototype, "isPrototypeOf"); } catch (error2) { return false; } } function isFunction(value) { return typeof value === "function"; } var slice = Array.prototype.slice; function toArray(value) { return Array.from ? Array.from(value) : slice.call(value); } function forEach(data, callback) { if (data && isFunction(callback)) { if (Array.isArray(data) || isNumber(data.length)) { toArray(data).forEach(function(value, key) { callback.call(data, value, key, data); }); } else if (isObject(data)) { Object.keys(data).forEach(function(key) { callback.call(data, data[key], key, data); }); } } return data; } var assign2 = Object.assign || function assign3(target) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (isObject(target) && args.length > 0) { args.forEach(function(arg) { if (isObject(arg)) { Object.keys(arg).forEach(function(key) { target[key] = arg[key]; }); } }); } return target; }; var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/; function normalizeDecimalNumber(value) { var times = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1e11; return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value; } var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/; function setStyle(element, styles) { var style = element.style; forEach(styles, function(value, property) { if (REGEXP_SUFFIX.test(property) && isNumber(value)) { value = "".concat(value, "px"); } style[property] = value; }); } function hasClass(element, value) { return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1; } function addClass(element, value) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { addClass(elem, value); }); return; } if (element.classList) { element.classList.add(value); return; } var className = element.className.trim(); if (!className) { element.className = value; } else if (className.indexOf(value) < 0) { element.className = "".concat(className, " ").concat(value); } } function removeClass(element, value) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { removeClass(elem, value); }); return; } if (element.classList) { element.classList.remove(value); return; } if (element.className.indexOf(value) >= 0) { element.className = element.className.replace(value, ""); } } function toggleClass(element, value, added) { if (!value) { return; } if (isNumber(element.length)) { forEach(element, function(elem) { toggleClass(elem, value, added); }); return; } if (added) { addClass(element, value); } else { removeClass(element, value); } } var REGEXP_CAMEL_CASE = /([a-z\d])([A-Z])/g; function toParamCase(value) { return value.replace(REGEXP_CAMEL_CASE, "$1-$2").toLowerCase(); } function getData(element, name) { if (isObject(element[name])) { return element[name]; } if (element.dataset) { return element.dataset[name]; } return element.getAttribute("data-".concat(toParamCase(name))); } function setData(element, name, data) { if (isObject(data)) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute("data-".concat(toParamCase(name)), data); } } function removeData(element, name) { if (isObject(element[name])) { try { delete element[name]; } catch (error2) { element[name] = void 0; } } else if (element.dataset) { try { delete element.dataset[name]; } catch (error2) { element.dataset[name] = void 0; } } else { element.removeAttribute("data-".concat(toParamCase(name))); } } var REGEXP_SPACES = /\s\s*/; var onceSupported = function() { var supported = false; if (IS_BROWSER) { var once = false; var listener = function listener2() { }; var options2 = Object.defineProperty({}, "once", { get: function get() { supported = true; return once; }, /** * This setter can fix a `TypeError` in strict mode * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only} * @param {boolean} value - The value to set */ set: function set(value) { once = value; } }); WINDOW.addEventListener("test", listener, options2); WINDOW.removeEventListener("test", listener, options2); } return supported; }(); function removeListener(element, type, listener) { var options2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; var handler = listener; type.trim().split(REGEXP_SPACES).forEach(function(event) { if (!onceSupported) { var listeners = element.listeners; if (listeners && listeners[event] && listeners[event][listener]) { handler = listeners[event][listener]; delete listeners[event][listener]; if (Object.keys(listeners[event]).length === 0) { delete listeners[event]; } if (Object.keys(listeners).length === 0) { delete element.listeners; } } } element.removeEventListener(event, handler, options2); }); } function addListener(element, type, listener) { var options2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; var _handler = listener; type.trim().split(REGEXP_SPACES).forEach(function(event) { if (options2.once && !onceSupported) { var _element$listeners = element.listeners, listeners = _element$listeners === void 0 ? {} : _element$listeners; _handler = function handler() { delete listeners[event][listener]; element.removeEventListener(event, _handler, options2); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } listener.apply(element, args); }; if (!listeners[event]) { listeners[event] = {}; } if (listeners[event][listener]) { element.removeEventListener(event, listeners[event][listener], options2); } listeners[event][listener] = _handler; element.listeners = listeners; } element.addEventListener(event, _handler, options2); }); } function dispatchEvent2(element, type, data) { var event; if (isFunction(Event) && isFunction(CustomEvent)) { event = new CustomEvent(type, { detail: data, bubbles: true, cancelable: true }); } else { event = document.createEvent("CustomEvent"); event.initCustomEvent(type, true, true, data); } return element.dispatchEvent(event); } function getOffset(element) { var box = element.getBoundingClientRect(); return { left: box.left + (window.pageXOffset - document.documentElement.clientLeft), top: box.top + (window.pageYOffset - document.documentElement.clientTop) }; } var location2 = WINDOW.location; var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i; function isCrossOriginURL(url) { var parts = url.match(REGEXP_ORIGINS); return parts !== null && (parts[1] !== location2.protocol || parts[2] !== location2.hostname || parts[3] !== location2.port); } function addTimestamp(url) { var timestamp = "timestamp=".concat((/* @__PURE__ */ new Date()).getTime()); return url + (url.indexOf("?") === -1 ? "?" : "&") + timestamp; } function getTransforms(_ref) { var rotate = _ref.rotate, scaleX = _ref.scaleX, scaleY = _ref.scaleY, translateX = _ref.translateX, translateY = _ref.translateY; var values = []; if (isNumber(translateX) && translateX !== 0) { values.push("translateX(".concat(translateX, "px)")); } if (isNumber(translateY) && translateY !== 0) { values.push("translateY(".concat(translateY, "px)")); } if (isNumber(rotate) && rotate !== 0) { values.push("rotate(".concat(rotate, "deg)")); } if (isNumber(scaleX) && scaleX !== 1) { values.push("scaleX(".concat(scaleX, ")")); } if (isNumber(scaleY) && scaleY !== 1) { values.push("scaleY(".concat(scaleY, ")")); } var transform = values.length ? values.join(" ") : "none"; return { WebkitTransform: transform, msTransform: transform, transform }; } function getMaxZoomRatio(pointers) { var pointers2 = _objectSpread2({}, pointers); var maxRatio = 0; forEach(pointers, function(pointer, pointerId) { delete pointers2[pointerId]; forEach(pointers2, function(pointer2) { var x1 = Math.abs(pointer.startX - pointer2.startX); var y1 = Math.abs(pointer.startY - pointer2.startY); var x22 = Math.abs(pointer.endX - pointer2.endX); var y22 = Math.abs(pointer.endY - pointer2.endY); var z1 = Math.sqrt(x1 * x1 + y1 * y1); var z22 = Math.sqrt(x22 * x22 + y22 * y22); var ratio = (z22 - z1) / z1; if (Math.abs(ratio) > Math.abs(maxRatio)) { maxRatio = ratio; } }); }); return maxRatio; } function getPointer(_ref2, endOnly) { var pageX = _ref2.pageX, pageY = _ref2.pageY; var end2 = { endX: pageX, endY: pageY }; return endOnly ? end2 : _objectSpread2({ startX: pageX, startY: pageY }, end2); } function getPointersCenter(pointers) { var pageX = 0; var pageY = 0; var count = 0; forEach(pointers, function(_ref3) { var startX = _ref3.startX, startY = _ref3.startY; pageX += startX; pageY += startY; count += 1; }); pageX /= count; pageY /= count; return { pageX, pageY }; } function getAdjustedSizes(_ref4) { var aspectRatio = _ref4.aspectRatio, height = _ref4.height, width = _ref4.width; var type = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "contain"; var isValidWidth = isPositiveNumber(width); var isValidHeight = isPositiveNumber(height); if (isValidWidth && isValidHeight) { var adjustedWidth = height * aspectRatio; if (type === "contain" && adjustedWidth > width || type === "cover" && adjustedWidth < width) { height = width / aspectRatio; } else { width = height * aspectRatio; } } else if (isValidWidth) { height = width / aspectRatio; } else if (isValidHeight) { width = height * aspectRatio; } return { width, height }; } function getRotatedSizes(_ref5) { var width = _ref5.width, height = _ref5.height, degree = _ref5.degree; degree = Math.abs(degree) % 180; if (degree === 90) { return { width: height, height: width }; } var arc = degree % 90 * Math.PI / 180; var sinArc = Math.sin(arc); var cosArc = Math.cos(arc); var newWidth = width * cosArc + height * sinArc; var newHeight = width * sinArc + height * cosArc; return degree > 90 ? { width: newHeight, height: newWidth } : { width: newWidth, height: newHeight }; } function getSourceCanvas(image, _ref6, _ref7, _ref8) { var imageAspectRatio = _ref6.aspectRatio, imageNaturalWidth = _ref6.naturalWidth, imageNaturalHeight = _ref6.naturalHeight, _ref6$rotate = _ref6.rotate, rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate, _ref6$scaleX = _ref6.scaleX, scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX, _ref6$scaleY = _ref6.scaleY, scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY; var aspectRatio = _ref7.aspectRatio, naturalWidth = _ref7.naturalWidth, naturalHeight = _ref7.naturalHeight; var _ref8$fillColor = _ref8.fillColor, fillColor = _ref8$fillColor === void 0 ? "transparent" : _ref8$fillColor, _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled, imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE, _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality, imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? "low" : _ref8$imageSmoothingQ, _ref8$maxWidth = _ref8.maxWidth, maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth, _ref8$maxHeight = _ref8.maxHeight, maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight, _ref8$minWidth = _ref8.minWidth, minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth, _ref8$minHeight = _ref8.minHeight, minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight; var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); var maxSizes = getAdjustedSizes({ aspectRatio, width: maxWidth, height: maxHeight }); var minSizes = getAdjustedSizes({ aspectRatio, width: minWidth, height: minHeight }, "cover"); var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth)); var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); var destMaxSizes = getAdjustedSizes({ aspectRatio: imageAspectRatio, width: maxWidth, height: maxHeight }); var destMinSizes = getAdjustedSizes({ aspectRatio: imageAspectRatio, width: minWidth, height: minHeight }, "cover"); var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth)); var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight)); var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight]; canvas.width = normalizeDecimalNumber(width); canvas.height = normalizeDecimalNumber(height); context.fillStyle = fillColor; context.fillRect(0, 0, width, height); context.save(); context.translate(width / 2, height / 2); context.rotate(rotate * Math.PI / 180); context.scale(scaleX, scaleY); context.imageSmoothingEnabled = imageSmoothingEnabled; context.imageSmoothingQuality = imageSmoothingQuality; context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function(param) { return Math.floor(normalizeDecimalNumber(param)); })))); context.restore(); return canvas; } var fromCharCode = String.fromCharCode; function getStringFromCharCode(dataView, start3, length) { var str = ""; length += start3; for (var i4 = start3; i4 < length; i4 += 1) { str += fromCharCode(dataView.getUint8(i4)); } return str; } var REGEXP_DATA_URL_HEAD = /^data:.*,/; function dataURLToArrayBuffer(dataURL) { var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, ""); var binary = atob(base64); var arrayBuffer = new ArrayBuffer(binary.length); var uint8 = new Uint8Array(arrayBuffer); forEach(uint8, function(value, i4) { uint8[i4] = binary.charCodeAt(i4); }); return arrayBuffer; } function arrayBufferToDataURL(arrayBuffer, mimeType) { var chunks2 = []; var chunkSize = 8192; var uint8 = new Uint8Array(arrayBuffer); while (uint8.length > 0) { chunks2.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize)))); uint8 = uint8.subarray(chunkSize); } return "data:".concat(mimeType, ";base64,").concat(btoa(chunks2.join(""))); } function resetAndGetOrientation(arrayBuffer) { var dataView = new DataView(arrayBuffer); var orientation; try { var littleEndian; var app1Start; var ifdStart; if (dataView.getUint8(0) === 255 && dataView.getUint8(1) === 216) { var length = dataView.byteLength; var offset2 = 2; while (offset2 + 1 < length) { if (dataView.getUint8(offset2) === 255 && dataView.getUint8(offset2 + 1) === 225) { app1Start = offset2; break; } offset2 += 1; } } if (app1Start) { var exifIDCode = app1Start + 4; var tiffOffset = app1Start + 10; if (getStringFromCharCode(dataView, exifIDCode, 4) === "Exif") { var endianness = dataView.getUint16(tiffOffset); littleEndian = endianness === 18761; if (littleEndian || endianness === 19789) { if (dataView.getUint16(tiffOffset + 2, littleEndian) === 42) { var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian); if (firstIFDOffset >= 8) { ifdStart = tiffOffset + firstIFDOffset; } } } } } if (ifdStart) { var _length = dataView.getUint16(ifdStart, littleEndian); var _offset; var i4; for (i4 = 0; i4 < _length; i4 += 1) { _offset = ifdStart + i4 * 12 + 2; if (dataView.getUint16(_offset, littleEndian) === 274) { _offset += 8; orientation = dataView.getUint16(_offset, littleEndian); dataView.setUint16(_offset, 1, littleEndian); break; } } } } catch (error2) { orientation = 1; } return orientation; } function parseOrientation(orientation) { var rotate = 0; var scaleX = 1; var scaleY = 1; switch (orientation) { case 2: scaleX = -1; break; case 3: rotate = -180; break; case 4: scaleY = -1; break; case 5: rotate = 90; scaleY = -1; break; case 6: rotate = 90; break; case 7: rotate = 90; scaleX = -1; break; case 8: rotate = -90; break; } return { rotate, scaleX, scaleY }; } var render = { render: function render2() { this.initContainer(); this.initCanvas(); this.initCropBox(); this.renderCanvas(); if (this.cropped) { this.renderCropBox(); } }, initContainer: function initContainer() { var element = this.element, options2 = this.options, container = this.container, cropper = this.cropper; var minWidth = Number(options2.minContainerWidth); var minHeight = Number(options2.minContainerHeight); addClass(cropper, CLASS_HIDDEN); removeClass(element, CLASS_HIDDEN); var containerData = { width: Math.max(container.offsetWidth, minWidth >= 0 ? minWidth : MIN_CONTAINER_WIDTH), height: Math.max(container.offsetHeight, minHeight >= 0 ? minHeight : MIN_CONTAINER_HEIGHT) }; this.containerData = containerData; setStyle(cropper, { width: containerData.width, height: containerData.height }); addClass(element, CLASS_HIDDEN); removeClass(cropper, CLASS_HIDDEN); }, // Canvas (image wrapper) initCanvas: function initCanvas() { var containerData = this.containerData, imageData = this.imageData; var viewMode = this.options.viewMode; var rotated = Math.abs(imageData.rotate) % 180 === 90; var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth; var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight; var aspectRatio = naturalWidth / naturalHeight; var canvasWidth = containerData.width; var canvasHeight = containerData.height; if (containerData.height * aspectRatio > containerData.width) { if (viewMode === 3) { canvasWidth = containerData.height * aspectRatio; } else { canvasHeight = containerData.width / aspectRatio; } } else if (viewMode === 3) { canvasHeight = containerData.width / aspectRatio; } else { canvasWidth = containerData.height * aspectRatio; } var canvasData = { aspectRatio, naturalWidth, naturalHeight, width: canvasWidth, height: canvasHeight }; this.canvasData = canvasData; this.limited = viewMode === 1 || viewMode === 2; this.limitCanvas(true, true); canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth); canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight); canvasData.left = (containerData.width - canvasData.width) / 2; canvasData.top = (containerData.height - canvasData.height) / 2; canvasData.oldLeft = canvasData.left; canvasData.oldTop = canvasData.top; this.initialCanvasData = assign2({}, canvasData); }, limitCanvas: function limitCanvas(sizeLimited, positionLimited) { var options2 = this.options, containerData = this.containerData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var viewMode = options2.viewMode; var aspectRatio = canvasData.aspectRatio; var cropped = this.cropped && cropBoxData; if (sizeLimited) { var minCanvasWidth = Number(options2.minCanvasWidth) || 0; var minCanvasHeight = Number(options2.minCanvasHeight) || 0; if (viewMode > 1) { minCanvasWidth = Math.max(minCanvasWidth, containerData.width); minCanvasHeight = Math.max(minCanvasHeight, containerData.height); if (viewMode === 3) { if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } else if (viewMode > 0) { if (minCanvasWidth) { minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0); } else if (minCanvasHeight) { minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0); } else if (cropped) { minCanvasWidth = cropBoxData.width; minCanvasHeight = cropBoxData.height; if (minCanvasHeight * aspectRatio > minCanvasWidth) { minCanvasWidth = minCanvasHeight * aspectRatio; } else { minCanvasHeight = minCanvasWidth / aspectRatio; } } } var _getAdjustedSizes = getAdjustedSizes({ aspectRatio, width: minCanvasWidth, height: minCanvasHeight }); minCanvasWidth = _getAdjustedSizes.width; minCanvasHeight = _getAdjustedSizes.height; canvasData.minWidth = minCanvasWidth; canvasData.minHeight = minCanvasHeight; canvasData.maxWidth = Infinity; canvasData.maxHeight = Infinity; } if (positionLimited) { if (viewMode > (cropped ? 0 : 1)) { var newCanvasLeft = containerData.width - canvasData.width; var newCanvasTop = containerData.height - canvasData.height; canvasData.minLeft = Math.min(0, newCanvasLeft); canvasData.minTop = Math.min(0, newCanvasTop); canvasData.maxLeft = Math.max(0, newCanvasLeft); canvasData.maxTop = Math.max(0, newCanvasTop); if (cropped && this.limited) { canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width)); canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height)); canvasData.maxLeft = cropBoxData.left; canvasData.maxTop = cropBoxData.top; if (viewMode === 2) { if (canvasData.width >= containerData.width) { canvasData.minLeft = Math.min(0, newCanvasLeft); canvasData.maxLeft = Math.max(0, newCanvasLeft); } if (canvasData.height >= containerData.height) { canvasData.minTop = Math.min(0, newCanvasTop); canvasData.maxTop = Math.max(0, newCanvasTop); } } } } else { canvasData.minLeft = -canvasData.width; canvasData.minTop = -canvasData.height; canvasData.maxLeft = containerData.width; canvasData.maxTop = containerData.height; } } }, renderCanvas: function renderCanvas(changed, transformed) { var canvasData = this.canvasData, imageData = this.imageData; if (transformed) { var _getRotatedSizes = getRotatedSizes({ width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1), height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1), degree: imageData.rotate || 0 }), naturalWidth = _getRotatedSizes.width, naturalHeight = _getRotatedSizes.height; var width = canvasData.width * (naturalWidth / canvasData.naturalWidth); var height = canvasData.height * (naturalHeight / canvasData.naturalHeight); canvasData.left -= (width - canvasData.width) / 2; canvasData.top -= (height - canvasData.height) / 2; canvasData.width = width; canvasData.height = height; canvasData.aspectRatio = naturalWidth / naturalHeight; canvasData.naturalWidth = naturalWidth; canvasData.naturalHeight = naturalHeight; this.limitCanvas(true, false); } if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) { canvasData.left = canvasData.oldLeft; } if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) { canvasData.top = canvasData.oldTop; } canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth); canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight); this.limitCanvas(false, true); canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft); canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop); canvasData.oldLeft = canvasData.left; canvasData.oldTop = canvasData.top; setStyle(this.canvas, assign2({ width: canvasData.width, height: canvasData.height }, getTransforms({ translateX: canvasData.left, translateY: canvasData.top }))); this.renderImage(changed); if (this.cropped && this.limited) { this.limitCropBox(true, true); } }, renderImage: function renderImage(changed) { var canvasData = this.canvasData, imageData = this.imageData; var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth); var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight); assign2(imageData, { width, height, left: (canvasData.width - width) / 2, top: (canvasData.height - height) / 2 }); setStyle(this.image, assign2({ width: imageData.width, height: imageData.height }, getTransforms(assign2({ translateX: imageData.left, translateY: imageData.top }, imageData)))); if (changed) { this.output(); } }, initCropBox: function initCropBox() { var options2 = this.options, canvasData = this.canvasData; var aspectRatio = options2.aspectRatio || options2.initialAspectRatio; var autoCropArea = Number(options2.autoCropArea) || 0.8; var cropBoxData = { width: canvasData.width, height: canvasData.height }; if (aspectRatio) { if (canvasData.height * aspectRatio > canvasData.width) { cropBoxData.height = cropBoxData.width / aspectRatio; } else { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.cropBoxData = cropBoxData; this.limitCropBox(true, true); cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea); cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea); cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2; cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2; cropBoxData.oldLeft = cropBoxData.left; cropBoxData.oldTop = cropBoxData.top; this.initialCropBoxData = assign2({}, cropBoxData); }, limitCropBox: function limitCropBox(sizeLimited, positionLimited) { var options2 = this.options, containerData = this.containerData, canvasData = this.canvasData, cropBoxData = this.cropBoxData, limited = this.limited; var aspectRatio = options2.aspectRatio; if (sizeLimited) { var minCropBoxWidth = Number(options2.minCropBoxWidth) || 0; var minCropBoxHeight = Number(options2.minCropBoxHeight) || 0; var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width; var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width); minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height); if (aspectRatio) { if (minCropBoxWidth && minCropBoxHeight) { if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else { minCropBoxWidth = minCropBoxHeight * aspectRatio; } } else if (minCropBoxWidth) { minCropBoxHeight = minCropBoxWidth / aspectRatio; } else if (minCropBoxHeight) { minCropBoxWidth = minCropBoxHeight * aspectRatio; } if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { maxCropBoxHeight = maxCropBoxWidth / aspectRatio; } else { maxCropBoxWidth = maxCropBoxHeight * aspectRatio; } } cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth); cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight); cropBoxData.maxWidth = maxCropBoxWidth; cropBoxData.maxHeight = maxCropBoxHeight; } if (positionLimited) { if (limited) { cropBoxData.minLeft = Math.max(0, canvasData.left); cropBoxData.minTop = Math.max(0, canvasData.top); cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width; cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height; } else { cropBoxData.minLeft = 0; cropBoxData.minTop = 0; cropBoxData.maxLeft = containerData.width - cropBoxData.width; cropBoxData.maxTop = containerData.height - cropBoxData.height; } } }, renderCropBox: function renderCropBox() { var options2 = this.options, containerData = this.containerData, cropBoxData = this.cropBoxData; if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) { cropBoxData.left = cropBoxData.oldLeft; } if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) { cropBoxData.top = cropBoxData.oldTop; } cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); this.limitCropBox(false, true); cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft); cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop); cropBoxData.oldLeft = cropBoxData.left; cropBoxData.oldTop = cropBoxData.top; if (options2.movable && options2.cropBoxMovable) { setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL); } setStyle(this.cropBox, assign2({ width: cropBoxData.width, height: cropBoxData.height }, getTransforms({ translateX: cropBoxData.left, translateY: cropBoxData.top }))); if (this.cropped && this.limited) { this.limitCanvas(true, true); } if (!this.disabled) { this.output(); } }, output: function output() { this.preview(); dispatchEvent2(this.element, EVENT_CROP, this.getData()); } }; var preview = { initPreview: function initPreview() { var element = this.element, crossOrigin = this.crossOrigin; var preview2 = this.options.preview; var url = crossOrigin ? this.crossOriginUrl : this.url; var alt = element.alt || "The image to preview"; var image = document.createElement("img"); if (crossOrigin) { image.crossOrigin = crossOrigin; } image.src = url; image.alt = alt; this.viewBox.appendChild(image); this.viewBoxImage = image; if (!preview2) { return; } var previews = preview2; if (typeof preview2 === "string") { previews = element.ownerDocument.querySelectorAll(preview2); } else if (preview2.querySelector) { previews = [preview2]; } this.previews = previews; forEach(previews, function(el) { var img = document.createElement("img"); setData(el, DATA_PREVIEW, { width: el.offsetWidth, height: el.offsetHeight, html: el.innerHTML }); if (crossOrigin) { img.crossOrigin = crossOrigin; } img.src = url; img.alt = alt; img.style.cssText = 'display:block;width:100%;height:auto;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important;"'; el.innerHTML = ""; el.appendChild(img); }); }, resetPreview: function resetPreview() { forEach(this.previews, function(element) { var data = getData(element, DATA_PREVIEW); setStyle(element, { width: data.width, height: data.height }); element.innerHTML = data.html; removeData(element, DATA_PREVIEW); }); }, preview: function preview2() { var imageData = this.imageData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var cropBoxWidth = cropBoxData.width, cropBoxHeight = cropBoxData.height; var width = imageData.width, height = imageData.height; var left2 = cropBoxData.left - canvasData.left - imageData.left; var top2 = cropBoxData.top - canvasData.top - imageData.top; if (!this.cropped || this.disabled) { return; } setStyle(this.viewBoxImage, assign2({ width, height }, getTransforms(assign2({ translateX: -left2, translateY: -top2 }, imageData)))); forEach(this.previews, function(element) { var data = getData(element, DATA_PREVIEW); var originalWidth = data.width; var originalHeight = data.height; var newWidth = originalWidth; var newHeight = originalHeight; var ratio = 1; if (cropBoxWidth) { ratio = originalWidth / cropBoxWidth; newHeight = cropBoxHeight * ratio; } if (cropBoxHeight && newHeight > originalHeight) { ratio = originalHeight / cropBoxHeight; newWidth = cropBoxWidth * ratio; newHeight = originalHeight; } setStyle(element, { width: newWidth, height: newHeight }); setStyle(element.getElementsByTagName("img")[0], assign2({ width: width * ratio, height: height * ratio }, getTransforms(assign2({ translateX: -left2 * ratio, translateY: -top2 * ratio }, imageData)))); }); } }; var events = { bind: function bind() { var element = this.element, options2 = this.options, cropper = this.cropper; if (isFunction(options2.cropstart)) { addListener(element, EVENT_CROP_START, options2.cropstart); } if (isFunction(options2.cropmove)) { addListener(element, EVENT_CROP_MOVE, options2.cropmove); } if (isFunction(options2.cropend)) { addListener(element, EVENT_CROP_END, options2.cropend); } if (isFunction(options2.crop)) { addListener(element, EVENT_CROP, options2.crop); } if (isFunction(options2.zoom)) { addListener(element, EVENT_ZOOM, options2.zoom); } addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this)); if (options2.zoomable && options2.zoomOnWheel) { addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), { passive: false, capture: true }); } if (options2.toggleDragModeOnDblclick) { addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this)); } addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this)); addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this)); if (options2.responsive) { addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this)); } }, unbind: function unbind() { var element = this.element, options2 = this.options, cropper = this.cropper; if (isFunction(options2.cropstart)) { removeListener(element, EVENT_CROP_START, options2.cropstart); } if (isFunction(options2.cropmove)) { removeListener(element, EVENT_CROP_MOVE, options2.cropmove); } if (isFunction(options2.cropend)) { removeListener(element, EVENT_CROP_END, options2.cropend); } if (isFunction(options2.crop)) { removeListener(element, EVENT_CROP, options2.crop); } if (isFunction(options2.zoom)) { removeListener(element, EVENT_ZOOM, options2.zoom); } removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart); if (options2.zoomable && options2.zoomOnWheel) { removeListener(cropper, EVENT_WHEEL, this.onWheel, { passive: false, capture: true }); } if (options2.toggleDragModeOnDblclick) { removeListener(cropper, EVENT_DBLCLICK, this.onDblclick); } removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove); removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd); if (options2.responsive) { removeListener(window, EVENT_RESIZE, this.onResize); } } }; var handlers = { resize: function resize() { if (this.disabled) { return; } var options2 = this.options, container = this.container, containerData = this.containerData; var ratioX = container.offsetWidth / containerData.width; var ratioY = container.offsetHeight / containerData.height; var ratio = Math.abs(ratioX - 1) > Math.abs(ratioY - 1) ? ratioX : ratioY; if (ratio !== 1) { var canvasData; var cropBoxData; if (options2.restore) { canvasData = this.getCanvasData(); cropBoxData = this.getCropBoxData(); } this.render(); if (options2.restore) { this.setCanvasData(forEach(canvasData, function(n3, i4) { canvasData[i4] = n3 * ratio; })); this.setCropBoxData(forEach(cropBoxData, function(n3, i4) { cropBoxData[i4] = n3 * ratio; })); } } }, dblclick: function dblclick() { if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) { return; } this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP); }, wheel: function wheel(event) { var _this = this; var ratio = Number(this.options.wheelZoomRatio) || 0.1; var delta = 1; if (this.disabled) { return; } event.preventDefault(); if (this.wheeling) { return; } this.wheeling = true; setTimeout(function() { _this.wheeling = false; }, 50); if (event.deltaY) { delta = event.deltaY > 0 ? 1 : -1; } else if (event.wheelDelta) { delta = -event.wheelDelta / 120; } else if (event.detail) { delta = event.detail > 0 ? 1 : -1; } this.zoom(-delta * ratio, event); }, cropStart: function cropStart(event) { var buttons = event.buttons, button = event.button; if (this.disabled || (event.type === "mousedown" || event.type === "pointerdown" && event.pointerType === "mouse") && // No primary button (Usually the left button) (isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 || event.ctrlKey)) { return; } var options2 = this.options, pointers = this.pointers; var action; if (event.changedTouches) { forEach(event.changedTouches, function(touch) { pointers[touch.identifier] = getPointer(touch); }); } else { pointers[event.pointerId || 0] = getPointer(event); } if (Object.keys(pointers).length > 1 && options2.zoomable && options2.zoomOnTouch) { action = ACTION_ZOOM; } else { action = getData(event.target, DATA_ACTION); } if (!REGEXP_ACTIONS.test(action)) { return; } if (dispatchEvent2(this.element, EVENT_CROP_START, { originalEvent: event, action }) === false) { return; } event.preventDefault(); this.action = action; this.cropping = false; if (action === ACTION_CROP) { this.cropping = true; addClass(this.dragBox, CLASS_MODAL); } }, cropMove: function cropMove(event) { var action = this.action; if (this.disabled || !action) { return; } var pointers = this.pointers; event.preventDefault(); if (dispatchEvent2(this.element, EVENT_CROP_MOVE, { originalEvent: event, action }) === false) { return; } if (event.changedTouches) { forEach(event.changedTouches, function(touch) { assign2(pointers[touch.identifier] || {}, getPointer(touch, true)); }); } else { assign2(pointers[event.pointerId || 0] || {}, getPointer(event, true)); } this.change(event); }, cropEnd: function cropEnd(event) { if (this.disabled) { return; } var action = this.action, pointers = this.pointers; if (event.changedTouches) { forEach(event.changedTouches, function(touch) { delete pointers[touch.identifier]; }); } else { delete pointers[event.pointerId || 0]; } if (!action) { return; } event.preventDefault(); if (!Object.keys(pointers).length) { this.action = ""; } if (this.cropping) { this.cropping = false; toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal); } dispatchEvent2(this.element, EVENT_CROP_END, { originalEvent: event, action }); } }; var change = { change: function change2(event) { var options2 = this.options, canvasData = this.canvasData, containerData = this.containerData, cropBoxData = this.cropBoxData, pointers = this.pointers; var action = this.action; var aspectRatio = options2.aspectRatio; var left2 = cropBoxData.left, top2 = cropBoxData.top, width = cropBoxData.width, height = cropBoxData.height; var right2 = left2 + width; var bottom2 = top2 + height; var minLeft = 0; var minTop = 0; var maxWidth = containerData.width; var maxHeight = containerData.height; var renderable = true; var offset2; if (!aspectRatio && event.shiftKey) { aspectRatio = width && height ? width / height : 1; } if (this.limited) { minLeft = cropBoxData.minLeft; minTop = cropBoxData.minTop; maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width); maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height); } var pointer = pointers[Object.keys(pointers)[0]]; var range = { x: pointer.endX - pointer.startX, y: pointer.endY - pointer.startY }; var check = function check2(side) { switch (side) { case ACTION_EAST: if (right2 + range.x > maxWidth) { range.x = maxWidth - right2; } break; case ACTION_WEST: if (left2 + range.x < minLeft) { range.x = minLeft - left2; } break; case ACTION_NORTH: if (top2 + range.y < minTop) { range.y = minTop - top2; } break; case ACTION_SOUTH: if (bottom2 + range.y > maxHeight) { range.y = maxHeight - bottom2; } break; } }; switch (action) { case ACTION_ALL: left2 += range.x; top2 += range.y; break; case ACTION_EAST: if (range.x >= 0 && (right2 >= maxWidth || aspectRatio && (top2 <= minTop || bottom2 >= maxHeight))) { renderable = false; break; } check(ACTION_EAST); width += range.x; if (width < 0) { action = ACTION_WEST; width = -width; left2 -= width; } if (aspectRatio) { height = width / aspectRatio; top2 += (cropBoxData.height - height) / 2; } break; case ACTION_NORTH: if (range.y <= 0 && (top2 <= minTop || aspectRatio && (left2 <= minLeft || right2 >= maxWidth))) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top2 += range.y; if (height < 0) { action = ACTION_SOUTH; height = -height; top2 -= height; } if (aspectRatio) { width = height * aspectRatio; left2 += (cropBoxData.width - width) / 2; } break; case ACTION_WEST: if (range.x <= 0 && (left2 <= minLeft || aspectRatio && (top2 <= minTop || bottom2 >= maxHeight))) { renderable = false; break; } check(ACTION_WEST); width -= range.x; left2 += range.x; if (width < 0) { action = ACTION_EAST; width = -width; left2 -= width; } if (aspectRatio) { height = width / aspectRatio; top2 += (cropBoxData.height - height) / 2; } break; case ACTION_SOUTH: if (range.y >= 0 && (bottom2 >= maxHeight || aspectRatio && (left2 <= minLeft || right2 >= maxWidth))) { renderable = false; break; } check(ACTION_SOUTH); height += range.y; if (height < 0) { action = ACTION_NORTH; height = -height; top2 -= height; } if (aspectRatio) { width = height * aspectRatio; left2 += (cropBoxData.width - width) / 2; } break; case ACTION_NORTH_EAST: if (aspectRatio) { if (range.y <= 0 && (top2 <= minTop || right2 >= maxWidth)) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top2 += range.y; width = height * aspectRatio; } else { check(ACTION_NORTH); check(ACTION_EAST); if (range.x >= 0) { if (right2 < maxWidth) { width += range.x; } else if (range.y <= 0 && top2 <= minTop) { renderable = false; } } else { width += range.x; } if (range.y <= 0) { if (top2 > minTop) { height -= range.y; top2 += range.y; } } else { height -= range.y; top2 += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_WEST; height = -height; width = -width; top2 -= height; left2 -= width; } else if (width < 0) { action = ACTION_NORTH_WEST; width = -width; left2 -= width; } else if (height < 0) { action = ACTION_SOUTH_EAST; height = -height; top2 -= height; } break; case ACTION_NORTH_WEST: if (aspectRatio) { if (range.y <= 0 && (top2 <= minTop || left2 <= minLeft)) { renderable = false; break; } check(ACTION_NORTH); height -= range.y; top2 += range.y; width = height * aspectRatio; left2 += cropBoxData.width - width; } else { check(ACTION_NORTH); check(ACTION_WEST); if (range.x <= 0) { if (left2 > minLeft) { width -= range.x; left2 += range.x; } else if (range.y <= 0 && top2 <= minTop) { renderable = false; } } else { width -= range.x; left2 += range.x; } if (range.y <= 0) { if (top2 > minTop) { height -= range.y; top2 += range.y; } } else { height -= range.y; top2 += range.y; } } if (width < 0 && height < 0) { action = ACTION_SOUTH_EAST; height = -height; width = -width; top2 -= height; left2 -= width; } else if (width < 0) { action = ACTION_NORTH_EAST; width = -width; left2 -= width; } else if (height < 0) { action = ACTION_SOUTH_WEST; height = -height; top2 -= height; } break; case ACTION_SOUTH_WEST: if (aspectRatio) { if (range.x <= 0 && (left2 <= minLeft || bottom2 >= maxHeight)) { renderable = false; break; } check(ACTION_WEST); width -= range.x; left2 += range.x; height = width / aspectRatio; } else { check(ACTION_SOUTH); check(ACTION_WEST); if (range.x <= 0) { if (left2 > minLeft) { width -= range.x; left2 += range.x; } else if (range.y >= 0 && bottom2 >= maxHeight) { renderable = false; } } else { width -= range.x; left2 += range.x; } if (range.y >= 0) { if (bottom2 < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_EAST; height = -height; width = -width; top2 -= height; left2 -= width; } else if (width < 0) { action = ACTION_SOUTH_EAST; width = -width; left2 -= width; } else if (height < 0) { action = ACTION_NORTH_WEST; height = -height; top2 -= height; } break; case ACTION_SOUTH_EAST: if (aspectRatio) { if (range.x >= 0 && (right2 >= maxWidth || bottom2 >= maxHeight)) { renderable = false; break; } check(ACTION_EAST); width += range.x; height = width / aspectRatio; } else { check(ACTION_SOUTH); check(ACTION_EAST); if (range.x >= 0) { if (right2 < maxWidth) { width += range.x; } else if (range.y >= 0 && bottom2 >= maxHeight) { renderable = false; } } else { width += range.x; } if (range.y >= 0) { if (bottom2 < maxHeight) { height += range.y; } } else { height += range.y; } } if (width < 0 && height < 0) { action = ACTION_NORTH_WEST; height = -height; width = -width; top2 -= height; left2 -= width; } else if (width < 0) { action = ACTION_SOUTH_WEST; width = -width; left2 -= width; } else if (height < 0) { action = ACTION_NORTH_EAST; height = -height; top2 -= height; } break; case ACTION_MOVE: this.move(range.x, range.y); renderable = false; break; case ACTION_ZOOM: this.zoom(getMaxZoomRatio(pointers), event); renderable = false; break; case ACTION_CROP: if (!range.x || !range.y) { renderable = false; break; } offset2 = getOffset(this.cropper); left2 = pointer.startX - offset2.left; top2 = pointer.startY - offset2.top; width = cropBoxData.minWidth; height = cropBoxData.minHeight; if (range.x > 0) { action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; } else if (range.x < 0) { left2 -= width; action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; } if (range.y < 0) { top2 -= height; } if (!this.cropped) { removeClass(this.cropBox, CLASS_HIDDEN); this.cropped = true; if (this.limited) { this.limitCropBox(true, true); } } break; } if (renderable) { cropBoxData.width = width; cropBoxData.height = height; cropBoxData.left = left2; cropBoxData.top = top2; this.action = action; this.renderCropBox(); } forEach(pointers, function(p4) { p4.startX = p4.endX; p4.startY = p4.endY; }); } }; var methods = { // Show the crop box manually crop: function crop() { if (this.ready && !this.cropped && !this.disabled) { this.cropped = true; this.limitCropBox(true, true); if (this.options.modal) { addClass(this.dragBox, CLASS_MODAL); } removeClass(this.cropBox, CLASS_HIDDEN); this.setCropBoxData(this.initialCropBoxData); } return this; }, // Reset the image and crop box to their initial states reset: function reset() { if (this.ready && !this.disabled) { this.imageData = assign2({}, this.initialImageData); this.canvasData = assign2({}, this.initialCanvasData); this.cropBoxData = assign2({}, this.initialCropBoxData); this.renderCanvas(); if (this.cropped) { this.renderCropBox(); } } return this; }, // Clear the crop box clear: function clear() { if (this.cropped && !this.disabled) { assign2(this.cropBoxData, { left: 0, top: 0, width: 0, height: 0 }); this.cropped = false; this.renderCropBox(); this.limitCanvas(true, true); this.renderCanvas(); removeClass(this.dragBox, CLASS_MODAL); addClass(this.cropBox, CLASS_HIDDEN); } return this; }, /** * Replace the image's src and rebuild the cropper * @param {string} url - The new URL. * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one. * @returns {Cropper} this */ replace: function replace(url) { var hasSameSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; if (!this.disabled && url) { if (this.isImg) { this.element.src = url; } if (hasSameSize) { this.url = url; this.image.src = url; if (this.ready) { this.viewBoxImage.src = url; forEach(this.previews, function(element) { element.getElementsByTagName("img")[0].src = url; }); } } else { if (this.isImg) { this.replaced = true; } this.options.data = null; this.uncreate(); this.load(url); } } return this; }, // Enable (unfreeze) the cropper enable: function enable() { if (this.ready && this.disabled) { this.disabled = false; removeClass(this.cropper, CLASS_DISABLED); } return this; }, // Disable (freeze) the cropper disable: function disable() { if (this.ready && !this.disabled) { this.disabled = true; addClass(this.cropper, CLASS_DISABLED); } return this; }, /** * Destroy the cropper and remove the instance from the image * @returns {Cropper} this */ destroy: function destroy() { var element = this.element; if (!element[NAMESPACE]) { return this; } element[NAMESPACE] = void 0; if (this.isImg && this.replaced) { element.src = this.originalUrl; } this.uncreate(); return this; }, /** * Move the canvas with relative offsets * @param {number} offsetX - The relative offset distance on the x-axis. * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis. * @returns {Cropper} this */ move: function move(offsetX) { var offsetY = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : offsetX; var _this$canvasData = this.canvasData, left2 = _this$canvasData.left, top2 = _this$canvasData.top; return this.moveTo(isUndefined(offsetX) ? offsetX : left2 + Number(offsetX), isUndefined(offsetY) ? offsetY : top2 + Number(offsetY)); }, /** * Move the canvas to an absolute point * @param {number} x - The x-axis coordinate. * @param {number} [y=x] - The y-axis coordinate. * @returns {Cropper} this */ moveTo: function moveTo(x3) { var y4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : x3; var canvasData = this.canvasData; var changed = false; x3 = Number(x3); y4 = Number(y4); if (this.ready && !this.disabled && this.options.movable) { if (isNumber(x3)) { canvasData.left = x3; changed = true; } if (isNumber(y4)) { canvasData.top = y4; changed = true; } if (changed) { this.renderCanvas(true); } } return this; }, /** * Zoom the canvas with a relative ratio * @param {number} ratio - The target ratio. * @param {Event} _originalEvent - The original event if any. * @returns {Cropper} this */ zoom: function zoom(ratio, _originalEvent) { var canvasData = this.canvasData; ratio = Number(ratio); if (ratio < 0) { ratio = 1 / (1 - ratio); } else { ratio = 1 + ratio; } return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent); }, /** * Zoom the canvas to an absolute ratio * @param {number} ratio - The target ratio. * @param {Object} pivot - The zoom pivot point coordinate. * @param {Event} _originalEvent - The original event if any. * @returns {Cropper} this */ zoomTo: function zoomTo(ratio, pivot, _originalEvent) { var options2 = this.options, canvasData = this.canvasData; var width = canvasData.width, height = canvasData.height, naturalWidth = canvasData.naturalWidth, naturalHeight = canvasData.naturalHeight; ratio = Number(ratio); if (ratio >= 0 && this.ready && !this.disabled && options2.zoomable) { var newWidth = naturalWidth * ratio; var newHeight = naturalHeight * ratio; if (dispatchEvent2(this.element, EVENT_ZOOM, { ratio, oldRatio: width / naturalWidth, originalEvent: _originalEvent }) === false) { return this; } if (_originalEvent) { var pointers = this.pointers; var offset2 = getOffset(this.cropper); var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { pageX: _originalEvent.pageX, pageY: _originalEvent.pageY }; canvasData.left -= (newWidth - width) * ((center.pageX - offset2.left - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((center.pageY - offset2.top - canvasData.top) / height); } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) { canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height); } else { canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; } canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }, /** * Rotate the canvas with a relative degree * @param {number} degree - The rotate degree. * @returns {Cropper} this */ rotate: function rotate(degree) { return this.rotateTo((this.imageData.rotate || 0) + Number(degree)); }, /** * Rotate the canvas to an absolute degree * @param {number} degree - The rotate degree. * @returns {Cropper} this */ rotateTo: function rotateTo(degree) { degree = Number(degree); if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) { this.imageData.rotate = degree % 360; this.renderCanvas(true, true); } return this; }, /** * Scale the image on the x-axis. * @param {number} scaleX - The scale ratio on the x-axis. * @returns {Cropper} this */ scaleX: function scaleX(_scaleX) { var scaleY = this.imageData.scaleY; return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1); }, /** * Scale the image on the y-axis. * @param {number} scaleY - The scale ratio on the y-axis. * @returns {Cropper} this */ scaleY: function scaleY(_scaleY) { var scaleX = this.imageData.scaleX; return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY); }, /** * Scale the image * @param {number} scaleX - The scale ratio on the x-axis. * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis. * @returns {Cropper} this */ scale: function scale(scaleX) { var scaleY = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : scaleX; var imageData = this.imageData; var transformed = false; scaleX = Number(scaleX); scaleY = Number(scaleY); if (this.ready && !this.disabled && this.options.scalable) { if (isNumber(scaleX)) { imageData.scaleX = scaleX; transformed = true; } if (isNumber(scaleY)) { imageData.scaleY = scaleY; transformed = true; } if (transformed) { this.renderCanvas(true, true); } } return this; }, /** * Get the cropped area position and size data (base on the original image) * @param {boolean} [rounded=false] - Indicate if round the data values or not. * @returns {Object} The result cropped data. */ getData: function getData2() { var rounded = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; var options2 = this.options, imageData = this.imageData, canvasData = this.canvasData, cropBoxData = this.cropBoxData; var data; if (this.ready && this.cropped) { data = { x: cropBoxData.left - canvasData.left, y: cropBoxData.top - canvasData.top, width: cropBoxData.width, height: cropBoxData.height }; var ratio = imageData.width / imageData.naturalWidth; forEach(data, function(n3, i4) { data[i4] = n3 / ratio; }); if (rounded) { var bottom2 = Math.round(data.y + data.height); var right2 = Math.round(data.x + data.width); data.x = Math.round(data.x); data.y = Math.round(data.y); data.width = right2 - data.x; data.height = bottom2 - data.y; } } else { data = { x: 0, y: 0, width: 0, height: 0 }; } if (options2.rotatable) { data.rotate = imageData.rotate || 0; } if (options2.scalable) { data.scaleX = imageData.scaleX || 1; data.scaleY = imageData.scaleY || 1; } return data; }, /** * Set the cropped area position and size with new data * @param {Object} data - The new data. * @returns {Cropper} this */ setData: function setData2(data) { var options2 = this.options, imageData = this.imageData, canvasData = this.canvasData; var cropBoxData = {}; if (this.ready && !this.disabled && isPlainObject(data)) { var transformed = false; if (options2.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; transformed = true; } } if (options2.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; transformed = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; transformed = true; } } if (transformed) { this.renderCanvas(true, true); } var ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }, /** * Get the container size data. * @returns {Object} The result container data. */ getContainerData: function getContainerData() { return this.ready ? assign2({}, this.containerData) : {}; }, /** * Get the image position and size data. * @returns {Object} The result image data. */ getImageData: function getImageData() { return this.sized ? assign2({}, this.imageData) : {}; }, /** * Get the canvas position and size data. * @returns {Object} The result canvas data. */ getCanvasData: function getCanvasData() { var canvasData = this.canvasData; var data = {}; if (this.ready) { forEach(["left", "top", "width", "height", "naturalWidth", "naturalHeight"], function(n3) { data[n3] = canvasData[n3]; }); } return data; }, /** * Set the canvas position and size with new data. * @param {Object} data - The new canvas data. * @returns {Cropper} this */ setCanvasData: function setCanvasData(data) { var canvasData = this.canvasData; var aspectRatio = canvasData.aspectRatio; if (this.ready && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { canvasData.left = data.left; } if (isNumber(data.top)) { canvasData.top = data.top; } if (isNumber(data.width)) { canvasData.width = data.width; canvasData.height = data.width / aspectRatio; } else if (isNumber(data.height)) { canvasData.height = data.height; canvasData.width = data.height * aspectRatio; } this.renderCanvas(true); } return this; }, /** * Get the crop box position and size data. * @returns {Object} The result crop box data. */ getCropBoxData: function getCropBoxData() { var cropBoxData = this.cropBoxData; var data; if (this.ready && this.cropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }, /** * Set the crop box position and size with new data. * @param {Object} data - The new crop box data. * @returns {Cropper} this */ setCropBoxData: function setCropBoxData(data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var widthChanged; var heightChanged; if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { widthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { heightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (widthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (heightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }, /** * Get a canvas drawn the cropped image. * @param {Object} [options={}] - The config options. * @returns {HTMLCanvasElement} - The result canvas. */ getCroppedCanvas: function getCroppedCanvas() { var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; if (!this.ready || !window.HTMLCanvasElement) { return null; } var canvasData = this.canvasData; var source = getSourceCanvas(this.image, this.imageData, canvasData, options2); if (!this.cropped) { return source; } var _this$getData = this.getData(options2.rounded), initialX = _this$getData.x, initialY = _this$getData.y, initialWidth = _this$getData.width, initialHeight = _this$getData.height; var ratio = source.width / Math.floor(canvasData.naturalWidth); if (ratio !== 1) { initialX *= ratio; initialY *= ratio; initialWidth *= ratio; initialHeight *= ratio; } var aspectRatio = initialWidth / initialHeight; var maxSizes = getAdjustedSizes({ aspectRatio, width: options2.maxWidth || Infinity, height: options2.maxHeight || Infinity }); var minSizes = getAdjustedSizes({ aspectRatio, width: options2.minWidth || 0, height: options2.minHeight || 0 }, "cover"); var _getAdjustedSizes = getAdjustedSizes({ aspectRatio, width: options2.width || (ratio !== 1 ? source.width : initialWidth), height: options2.height || (ratio !== 1 ? source.height : initialHeight) }), width = _getAdjustedSizes.width, height = _getAdjustedSizes.height; width = Math.min(maxSizes.width, Math.max(minSizes.width, width)); height = Math.min(maxSizes.height, Math.max(minSizes.height, height)); var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); canvas.width = normalizeDecimalNumber(width); canvas.height = normalizeDecimalNumber(height); context.fillStyle = options2.fillColor || "transparent"; context.fillRect(0, 0, width, height); var _options$imageSmoothi = options2.imageSmoothingEnabled, imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi, imageSmoothingQuality = options2.imageSmoothingQuality; context.imageSmoothingEnabled = imageSmoothingEnabled; if (imageSmoothingQuality) { context.imageSmoothingQuality = imageSmoothingQuality; } var sourceWidth = source.width; var sourceHeight = source.height; var srcX = initialX; var srcY = initialY; var srcWidth; var srcHeight; var dstX; var dstY; var dstWidth; var dstHeight; if (srcX <= -initialWidth || srcX > sourceWidth) { srcX = 0; srcWidth = 0; dstX = 0; dstWidth = 0; } else if (srcX <= 0) { dstX = -srcX; srcX = 0; srcWidth = Math.min(sourceWidth, initialWidth + srcX); dstWidth = srcWidth; } else if (srcX <= sourceWidth) { dstX = 0; srcWidth = Math.min(initialWidth, sourceWidth - srcX); dstWidth = srcWidth; } if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) { srcY = 0; srcHeight = 0; dstY = 0; dstHeight = 0; } else if (srcY <= 0) { dstY = -srcY; srcY = 0; srcHeight = Math.min(sourceHeight, initialHeight + srcY); dstHeight = srcHeight; } else if (srcY <= sourceHeight) { dstY = 0; srcHeight = Math.min(initialHeight, sourceHeight - srcY); dstHeight = srcHeight; } var params = [srcX, srcY, srcWidth, srcHeight]; if (dstWidth > 0 && dstHeight > 0) { var scale = width / initialWidth; params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale); } context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function(param) { return Math.floor(normalizeDecimalNumber(param)); })))); return canvas; }, /** * Change the aspect ratio of the crop box. * @param {number} aspectRatio - The new aspect ratio. * @returns {Cropper} this */ setAspectRatio: function setAspectRatio(aspectRatio) { var options2 = this.options; if (!this.disabled && !isUndefined(aspectRatio)) { options2.aspectRatio = Math.max(0, aspectRatio) || NaN; if (this.ready) { this.initCropBox(); if (this.cropped) { this.renderCropBox(); } } } return this; }, /** * Change the drag mode. * @param {string} mode - The new drag mode. * @returns {Cropper} this */ setDragMode: function setDragMode(mode) { var options2 = this.options, dragBox = this.dragBox, face = this.face; if (this.ready && !this.disabled) { var croppable = mode === DRAG_MODE_CROP; var movable = options2.movable && mode === DRAG_MODE_MOVE; mode = croppable || movable ? mode : DRAG_MODE_NONE; options2.dragMode = mode; setData(dragBox, DATA_ACTION, mode); toggleClass(dragBox, CLASS_CROP, croppable); toggleClass(dragBox, CLASS_MOVE, movable); if (!options2.cropBoxMovable) { setData(face, DATA_ACTION, mode); toggleClass(face, CLASS_CROP, croppable); toggleClass(face, CLASS_MOVE, movable); } } return this; } }; var AnotherCropper = WINDOW.Cropper; var Cropper2 = /* @__PURE__ */ function() { function Cropper3(element) { var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; _classCallCheck(this, Cropper3); if (!element || !REGEXP_TAG_NAME.test(element.tagName)) { throw new Error("The first argument is required and must be an or element."); } this.element = element; this.options = assign2({}, DEFAULTS, isPlainObject(options2) && options2); this.cropped = false; this.disabled = false; this.pointers = {}; this.ready = false; this.reloading = false; this.replaced = false; this.sized = false; this.sizing = false; this.init(); } return _createClass(Cropper3, [{ key: "init", value: function init() { var element = this.element; var tagName = element.tagName.toLowerCase(); var url; if (element[NAMESPACE]) { return; } element[NAMESPACE] = this; if (tagName === "img") { this.isImg = true; url = element.getAttribute("src") || ""; this.originalUrl = url; if (!url) { return; } url = element.src; } else if (tagName === "canvas" && window.HTMLCanvasElement) { url = element.toDataURL(); } this.load(url); } }, { key: "load", value: function load(url) { var _this = this; if (!url) { return; } this.url = url; this.imageData = {}; var element = this.element, options2 = this.options; if (!options2.rotatable && !options2.scalable) { options2.checkOrientation = false; } if (!options2.checkOrientation || !window.ArrayBuffer) { this.clone(); return; } if (REGEXP_DATA_URL.test(url)) { if (REGEXP_DATA_URL_JPEG.test(url)) { this.read(dataURLToArrayBuffer(url)); } else { this.clone(); } return; } var xhr = new XMLHttpRequest(); var clone2 = this.clone.bind(this); this.reloading = true; this.xhr = xhr; xhr.onabort = clone2; xhr.onerror = clone2; xhr.ontimeout = clone2; xhr.onprogress = function() { if (xhr.getResponseHeader("content-type") !== MIME_TYPE_JPEG) { xhr.abort(); } }; xhr.onload = function() { _this.read(xhr.response); }; xhr.onloadend = function() { _this.reloading = false; _this.xhr = null; }; if (options2.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) { url = addTimestamp(url); } xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.withCredentials = element.crossOrigin === "use-credentials"; xhr.send(); } }, { key: "read", value: function read2(arrayBuffer) { var options2 = this.options, imageData = this.imageData; var orientation = resetAndGetOrientation(arrayBuffer); var rotate = 0; var scaleX = 1; var scaleY = 1; if (orientation > 1) { this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG); var _parseOrientation = parseOrientation(orientation); rotate = _parseOrientation.rotate; scaleX = _parseOrientation.scaleX; scaleY = _parseOrientation.scaleY; } if (options2.rotatable) { imageData.rotate = rotate; } if (options2.scalable) { imageData.scaleX = scaleX; imageData.scaleY = scaleY; } this.clone(); } }, { key: "clone", value: function clone2() { var element = this.element, url = this.url; var crossOrigin = element.crossOrigin; var crossOriginUrl = url; if (this.options.checkCrossOrigin && isCrossOriginURL(url)) { if (!crossOrigin) { crossOrigin = "anonymous"; } crossOriginUrl = addTimestamp(url); } this.crossOrigin = crossOrigin; this.crossOriginUrl = crossOriginUrl; var image = document.createElement("img"); if (crossOrigin) { image.crossOrigin = crossOrigin; } image.src = crossOriginUrl || url; image.alt = element.alt || "The image to crop"; this.image = image; image.onload = this.start.bind(this); image.onerror = this.stop.bind(this); addClass(image, CLASS_HIDE); element.parentNode.insertBefore(image, element.nextSibling); } }, { key: "start", value: function start3() { var _this2 = this; var image = this.image; image.onload = null; image.onerror = null; this.sizing = true; var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent); var done = function done2(naturalWidth, naturalHeight) { assign2(_this2.imageData, { naturalWidth, naturalHeight, aspectRatio: naturalWidth / naturalHeight }); _this2.initialImageData = assign2({}, _this2.imageData); _this2.sizing = false; _this2.sized = true; _this2.build(); }; if (image.naturalWidth && !isIOSWebKit) { done(image.naturalWidth, image.naturalHeight); return; } var sizingImage = document.createElement("img"); var body = document.body || document.documentElement; this.sizingImage = sizingImage; sizingImage.onload = function() { done(sizingImage.width, sizingImage.height); if (!isIOSWebKit) { body.removeChild(sizingImage); } }; sizingImage.src = image.src; if (!isIOSWebKit) { sizingImage.style.cssText = "left:0;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;opacity:0;position:absolute;top:0;z-index:-1;"; body.appendChild(sizingImage); } } }, { key: "stop", value: function stop() { var image = this.image; image.onload = null; image.onerror = null; image.parentNode.removeChild(image); this.image = null; } }, { key: "build", value: function build() { if (!this.sized || this.ready) { return; } var element = this.element, options2 = this.options, image = this.image; var container = element.parentNode; var template = document.createElement("div"); template.innerHTML = TEMPLATE; var cropper = template.querySelector(".".concat(NAMESPACE, "-container")); var canvas = cropper.querySelector(".".concat(NAMESPACE, "-canvas")); var dragBox = cropper.querySelector(".".concat(NAMESPACE, "-drag-box")); var cropBox = cropper.querySelector(".".concat(NAMESPACE, "-crop-box")); var face = cropBox.querySelector(".".concat(NAMESPACE, "-face")); this.container = container; this.cropper = cropper; this.canvas = canvas; this.dragBox = dragBox; this.cropBox = cropBox; this.viewBox = cropper.querySelector(".".concat(NAMESPACE, "-view-box")); this.face = face; canvas.appendChild(image); addClass(element, CLASS_HIDDEN); container.insertBefore(cropper, element.nextSibling); removeClass(image, CLASS_HIDE); this.initPreview(); this.bind(); options2.initialAspectRatio = Math.max(0, options2.initialAspectRatio) || NaN; options2.aspectRatio = Math.max(0, options2.aspectRatio) || NaN; options2.viewMode = Math.max(0, Math.min(3, Math.round(options2.viewMode))) || 0; addClass(cropBox, CLASS_HIDDEN); if (!options2.guides) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-dashed")), CLASS_HIDDEN); } if (!options2.center) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-center")), CLASS_HIDDEN); } if (options2.background) { addClass(cropper, "".concat(NAMESPACE, "-bg")); } if (!options2.highlight) { addClass(face, CLASS_INVISIBLE); } if (options2.cropBoxMovable) { addClass(face, CLASS_MOVE); setData(face, DATA_ACTION, ACTION_ALL); } if (!options2.cropBoxResizable) { addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-line")), CLASS_HIDDEN); addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-point")), CLASS_HIDDEN); } this.render(); this.ready = true; this.setDragMode(options2.dragMode); if (options2.autoCrop) { this.crop(); } this.setData(options2.data); if (isFunction(options2.ready)) { addListener(element, EVENT_READY, options2.ready, { once: true }); } dispatchEvent2(element, EVENT_READY); } }, { key: "unbuild", value: function unbuild() { if (!this.ready) { return; } this.ready = false; this.unbind(); this.resetPreview(); var parentNode = this.cropper.parentNode; if (parentNode) { parentNode.removeChild(this.cropper); } removeClass(this.element, CLASS_HIDDEN); } }, { key: "uncreate", value: function uncreate() { if (this.ready) { this.unbuild(); this.ready = false; this.cropped = false; } else if (this.sizing) { this.sizingImage.onload = null; this.sizing = false; this.sized = false; } else if (this.reloading) { this.xhr.onabort = null; this.xhr.abort(); } else if (this.image) { this.stop(); } } /** * Get the no conflict cropper class. * @returns {Cropper} The cropper class. */ }], [{ key: "noConflict", value: function noConflict() { window.Cropper = AnotherCropper; return Cropper3; } /** * Change the default options. * @param {Object} options - The new default options. */ }, { key: "setDefaults", value: function setDefaults(options2) { assign2(DEFAULTS, isPlainObject(options2) && options2); } }]); }(); assign2(Cropper2.prototype, render, preview, events, handlers, change, methods); return Cropper2; }); } }); // node_modules/@hotwired/stimulus/dist/stimulus.js var EventListener = class { constructor(eventTarget, eventName, eventOptions) { this.eventTarget = eventTarget; this.eventName = eventName; this.eventOptions = eventOptions; this.unorderedBindings = /* @__PURE__ */ new Set(); } connect() { this.eventTarget.addEventListener(this.eventName, this, this.eventOptions); } disconnect() { this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions); } bindingConnected(binding) { this.unorderedBindings.add(binding); } bindingDisconnected(binding) { this.unorderedBindings.delete(binding); } handleEvent(event) { const extendedEvent = extendEvent(event); for (const binding of this.bindings) { if (extendedEvent.immediatePropagationStopped) { break; } else { binding.handleEvent(extendedEvent); } } } hasBindings() { return this.unorderedBindings.size > 0; } get bindings() { return Array.from(this.unorderedBindings).sort((left2, right2) => { const leftIndex = left2.index, rightIndex = right2.index; return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0; }); } }; function extendEvent(event) { if ("immediatePropagationStopped" in event) { return event; } else { const { stopImmediatePropagation } = event; return Object.assign(event, { immediatePropagationStopped: false, stopImmediatePropagation() { this.immediatePropagationStopped = true; stopImmediatePropagation.call(this); } }); } } var Dispatcher = class { constructor(application2) { this.application = application2; this.eventListenerMaps = /* @__PURE__ */ new Map(); this.started = false; } start() { if (!this.started) { this.started = true; this.eventListeners.forEach((eventListener) => eventListener.connect()); } } stop() { if (this.started) { this.started = false; this.eventListeners.forEach((eventListener) => eventListener.disconnect()); } } get eventListeners() { return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []); } bindingConnected(binding) { this.fetchEventListenerForBinding(binding).bindingConnected(binding); } bindingDisconnected(binding, clearEventListeners = false) { this.fetchEventListenerForBinding(binding).bindingDisconnected(binding); if (clearEventListeners) this.clearEventListenersForBinding(binding); } handleError(error2, message, detail = {}) { this.application.handleError(error2, `Error ${message}`, detail); } clearEventListenersForBinding(binding) { const eventListener = this.fetchEventListenerForBinding(binding); if (!eventListener.hasBindings()) { eventListener.disconnect(); this.removeMappedEventListenerFor(binding); } } removeMappedEventListenerFor(binding) { const { eventTarget, eventName, eventOptions } = binding; const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget); const cacheKey = this.cacheKey(eventName, eventOptions); eventListenerMap.delete(cacheKey); if (eventListenerMap.size == 0) this.eventListenerMaps.delete(eventTarget); } fetchEventListenerForBinding(binding) { const { eventTarget, eventName, eventOptions } = binding; return this.fetchEventListener(eventTarget, eventName, eventOptions); } fetchEventListener(eventTarget, eventName, eventOptions) { const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget); const cacheKey = this.cacheKey(eventName, eventOptions); let eventListener = eventListenerMap.get(cacheKey); if (!eventListener) { eventListener = this.createEventListener(eventTarget, eventName, eventOptions); eventListenerMap.set(cacheKey, eventListener); } return eventListener; } createEventListener(eventTarget, eventName, eventOptions) { const eventListener = new EventListener(eventTarget, eventName, eventOptions); if (this.started) { eventListener.connect(); } return eventListener; } fetchEventListenerMapForEventTarget(eventTarget) { let eventListenerMap = this.eventListenerMaps.get(eventTarget); if (!eventListenerMap) { eventListenerMap = /* @__PURE__ */ new Map(); this.eventListenerMaps.set(eventTarget, eventListenerMap); } return eventListenerMap; } cacheKey(eventName, eventOptions) { const parts = [eventName]; Object.keys(eventOptions).sort().forEach((key) => { parts.push(`${eventOptions[key] ? "" : "!"}${key}`); }); return parts.join(":"); } }; var defaultActionDescriptorFilters = { stop({ event, value }) { if (value) event.stopPropagation(); return true; }, prevent({ event, value }) { if (value) event.preventDefault(); return true; }, self({ event, value, element }) { if (value) { return element === event.target; } else { return true; } } }; var descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/; function parseActionDescriptorString(descriptorString) { const source = descriptorString.trim(); const matches = source.match(descriptorPattern) || []; let eventName = matches[2]; let keyFilter = matches[3]; if (keyFilter && !["keydown", "keyup", "keypress"].includes(eventName)) { eventName += `.${keyFilter}`; keyFilter = ""; } return { eventTarget: parseEventTarget(matches[4]), eventName, eventOptions: matches[7] ? parseEventOptions(matches[7]) : {}, identifier: matches[5], methodName: matches[6], keyFilter: matches[1] || keyFilter }; } function parseEventTarget(eventTargetName) { if (eventTargetName == "window") { return window; } else if (eventTargetName == "document") { return document; } } function parseEventOptions(eventOptions) { return eventOptions.split(":").reduce((options2, token) => Object.assign(options2, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {}); } function stringifyEventTarget(eventTarget) { if (eventTarget == window) { return "window"; } else if (eventTarget == document) { return "document"; } } function camelize(value) { return value.replace(/(?:[_-])([a-z0-9])/g, (_3, char) => char.toUpperCase()); } function namespaceCamelize(value) { return camelize(value.replace(/--/g, "-").replace(/__/g, "_")); } function capitalize(value) { return value.charAt(0).toUpperCase() + value.slice(1); } function dasherize(value) { return value.replace(/([A-Z])/g, (_3, char) => `-${char.toLowerCase()}`); } function tokenize(value) { return value.match(/[^\s]+/g) || []; } function isSomething(object) { return object !== null && object !== void 0; } function hasProperty(object, property) { return Object.prototype.hasOwnProperty.call(object, property); } var allModifiers = ["meta", "ctrl", "alt", "shift"]; var Action = class { constructor(element, index, descriptor, schema) { this.element = element; this.index = index; this.eventTarget = descriptor.eventTarget || element; this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name"); this.eventOptions = descriptor.eventOptions || {}; this.identifier = descriptor.identifier || error("missing identifier"); this.methodName = descriptor.methodName || error("missing method name"); this.keyFilter = descriptor.keyFilter || ""; this.schema = schema; } static forToken(token, schema) { return new this(token.element, token.index, parseActionDescriptorString(token.content), schema); } toString() { const eventFilter = this.keyFilter ? `.${this.keyFilter}` : ""; const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : ""; return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`; } shouldIgnoreKeyboardEvent(event) { if (!this.keyFilter) { return false; } const filters = this.keyFilter.split("+"); if (this.keyFilterDissatisfied(event, filters)) { return true; } const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0]; if (!standardFilter) { return false; } if (!hasProperty(this.keyMappings, standardFilter)) { error(`contains unknown key filter: ${this.keyFilter}`); } return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase(); } shouldIgnoreMouseEvent(event) { if (!this.keyFilter) { return false; } const filters = [this.keyFilter]; if (this.keyFilterDissatisfied(event, filters)) { return true; } return false; } get params() { const params = {}; const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, "i"); for (const { name, value } of Array.from(this.element.attributes)) { const match2 = name.match(pattern); const key = match2 && match2[1]; if (key) { params[camelize(key)] = typecast(value); } } return params; } get eventTargetName() { return stringifyEventTarget(this.eventTarget); } get keyMappings() { return this.schema.keyMappings; } keyFilterDissatisfied(event, filters) { const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier)); return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift; } }; var defaultEventNames = { a: () => "click", button: () => "click", form: () => "submit", details: () => "toggle", input: (e4) => e4.getAttribute("type") == "submit" ? "click" : "input", select: () => "change", textarea: () => "input" }; function getDefaultEventNameForElement(element) { const tagName = element.tagName.toLowerCase(); if (tagName in defaultEventNames) { return defaultEventNames[tagName](element); } } function error(message) { throw new Error(message); } function typecast(value) { try { return JSON.parse(value); } catch (o_O) { return value; } } var Binding = class { constructor(context, action) { this.context = context; this.action = action; } get index() { return this.action.index; } get eventTarget() { return this.action.eventTarget; } get eventOptions() { return this.action.eventOptions; } get identifier() { return this.context.identifier; } handleEvent(event) { const actionEvent = this.prepareActionEvent(event); if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) { this.invokeWithEvent(actionEvent); } } get eventName() { return this.action.eventName; } get method() { const method = this.controller[this.methodName]; if (typeof method == "function") { return method; } throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`); } applyEventModifiers(event) { const { element } = this.action; const { actionDescriptorFilters } = this.context.application; const { controller } = this.context; let passes = true; for (const [name, value] of Object.entries(this.eventOptions)) { if (name in actionDescriptorFilters) { const filter = actionDescriptorFilters[name]; passes = passes && filter({ name, value, event, element, controller }); } else { continue; } } return passes; } prepareActionEvent(event) { return Object.assign(event, { params: this.action.params }); } invokeWithEvent(event) { const { target, currentTarget } = event; try { this.method.call(this.controller, event); this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName }); } catch (error2) { const { identifier, controller, element, index } = this; const detail = { identifier, controller, element, index, event }; this.context.handleError(error2, `invoking action "${this.action}"`, detail); } } willBeInvokedByEvent(event) { const eventTarget = event.target; if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) { return false; } if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) { return false; } if (this.element === eventTarget) { return true; } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) { return this.scope.containsElement(eventTarget); } else { return this.scope.containsElement(this.action.element); } } get controller() { return this.context.controller; } get methodName() { return this.action.methodName; } get element() { return this.scope.element; } get scope() { return this.context.scope; } }; var ElementObserver = class { constructor(element, delegate) { this.mutationObserverInit = { attributes: true, childList: true, subtree: true }; this.element = element; this.started = false; this.delegate = delegate; this.elements = /* @__PURE__ */ new Set(); this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations)); } start() { if (!this.started) { this.started = true; this.mutationObserver.observe(this.element, this.mutationObserverInit); this.refresh(); } } pause(callback) { if (this.started) { this.mutationObserver.disconnect(); this.started = false; } callback(); if (!this.started) { this.mutationObserver.observe(this.element, this.mutationObserverInit); this.started = true; } } stop() { if (this.started) { this.mutationObserver.takeRecords(); this.mutationObserver.disconnect(); this.started = false; } } refresh() { if (this.started) { const matches = new Set(this.matchElementsInTree()); for (const element of Array.from(this.elements)) { if (!matches.has(element)) { this.removeElement(element); } } for (const element of Array.from(matches)) { this.addElement(element); } } } processMutations(mutations) { if (this.started) { for (const mutation of mutations) { this.processMutation(mutation); } } } processMutation(mutation) { if (mutation.type == "attributes") { this.processAttributeChange(mutation.target, mutation.attributeName); } else if (mutation.type == "childList") { this.processRemovedNodes(mutation.removedNodes); this.processAddedNodes(mutation.addedNodes); } } processAttributeChange(element, attributeName) { if (this.elements.has(element)) { if (this.delegate.elementAttributeChanged && this.matchElement(element)) { this.delegate.elementAttributeChanged(element, attributeName); } else { this.removeElement(element); } } else if (this.matchElement(element)) { this.addElement(element); } } processRemovedNodes(nodes) { for (const node of Array.from(nodes)) { const element = this.elementFromNode(node); if (element) { this.processTree(element, this.removeElement); } } } processAddedNodes(nodes) { for (const node of Array.from(nodes)) { const element = this.elementFromNode(node); if (element && this.elementIsActive(element)) { this.processTree(element, this.addElement); } } } matchElement(element) { return this.delegate.matchElement(element); } matchElementsInTree(tree = this.element) { return this.delegate.matchElementsInTree(tree); } processTree(tree, processor) { for (const element of this.matchElementsInTree(tree)) { processor.call(this, element); } } elementFromNode(node) { if (node.nodeType == Node.ELEMENT_NODE) { return node; } } elementIsActive(element) { if (element.isConnected != this.element.isConnected) { return false; } else { return this.element.contains(element); } } addElement(element) { if (!this.elements.has(element)) { if (this.elementIsActive(element)) { this.elements.add(element); if (this.delegate.elementMatched) { this.delegate.elementMatched(element); } } } } removeElement(element) { if (this.elements.has(element)) { this.elements.delete(element); if (this.delegate.elementUnmatched) { this.delegate.elementUnmatched(element); } } } }; var AttributeObserver = class { constructor(element, attributeName, delegate) { this.attributeName = attributeName; this.delegate = delegate; this.elementObserver = new ElementObserver(element, this); } get element() { return this.elementObserver.element; } get selector() { return `[${this.attributeName}]`; } start() { this.elementObserver.start(); } pause(callback) { this.elementObserver.pause(callback); } stop() { this.elementObserver.stop(); } refresh() { this.elementObserver.refresh(); } get started() { return this.elementObserver.started; } matchElement(element) { return element.hasAttribute(this.attributeName); } matchElementsInTree(tree) { const match2 = this.matchElement(tree) ? [tree] : []; const matches = Array.from(tree.querySelectorAll(this.selector)); return match2.concat(matches); } elementMatched(element) { if (this.delegate.elementMatchedAttribute) { this.delegate.elementMatchedAttribute(element, this.attributeName); } } elementUnmatched(element) { if (this.delegate.elementUnmatchedAttribute) { this.delegate.elementUnmatchedAttribute(element, this.attributeName); } } elementAttributeChanged(element, attributeName) { if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) { this.delegate.elementAttributeValueChanged(element, attributeName); } } }; function add(map, key, value) { fetch2(map, key).add(value); } function del(map, key, value) { fetch2(map, key).delete(value); prune(map, key); } function fetch2(map, key) { let values = map.get(key); if (!values) { values = /* @__PURE__ */ new Set(); map.set(key, values); } return values; } function prune(map, key) { const values = map.get(key); if (values != null && values.size == 0) { map.delete(key); } } var Multimap = class { constructor() { this.valuesByKey = /* @__PURE__ */ new Map(); } get keys() { return Array.from(this.valuesByKey.keys()); } get values() { const sets = Array.from(this.valuesByKey.values()); return sets.reduce((values, set) => values.concat(Array.from(set)), []); } get size() { const sets = Array.from(this.valuesByKey.values()); return sets.reduce((size, set) => size + set.size, 0); } add(key, value) { add(this.valuesByKey, key, value); } delete(key, value) { del(this.valuesByKey, key, value); } has(key, value) { const values = this.valuesByKey.get(key); return values != null && values.has(value); } hasKey(key) { return this.valuesByKey.has(key); } hasValue(value) { const sets = Array.from(this.valuesByKey.values()); return sets.some((set) => set.has(value)); } getValuesForKey(key) { const values = this.valuesByKey.get(key); return values ? Array.from(values) : []; } getKeysForValue(value) { return Array.from(this.valuesByKey).filter(([_key, values]) => values.has(value)).map(([key, _values]) => key); } }; var SelectorObserver = class { constructor(element, selector, delegate, details) { this._selector = selector; this.details = details; this.elementObserver = new ElementObserver(element, this); this.delegate = delegate; this.matchesByElement = new Multimap(); } get started() { return this.elementObserver.started; } get selector() { return this._selector; } set selector(selector) { this._selector = selector; this.refresh(); } start() { this.elementObserver.start(); } pause(callback) { this.elementObserver.pause(callback); } stop() { this.elementObserver.stop(); } refresh() { this.elementObserver.refresh(); } get element() { return this.elementObserver.element; } matchElement(element) { const { selector } = this; if (selector) { const matches = element.matches(selector); if (this.delegate.selectorMatchElement) { return matches && this.delegate.selectorMatchElement(element, this.details); } return matches; } else { return false; } } matchElementsInTree(tree) { const { selector } = this; if (selector) { const match2 = this.matchElement(tree) ? [tree] : []; const matches = Array.from(tree.querySelectorAll(selector)).filter((match3) => this.matchElement(match3)); return match2.concat(matches); } else { return []; } } elementMatched(element) { const { selector } = this; if (selector) { this.selectorMatched(element, selector); } } elementUnmatched(element) { const selectors = this.matchesByElement.getKeysForValue(element); for (const selector of selectors) { this.selectorUnmatched(element, selector); } } elementAttributeChanged(element, _attributeName) { const { selector } = this; if (selector) { const matches = this.matchElement(element); const matchedBefore = this.matchesByElement.has(selector, element); if (matches && !matchedBefore) { this.selectorMatched(element, selector); } else if (!matches && matchedBefore) { this.selectorUnmatched(element, selector); } } } selectorMatched(element, selector) { this.delegate.selectorMatched(element, selector, this.details); this.matchesByElement.add(selector, element); } selectorUnmatched(element, selector) { this.delegate.selectorUnmatched(element, selector, this.details); this.matchesByElement.delete(selector, element); } }; var StringMapObserver = class { constructor(element, delegate) { this.element = element; this.delegate = delegate; this.started = false; this.stringMap = /* @__PURE__ */ new Map(); this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations)); } start() { if (!this.started) { this.started = true; this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true }); this.refresh(); } } stop() { if (this.started) { this.mutationObserver.takeRecords(); this.mutationObserver.disconnect(); this.started = false; } } refresh() { if (this.started) { for (const attributeName of this.knownAttributeNames) { this.refreshAttribute(attributeName, null); } } } processMutations(mutations) { if (this.started) { for (const mutation of mutations) { this.processMutation(mutation); } } } processMutation(mutation) { const attributeName = mutation.attributeName; if (attributeName) { this.refreshAttribute(attributeName, mutation.oldValue); } } refreshAttribute(attributeName, oldValue) { const key = this.delegate.getStringMapKeyForAttribute(attributeName); if (key != null) { if (!this.stringMap.has(attributeName)) { this.stringMapKeyAdded(key, attributeName); } const value = this.element.getAttribute(attributeName); if (this.stringMap.get(attributeName) != value) { this.stringMapValueChanged(value, key, oldValue); } if (value == null) { const oldValue2 = this.stringMap.get(attributeName); this.stringMap.delete(attributeName); if (oldValue2) this.stringMapKeyRemoved(key, attributeName, oldValue2); } else { this.stringMap.set(attributeName, value); } } } stringMapKeyAdded(key, attributeName) { if (this.delegate.stringMapKeyAdded) { this.delegate.stringMapKeyAdded(key, attributeName); } } stringMapValueChanged(value, key, oldValue) { if (this.delegate.stringMapValueChanged) { this.delegate.stringMapValueChanged(value, key, oldValue); } } stringMapKeyRemoved(key, attributeName, oldValue) { if (this.delegate.stringMapKeyRemoved) { this.delegate.stringMapKeyRemoved(key, attributeName, oldValue); } } get knownAttributeNames() { return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames))); } get currentAttributeNames() { return Array.from(this.element.attributes).map((attribute) => attribute.name); } get recordedAttributeNames() { return Array.from(this.stringMap.keys()); } }; var TokenListObserver = class { constructor(element, attributeName, delegate) { this.attributeObserver = new AttributeObserver(element, attributeName, this); this.delegate = delegate; this.tokensByElement = new Multimap(); } get started() { return this.attributeObserver.started; } start() { this.attributeObserver.start(); } pause(callback) { this.attributeObserver.pause(callback); } stop() { this.attributeObserver.stop(); } refresh() { this.attributeObserver.refresh(); } get element() { return this.attributeObserver.element; } get attributeName() { return this.attributeObserver.attributeName; } elementMatchedAttribute(element) { this.tokensMatched(this.readTokensForElement(element)); } elementAttributeValueChanged(element) { const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element); this.tokensUnmatched(unmatchedTokens); this.tokensMatched(matchedTokens); } elementUnmatchedAttribute(element) { this.tokensUnmatched(this.tokensByElement.getValuesForKey(element)); } tokensMatched(tokens) { tokens.forEach((token) => this.tokenMatched(token)); } tokensUnmatched(tokens) { tokens.forEach((token) => this.tokenUnmatched(token)); } tokenMatched(token) { this.delegate.tokenMatched(token); this.tokensByElement.add(token.element, token); } tokenUnmatched(token) { this.delegate.tokenUnmatched(token); this.tokensByElement.delete(token.element, token); } refreshTokensForElement(element) { const previousTokens = this.tokensByElement.getValuesForKey(element); const currentTokens = this.readTokensForElement(element); const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken)); if (firstDifferingIndex == -1) { return [[], []]; } else { return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)]; } } readTokensForElement(element) { const attributeName = this.attributeName; const tokenString = element.getAttribute(attributeName) || ""; return parseTokenString(tokenString, element, attributeName); } }; function parseTokenString(tokenString, element, attributeName) { return tokenString.trim().split(/\s+/).filter((content) => content.length).map((content, index) => ({ element, attributeName, content, index })); } function zip(left2, right2) { const length = Math.max(left2.length, right2.length); return Array.from({ length }, (_3, index) => [left2[index], right2[index]]); } function tokensAreEqual(left2, right2) { return left2 && right2 && left2.index == right2.index && left2.content == right2.content; } var ValueListObserver = class { constructor(element, attributeName, delegate) { this.tokenListObserver = new TokenListObserver(element, attributeName, this); this.delegate = delegate; this.parseResultsByToken = /* @__PURE__ */ new WeakMap(); this.valuesByTokenByElement = /* @__PURE__ */ new WeakMap(); } get started() { return this.tokenListObserver.started; } start() { this.tokenListObserver.start(); } stop() { this.tokenListObserver.stop(); } refresh() { this.tokenListObserver.refresh(); } get element() { return this.tokenListObserver.element; } get attributeName() { return this.tokenListObserver.attributeName; } tokenMatched(token) { const { element } = token; const { value } = this.fetchParseResultForToken(token); if (value) { this.fetchValuesByTokenForElement(element).set(token, value); this.delegate.elementMatchedValue(element, value); } } tokenUnmatched(token) { const { element } = token; const { value } = this.fetchParseResultForToken(token); if (value) { this.fetchValuesByTokenForElement(element).delete(token); this.delegate.elementUnmatchedValue(element, value); } } fetchParseResultForToken(token) { let parseResult = this.parseResultsByToken.get(token); if (!parseResult) { parseResult = this.parseToken(token); this.parseResultsByToken.set(token, parseResult); } return parseResult; } fetchValuesByTokenForElement(element) { let valuesByToken = this.valuesByTokenByElement.get(element); if (!valuesByToken) { valuesByToken = /* @__PURE__ */ new Map(); this.valuesByTokenByElement.set(element, valuesByToken); } return valuesByToken; } parseToken(token) { try { const value = this.delegate.parseValueForToken(token); return { value }; } catch (error2) { return { error: error2 }; } } }; var BindingObserver = class { constructor(context, delegate) { this.context = context; this.delegate = delegate; this.bindingsByAction = /* @__PURE__ */ new Map(); } start() { if (!this.valueListObserver) { this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this); this.valueListObserver.start(); } } stop() { if (this.valueListObserver) { this.valueListObserver.stop(); delete this.valueListObserver; this.disconnectAllActions(); } } get element() { return this.context.element; } get identifier() { return this.context.identifier; } get actionAttribute() { return this.schema.actionAttribute; } get schema() { return this.context.schema; } get bindings() { return Array.from(this.bindingsByAction.values()); } connectAction(action) { const binding = new Binding(this.context, action); this.bindingsByAction.set(action, binding); this.delegate.bindingConnected(binding); } disconnectAction(action) { const binding = this.bindingsByAction.get(action); if (binding) { this.bindingsByAction.delete(action); this.delegate.bindingDisconnected(binding); } } disconnectAllActions() { this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true)); this.bindingsByAction.clear(); } parseValueForToken(token) { const action = Action.forToken(token, this.schema); if (action.identifier == this.identifier) { return action; } } elementMatchedValue(element, action) { this.connectAction(action); } elementUnmatchedValue(element, action) { this.disconnectAction(action); } }; var ValueObserver = class { constructor(context, receiver) { this.context = context; this.receiver = receiver; this.stringMapObserver = new StringMapObserver(this.element, this); this.valueDescriptorMap = this.controller.valueDescriptorMap; } start() { this.stringMapObserver.start(); this.invokeChangedCallbacksForDefaultValues(); } stop() { this.stringMapObserver.stop(); } get element() { return this.context.element; } get controller() { return this.context.controller; } getStringMapKeyForAttribute(attributeName) { if (attributeName in this.valueDescriptorMap) { return this.valueDescriptorMap[attributeName].name; } } stringMapKeyAdded(key, attributeName) { const descriptor = this.valueDescriptorMap[attributeName]; if (!this.hasValue(key)) { this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue)); } } stringMapValueChanged(value, name, oldValue) { const descriptor = this.valueDescriptorNameMap[name]; if (value === null) return; if (oldValue === null) { oldValue = descriptor.writer(descriptor.defaultValue); } this.invokeChangedCallback(name, value, oldValue); } stringMapKeyRemoved(key, attributeName, oldValue) { const descriptor = this.valueDescriptorNameMap[key]; if (this.hasValue(key)) { this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue); } else { this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue); } } invokeChangedCallbacksForDefaultValues() { for (const { key, name, defaultValue, writer } of this.valueDescriptors) { if (defaultValue != void 0 && !this.controller.data.has(key)) { this.invokeChangedCallback(name, writer(defaultValue), void 0); } } } invokeChangedCallback(name, rawValue, rawOldValue) { const changedMethodName = `${name}Changed`; const changedMethod = this.receiver[changedMethodName]; if (typeof changedMethod == "function") { const descriptor = this.valueDescriptorNameMap[name]; try { const value = descriptor.reader(rawValue); let oldValue = rawOldValue; if (rawOldValue) { oldValue = descriptor.reader(rawOldValue); } changedMethod.call(this.receiver, value, oldValue); } catch (error2) { if (error2 instanceof TypeError) { error2.message = `Stimulus Value "${this.context.identifier}.${descriptor.name}" - ${error2.message}`; } throw error2; } } } get valueDescriptors() { const { valueDescriptorMap } = this; return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]); } get valueDescriptorNameMap() { const descriptors = {}; Object.keys(this.valueDescriptorMap).forEach((key) => { const descriptor = this.valueDescriptorMap[key]; descriptors[descriptor.name] = descriptor; }); return descriptors; } hasValue(attributeName) { const descriptor = this.valueDescriptorNameMap[attributeName]; const hasMethodName = `has${capitalize(descriptor.name)}`; return this.receiver[hasMethodName]; } }; var TargetObserver = class { constructor(context, delegate) { this.context = context; this.delegate = delegate; this.targetsByName = new Multimap(); } start() { if (!this.tokenListObserver) { this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this); this.tokenListObserver.start(); } } stop() { if (this.tokenListObserver) { this.disconnectAllTargets(); this.tokenListObserver.stop(); delete this.tokenListObserver; } } tokenMatched({ element, content: name }) { if (this.scope.containsElement(element)) { this.connectTarget(element, name); } } tokenUnmatched({ element, content: name }) { this.disconnectTarget(element, name); } connectTarget(element, name) { var _a; if (!this.targetsByName.has(name, element)) { this.targetsByName.add(name, element); (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name)); } } disconnectTarget(element, name) { var _a; if (this.targetsByName.has(name, element)) { this.targetsByName.delete(name, element); (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name)); } } disconnectAllTargets() { for (const name of this.targetsByName.keys) { for (const element of this.targetsByName.getValuesForKey(name)) { this.disconnectTarget(element, name); } } } get attributeName() { return `data-${this.context.identifier}-target`; } get element() { return this.context.element; } get scope() { return this.context.scope; } }; function readInheritableStaticArrayValues(constructor, propertyName) { const ancestors = getAncestorsForConstructor(constructor); return Array.from(ancestors.reduce((values, constructor2) => { getOwnStaticArrayValues(constructor2, propertyName).forEach((name) => values.add(name)); return values; }, /* @__PURE__ */ new Set())); } function readInheritableStaticObjectPairs(constructor, propertyName) { const ancestors = getAncestorsForConstructor(constructor); return ancestors.reduce((pairs, constructor2) => { pairs.push(...getOwnStaticObjectPairs(constructor2, propertyName)); return pairs; }, []); } function getAncestorsForConstructor(constructor) { const ancestors = []; while (constructor) { ancestors.push(constructor); constructor = Object.getPrototypeOf(constructor); } return ancestors.reverse(); } function getOwnStaticArrayValues(constructor, propertyName) { const definition = constructor[propertyName]; return Array.isArray(definition) ? definition : []; } function getOwnStaticObjectPairs(constructor, propertyName) { const definition = constructor[propertyName]; return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : []; } var OutletObserver = class { constructor(context, delegate) { this.started = false; this.context = context; this.delegate = delegate; this.outletsByName = new Multimap(); this.outletElementsByName = new Multimap(); this.selectorObserverMap = /* @__PURE__ */ new Map(); this.attributeObserverMap = /* @__PURE__ */ new Map(); } start() { if (!this.started) { this.outletDefinitions.forEach((outletName) => { this.setupSelectorObserverForOutlet(outletName); this.setupAttributeObserverForOutlet(outletName); }); this.started = true; this.dependentContexts.forEach((context) => context.refresh()); } } refresh() { this.selectorObserverMap.forEach((observer) => observer.refresh()); this.attributeObserverMap.forEach((observer) => observer.refresh()); } stop() { if (this.started) { this.started = false; this.disconnectAllOutlets(); this.stopSelectorObservers(); this.stopAttributeObservers(); } } stopSelectorObservers() { if (this.selectorObserverMap.size > 0) { this.selectorObserverMap.forEach((observer) => observer.stop()); this.selectorObserverMap.clear(); } } stopAttributeObservers() { if (this.attributeObserverMap.size > 0) { this.attributeObserverMap.forEach((observer) => observer.stop()); this.attributeObserverMap.clear(); } } selectorMatched(element, _selector, { outletName }) { const outlet = this.getOutlet(element, outletName); if (outlet) { this.connectOutlet(outlet, element, outletName); } } selectorUnmatched(element, _selector, { outletName }) { const outlet = this.getOutletFromMap(element, outletName); if (outlet) { this.disconnectOutlet(outlet, element, outletName); } } selectorMatchElement(element, { outletName }) { const selector = this.selector(outletName); const hasOutlet = this.hasOutlet(element, outletName); const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`); if (selector) { return hasOutlet && hasOutletController && element.matches(selector); } else { return false; } } elementMatchedAttribute(_element, attributeName) { const outletName = this.getOutletNameFromOutletAttributeName(attributeName); if (outletName) { this.updateSelectorObserverForOutlet(outletName); } } elementAttributeValueChanged(_element, attributeName) { const outletName = this.getOutletNameFromOutletAttributeName(attributeName); if (outletName) { this.updateSelectorObserverForOutlet(outletName); } } elementUnmatchedAttribute(_element, attributeName) { const outletName = this.getOutletNameFromOutletAttributeName(attributeName); if (outletName) { this.updateSelectorObserverForOutlet(outletName); } } connectOutlet(outlet, element, outletName) { var _a; if (!this.outletElementsByName.has(outletName, element)) { this.outletsByName.add(outletName, outlet); this.outletElementsByName.add(outletName, element); (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName)); } } disconnectOutlet(outlet, element, outletName) { var _a; if (this.outletElementsByName.has(outletName, element)) { this.outletsByName.delete(outletName, outlet); this.outletElementsByName.delete(outletName, element); (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName)); } } disconnectAllOutlets() { for (const outletName of this.outletElementsByName.keys) { for (const element of this.outletElementsByName.getValuesForKey(outletName)) { for (const outlet of this.outletsByName.getValuesForKey(outletName)) { this.disconnectOutlet(outlet, element, outletName); } } } } updateSelectorObserverForOutlet(outletName) { const observer = this.selectorObserverMap.get(outletName); if (observer) { observer.selector = this.selector(outletName); } } setupSelectorObserverForOutlet(outletName) { const selector = this.selector(outletName); const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName }); this.selectorObserverMap.set(outletName, selectorObserver); selectorObserver.start(); } setupAttributeObserverForOutlet(outletName) { const attributeName = this.attributeNameForOutletName(outletName); const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this); this.attributeObserverMap.set(outletName, attributeObserver); attributeObserver.start(); } selector(outletName) { return this.scope.outlets.getSelectorForOutletName(outletName); } attributeNameForOutletName(outletName) { return this.scope.schema.outletAttributeForScope(this.identifier, outletName); } getOutletNameFromOutletAttributeName(attributeName) { return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName); } get outletDependencies() { const dependencies = new Multimap(); this.router.modules.forEach((module) => { const constructor = module.definition.controllerConstructor; const outlets = readInheritableStaticArrayValues(constructor, "outlets"); outlets.forEach((outlet) => dependencies.add(outlet, module.identifier)); }); return dependencies; } get outletDefinitions() { return this.outletDependencies.getKeysForValue(this.identifier); } get dependentControllerIdentifiers() { return this.outletDependencies.getValuesForKey(this.identifier); } get dependentContexts() { const identifiers = this.dependentControllerIdentifiers; return this.router.contexts.filter((context) => identifiers.includes(context.identifier)); } hasOutlet(element, outletName) { return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName); } getOutlet(element, outletName) { return this.application.getControllerForElementAndIdentifier(element, outletName); } getOutletFromMap(element, outletName) { return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element); } get scope() { return this.context.scope; } get schema() { return this.context.schema; } get identifier() { return this.context.identifier; } get application() { return this.context.application; } get router() { return this.application.router; } }; var Context = class { constructor(module, scope) { this.logDebugActivity = (functionName, detail = {}) => { const { identifier, controller, element } = this; detail = Object.assign({ identifier, controller, element }, detail); this.application.logDebugActivity(this.identifier, functionName, detail); }; this.module = module; this.scope = scope; this.controller = new module.controllerConstructor(this); this.bindingObserver = new BindingObserver(this, this.dispatcher); this.valueObserver = new ValueObserver(this, this.controller); this.targetObserver = new TargetObserver(this, this); this.outletObserver = new OutletObserver(this, this); try { this.controller.initialize(); this.logDebugActivity("initialize"); } catch (error2) { this.handleError(error2, "initializing controller"); } } connect() { this.bindingObserver.start(); this.valueObserver.start(); this.targetObserver.start(); this.outletObserver.start(); try { this.controller.connect(); this.logDebugActivity("connect"); } catch (error2) { this.handleError(error2, "connecting controller"); } } refresh() { this.outletObserver.refresh(); } disconnect() { try { this.controller.disconnect(); this.logDebugActivity("disconnect"); } catch (error2) { this.handleError(error2, "disconnecting controller"); } this.outletObserver.stop(); this.targetObserver.stop(); this.valueObserver.stop(); this.bindingObserver.stop(); } get application() { return this.module.application; } get identifier() { return this.module.identifier; } get schema() { return this.application.schema; } get dispatcher() { return this.application.dispatcher; } get element() { return this.scope.element; } get parentElement() { return this.element.parentElement; } handleError(error2, message, detail = {}) { const { identifier, controller, element } = this; detail = Object.assign({ identifier, controller, element }, detail); this.application.handleError(error2, `Error ${message}`, detail); } targetConnected(element, name) { this.invokeControllerMethod(`${name}TargetConnected`, element); } targetDisconnected(element, name) { this.invokeControllerMethod(`${name}TargetDisconnected`, element); } outletConnected(outlet, element, name) { this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element); } outletDisconnected(outlet, element, name) { this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element); } invokeControllerMethod(methodName, ...args) { const controller = this.controller; if (typeof controller[methodName] == "function") { controller[methodName](...args); } } }; function bless(constructor) { return shadow(constructor, getBlessedProperties(constructor)); } function shadow(constructor, properties) { const shadowConstructor = extend(constructor); const shadowProperties = getShadowProperties(constructor.prototype, properties); Object.defineProperties(shadowConstructor.prototype, shadowProperties); return shadowConstructor; } function getBlessedProperties(constructor) { const blessings = readInheritableStaticArrayValues(constructor, "blessings"); return blessings.reduce((blessedProperties, blessing) => { const properties = blessing(constructor); for (const key in properties) { const descriptor = blessedProperties[key] || {}; blessedProperties[key] = Object.assign(descriptor, properties[key]); } return blessedProperties; }, {}); } function getShadowProperties(prototype, properties) { return getOwnKeys(properties).reduce((shadowProperties, key) => { const descriptor = getShadowedDescriptor(prototype, properties, key); if (descriptor) { Object.assign(shadowProperties, { [key]: descriptor }); } return shadowProperties; }, {}); } function getShadowedDescriptor(prototype, properties, key) { const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key); const shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor; if (!shadowedByValue) { const descriptor = Object.getOwnPropertyDescriptor(properties, key).value; if (shadowingDescriptor) { descriptor.get = shadowingDescriptor.get || descriptor.get; descriptor.set = shadowingDescriptor.set || descriptor.set; } return descriptor; } } var getOwnKeys = (() => { if (typeof Object.getOwnPropertySymbols == "function") { return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)]; } else { return Object.getOwnPropertyNames; } })(); var extend = (() => { function extendWithReflect(constructor) { function extended() { return Reflect.construct(constructor, arguments, new.target); } extended.prototype = Object.create(constructor.prototype, { constructor: { value: extended } }); Reflect.setPrototypeOf(extended, constructor); return extended; } function testReflectExtension() { const a4 = function() { this.a.call(this); }; const b3 = extendWithReflect(a4); b3.prototype.a = function() { }; return new b3(); } try { testReflectExtension(); return extendWithReflect; } catch (error2) { return (constructor) => class extended extends constructor { }; } })(); function blessDefinition(definition) { return { identifier: definition.identifier, controllerConstructor: bless(definition.controllerConstructor) }; } var Module = class { constructor(application2, definition) { this.application = application2; this.definition = blessDefinition(definition); this.contextsByScope = /* @__PURE__ */ new WeakMap(); this.connectedContexts = /* @__PURE__ */ new Set(); } get identifier() { return this.definition.identifier; } get controllerConstructor() { return this.definition.controllerConstructor; } get contexts() { return Array.from(this.connectedContexts); } connectContextForScope(scope) { const context = this.fetchContextForScope(scope); this.connectedContexts.add(context); context.connect(); } disconnectContextForScope(scope) { const context = this.contextsByScope.get(scope); if (context) { this.connectedContexts.delete(context); context.disconnect(); } } fetchContextForScope(scope) { let context = this.contextsByScope.get(scope); if (!context) { context = new Context(this, scope); this.contextsByScope.set(scope, context); } return context; } }; var ClassMap = class { constructor(scope) { this.scope = scope; } has(name) { return this.data.has(this.getDataKey(name)); } get(name) { return this.getAll(name)[0]; } getAll(name) { const tokenString = this.data.get(this.getDataKey(name)) || ""; return tokenize(tokenString); } getAttributeName(name) { return this.data.getAttributeNameForKey(this.getDataKey(name)); } getDataKey(name) { return `${name}-class`; } get data() { return this.scope.data; } }; var DataMap = class { constructor(scope) { this.scope = scope; } get element() { return this.scope.element; } get identifier() { return this.scope.identifier; } get(key) { const name = this.getAttributeNameForKey(key); return this.element.getAttribute(name); } set(key, value) { const name = this.getAttributeNameForKey(key); this.element.setAttribute(name, value); return this.get(key); } has(key) { const name = this.getAttributeNameForKey(key); return this.element.hasAttribute(name); } delete(key) { if (this.has(key)) { const name = this.getAttributeNameForKey(key); this.element.removeAttribute(name); return true; } else { return false; } } getAttributeNameForKey(key) { return `data-${this.identifier}-${dasherize(key)}`; } }; var Guide = class { constructor(logger) { this.warnedKeysByObject = /* @__PURE__ */ new WeakMap(); this.logger = logger; } warn(object, key, message) { let warnedKeys = this.warnedKeysByObject.get(object); if (!warnedKeys) { warnedKeys = /* @__PURE__ */ new Set(); this.warnedKeysByObject.set(object, warnedKeys); } if (!warnedKeys.has(key)) { warnedKeys.add(key); this.logger.warn(message, object); } } }; function attributeValueContainsToken(attributeName, token) { return `[${attributeName}~="${token}"]`; } var TargetSet = class { constructor(scope) { this.scope = scope; } get element() { return this.scope.element; } get identifier() { return this.scope.identifier; } get schema() { return this.scope.schema; } has(targetName) { return this.find(targetName) != null; } find(...targetNames) { return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), void 0); } findAll(...targetNames) { return targetNames.reduce((targets, targetName) => [ ...targets, ...this.findAllTargets(targetName), ...this.findAllLegacyTargets(targetName) ], []); } findTarget(targetName) { const selector = this.getSelectorForTargetName(targetName); return this.scope.findElement(selector); } findAllTargets(targetName) { const selector = this.getSelectorForTargetName(targetName); return this.scope.findAllElements(selector); } getSelectorForTargetName(targetName) { const attributeName = this.schema.targetAttributeForScope(this.identifier); return attributeValueContainsToken(attributeName, targetName); } findLegacyTarget(targetName) { const selector = this.getLegacySelectorForTargetName(targetName); return this.deprecate(this.scope.findElement(selector), targetName); } findAllLegacyTargets(targetName) { const selector = this.getLegacySelectorForTargetName(targetName); return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName)); } getLegacySelectorForTargetName(targetName) { const targetDescriptor = `${this.identifier}.${targetName}`; return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor); } deprecate(element, targetName) { if (element) { const { identifier } = this; const attributeName = this.schema.targetAttribute; const revisedAttributeName = this.schema.targetAttributeForScope(identifier); this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}="${identifier}.${targetName}" with ${revisedAttributeName}="${targetName}". The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`); } return element; } get guide() { return this.scope.guide; } }; var OutletSet = class { constructor(scope, controllerElement) { this.scope = scope; this.controllerElement = controllerElement; } get element() { return this.scope.element; } get identifier() { return this.scope.identifier; } get schema() { return this.scope.schema; } has(outletName) { return this.find(outletName) != null; } find(...outletNames) { return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), void 0); } findAll(...outletNames) { return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []); } getSelectorForOutletName(outletName) { const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName); return this.controllerElement.getAttribute(attributeName); } findOutlet(outletName) { const selector = this.getSelectorForOutletName(outletName); if (selector) return this.findElement(selector, outletName); } findAllOutlets(outletName) { const selector = this.getSelectorForOutletName(outletName); return selector ? this.findAllElements(selector, outletName) : []; } findElement(selector, outletName) { const elements = this.scope.queryElements(selector); return elements.filter((element) => this.matchesElement(element, selector, outletName))[0]; } findAllElements(selector, outletName) { const elements = this.scope.queryElements(selector); return elements.filter((element) => this.matchesElement(element, selector, outletName)); } matchesElement(element, selector, outletName) { const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || ""; return element.matches(selector) && controllerAttribute.split(" ").includes(outletName); } }; var Scope = class _Scope { constructor(schema, element, identifier, logger) { this.targets = new TargetSet(this); this.classes = new ClassMap(this); this.data = new DataMap(this); this.containsElement = (element2) => { return element2.closest(this.controllerSelector) === this.element; }; this.schema = schema; this.element = element; this.identifier = identifier; this.guide = new Guide(logger); this.outlets = new OutletSet(this.documentScope, element); } findElement(selector) { return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement); } findAllElements(selector) { return [ ...this.element.matches(selector) ? [this.element] : [], ...this.queryElements(selector).filter(this.containsElement) ]; } queryElements(selector) { return Array.from(this.element.querySelectorAll(selector)); } get controllerSelector() { return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier); } get isDocumentScope() { return this.element === document.documentElement; } get documentScope() { return this.isDocumentScope ? this : new _Scope(this.schema, document.documentElement, this.identifier, this.guide.logger); } }; var ScopeObserver = class { constructor(element, schema, delegate) { this.element = element; this.schema = schema; this.delegate = delegate; this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this); this.scopesByIdentifierByElement = /* @__PURE__ */ new WeakMap(); this.scopeReferenceCounts = /* @__PURE__ */ new WeakMap(); } start() { this.valueListObserver.start(); } stop() { this.valueListObserver.stop(); } get controllerAttribute() { return this.schema.controllerAttribute; } parseValueForToken(token) { const { element, content: identifier } = token; return this.parseValueForElementAndIdentifier(element, identifier); } parseValueForElementAndIdentifier(element, identifier) { const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element); let scope = scopesByIdentifier.get(identifier); if (!scope) { scope = this.delegate.createScopeForElementAndIdentifier(element, identifier); scopesByIdentifier.set(identifier, scope); } return scope; } elementMatchedValue(element, value) { const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1; this.scopeReferenceCounts.set(value, referenceCount); if (referenceCount == 1) { this.delegate.scopeConnected(value); } } elementUnmatchedValue(element, value) { const referenceCount = this.scopeReferenceCounts.get(value); if (referenceCount) { this.scopeReferenceCounts.set(value, referenceCount - 1); if (referenceCount == 1) { this.delegate.scopeDisconnected(value); } } } fetchScopesByIdentifierForElement(element) { let scopesByIdentifier = this.scopesByIdentifierByElement.get(element); if (!scopesByIdentifier) { scopesByIdentifier = /* @__PURE__ */ new Map(); this.scopesByIdentifierByElement.set(element, scopesByIdentifier); } return scopesByIdentifier; } }; var Router = class { constructor(application2) { this.application = application2; this.scopeObserver = new ScopeObserver(this.element, this.schema, this); this.scopesByIdentifier = new Multimap(); this.modulesByIdentifier = /* @__PURE__ */ new Map(); } get element() { return this.application.element; } get schema() { return this.application.schema; } get logger() { return this.application.logger; } get controllerAttribute() { return this.schema.controllerAttribute; } get modules() { return Array.from(this.modulesByIdentifier.values()); } get contexts() { return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []); } start() { this.scopeObserver.start(); } stop() { this.scopeObserver.stop(); } loadDefinition(definition) { this.unloadIdentifier(definition.identifier); const module = new Module(this.application, definition); this.connectModule(module); const afterLoad = definition.controllerConstructor.afterLoad; if (afterLoad) { afterLoad.call(definition.controllerConstructor, definition.identifier, this.application); } } unloadIdentifier(identifier) { const module = this.modulesByIdentifier.get(identifier); if (module) { this.disconnectModule(module); } } getContextForElementAndIdentifier(element, identifier) { const module = this.modulesByIdentifier.get(identifier); if (module) { return module.contexts.find((context) => context.element == element); } } proposeToConnectScopeForElementAndIdentifier(element, identifier) { const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier); if (scope) { this.scopeObserver.elementMatchedValue(scope.element, scope); } else { console.error(`Couldn't find or create scope for identifier: "${identifier}" and element:`, element); } } handleError(error2, message, detail) { this.application.handleError(error2, message, detail); } createScopeForElementAndIdentifier(element, identifier) { return new Scope(this.schema, element, identifier, this.logger); } scopeConnected(scope) { this.scopesByIdentifier.add(scope.identifier, scope); const module = this.modulesByIdentifier.get(scope.identifier); if (module) { module.connectContextForScope(scope); } } scopeDisconnected(scope) { this.scopesByIdentifier.delete(scope.identifier, scope); const module = this.modulesByIdentifier.get(scope.identifier); if (module) { module.disconnectContextForScope(scope); } } connectModule(module) { this.modulesByIdentifier.set(module.identifier, module); const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier); scopes.forEach((scope) => module.connectContextForScope(scope)); } disconnectModule(module) { this.modulesByIdentifier.delete(module.identifier); const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier); scopes.forEach((scope) => module.disconnectContextForScope(scope)); } }; var defaultSchema = { controllerAttribute: "data-controller", actionAttribute: "data-action", targetAttribute: "data-target", targetAttributeForScope: (identifier) => `data-${identifier}-target`, outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`, keyMappings: Object.assign(Object.assign({ enter: "Enter", tab: "Tab", esc: "Escape", space: " ", up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", home: "Home", end: "End", page_up: "PageUp", page_down: "PageDown" }, objectFromEntries("abcdefghijklmnopqrstuvwxyz".split("").map((c4) => [c4, c4]))), objectFromEntries("0123456789".split("").map((n3) => [n3, n3]))) }; function objectFromEntries(array) { return array.reduce((memo, [k4, v4]) => Object.assign(Object.assign({}, memo), { [k4]: v4 }), {}); } var Application = class { constructor(element = document.documentElement, schema = defaultSchema) { this.logger = console; this.debug = false; this.logDebugActivity = (identifier, functionName, detail = {}) => { if (this.debug) { this.logFormattedMessage(identifier, functionName, detail); } }; this.element = element; this.schema = schema; this.dispatcher = new Dispatcher(this); this.router = new Router(this); this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters); } static start(element, schema) { const application2 = new this(element, schema); application2.start(); return application2; } async start() { await domReady(); this.logDebugActivity("application", "starting"); this.dispatcher.start(); this.router.start(); this.logDebugActivity("application", "start"); } stop() { this.logDebugActivity("application", "stopping"); this.dispatcher.stop(); this.router.stop(); this.logDebugActivity("application", "stop"); } register(identifier, controllerConstructor) { this.load({ identifier, controllerConstructor }); } registerActionOption(name, filter) { this.actionDescriptorFilters[name] = filter; } load(head, ...rest) { const definitions = Array.isArray(head) ? head : [head, ...rest]; definitions.forEach((definition) => { if (definition.controllerConstructor.shouldLoad) { this.router.loadDefinition(definition); } }); } unload(head, ...rest) { const identifiers = Array.isArray(head) ? head : [head, ...rest]; identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier)); } get controllers() { return this.router.contexts.map((context) => context.controller); } getControllerForElementAndIdentifier(element, identifier) { const context = this.router.getContextForElementAndIdentifier(element, identifier); return context ? context.controller : null; } handleError(error2, message, detail) { var _a; this.logger.error(`%s %o %o`, message, error2, detail); (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, "", 0, 0, error2); } logFormattedMessage(identifier, functionName, detail = {}) { detail = Object.assign({ application: this }, detail); this.logger.groupCollapsed(`${identifier} #${functionName}`); this.logger.log("details:", Object.assign({}, detail)); this.logger.groupEnd(); } }; function domReady() { return new Promise((resolve) => { if (document.readyState == "loading") { document.addEventListener("DOMContentLoaded", () => resolve()); } else { resolve(); } }); } function ClassPropertiesBlessing(constructor) { const classes = readInheritableStaticArrayValues(constructor, "classes"); return classes.reduce((properties, classDefinition) => { return Object.assign(properties, propertiesForClassDefinition(classDefinition)); }, {}); } function propertiesForClassDefinition(key) { return { [`${key}Class`]: { get() { const { classes } = this; if (classes.has(key)) { return classes.get(key); } else { const attribute = classes.getAttributeName(key); throw new Error(`Missing attribute "${attribute}"`); } } }, [`${key}Classes`]: { get() { return this.classes.getAll(key); } }, [`has${capitalize(key)}Class`]: { get() { return this.classes.has(key); } } }; } function OutletPropertiesBlessing(constructor) { const outlets = readInheritableStaticArrayValues(constructor, "outlets"); return outlets.reduce((properties, outletDefinition) => { return Object.assign(properties, propertiesForOutletDefinition(outletDefinition)); }, {}); } function getOutletController(controller, element, identifier) { return controller.application.getControllerForElementAndIdentifier(element, identifier); } function getControllerAndEnsureConnectedScope(controller, element, outletName) { let outletController = getOutletController(controller, element, outletName); if (outletController) return outletController; controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName); outletController = getOutletController(controller, element, outletName); if (outletController) return outletController; } function propertiesForOutletDefinition(name) { const camelizedName = namespaceCamelize(name); return { [`${camelizedName}Outlet`]: { get() { const outletElement = this.outlets.find(name); const selector = this.outlets.getSelectorForOutletName(name); if (outletElement) { const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name); if (outletController) return outletController; throw new Error(`The provided outlet element is missing an outlet controller "${name}" instance for host controller "${this.identifier}"`); } throw new Error(`Missing outlet element "${name}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${selector}".`); } }, [`${camelizedName}Outlets`]: { get() { const outlets = this.outlets.findAll(name); if (outlets.length > 0) { return outlets.map((outletElement) => { const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name); if (outletController) return outletController; console.warn(`The provided outlet element is missing an outlet controller "${name}" instance for host controller "${this.identifier}"`, outletElement); }).filter((controller) => controller); } return []; } }, [`${camelizedName}OutletElement`]: { get() { const outletElement = this.outlets.find(name); const selector = this.outlets.getSelectorForOutletName(name); if (outletElement) { return outletElement; } else { throw new Error(`Missing outlet element "${name}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${selector}".`); } } }, [`${camelizedName}OutletElements`]: { get() { return this.outlets.findAll(name); } }, [`has${capitalize(camelizedName)}Outlet`]: { get() { return this.outlets.has(name); } } }; } function TargetPropertiesBlessing(constructor) { const targets = readInheritableStaticArrayValues(constructor, "targets"); return targets.reduce((properties, targetDefinition) => { return Object.assign(properties, propertiesForTargetDefinition(targetDefinition)); }, {}); } function propertiesForTargetDefinition(name) { return { [`${name}Target`]: { get() { const target = this.targets.find(name); if (target) { return target; } else { throw new Error(`Missing target element "${name}" for "${this.identifier}" controller`); } } }, [`${name}Targets`]: { get() { return this.targets.findAll(name); } }, [`has${capitalize(name)}Target`]: { get() { return this.targets.has(name); } } }; } function ValuePropertiesBlessing(constructor) { const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, "values"); const propertyDescriptorMap = { valueDescriptorMap: { get() { return valueDefinitionPairs.reduce((result, valueDefinitionPair) => { const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier); const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key); return Object.assign(result, { [attributeName]: valueDescriptor }); }, {}); } } }; return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => { return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair)); }, propertyDescriptorMap); } function propertiesForValueDefinitionPair(valueDefinitionPair, controller) { const definition = parseValueDefinitionPair(valueDefinitionPair, controller); const { key, name, reader: read2, writer: write2 } = definition; return { [name]: { get() { const value = this.data.get(key); if (value !== null) { return read2(value); } else { return definition.defaultValue; } }, set(value) { if (value === void 0) { this.data.delete(key); } else { this.data.set(key, write2(value)); } } }, [`has${capitalize(name)}`]: { get() { return this.data.has(key) || definition.hasCustomDefaultValue; } } }; } function parseValueDefinitionPair([token, typeDefinition], controller) { return valueDescriptorForTokenAndTypeDefinition({ controller, token, typeDefinition }); } function parseValueTypeConstant(constant) { switch (constant) { case Array: return "array"; case Boolean: return "boolean"; case Number: return "number"; case Object: return "object"; case String: return "string"; } } function parseValueTypeDefault(defaultValue) { switch (typeof defaultValue) { case "boolean": return "boolean"; case "number": return "number"; case "string": return "string"; } if (Array.isArray(defaultValue)) return "array"; if (Object.prototype.toString.call(defaultValue) === "[object Object]") return "object"; } function parseValueTypeObject(payload) { const { controller, token, typeObject } = payload; const hasType = isSomething(typeObject.type); const hasDefault = isSomething(typeObject.default); const fullObject = hasType && hasDefault; const onlyType = hasType && !hasDefault; const onlyDefault = !hasType && hasDefault; const typeFromObject = parseValueTypeConstant(typeObject.type); const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default); if (onlyType) return typeFromObject; if (onlyDefault) return typeFromDefaultValue; if (typeFromObject !== typeFromDefaultValue) { const propertyPath = controller ? `${controller}.${token}` : token; throw new Error(`The specified default value for the Stimulus Value "${propertyPath}" must match the defined type "${typeFromObject}". The provided default value of "${typeObject.default}" is of type "${typeFromDefaultValue}".`); } if (fullObject) return typeFromObject; } function parseValueTypeDefinition(payload) { const { controller, token, typeDefinition } = payload; const typeObject = { controller, token, typeObject: typeDefinition }; const typeFromObject = parseValueTypeObject(typeObject); const typeFromDefaultValue = parseValueTypeDefault(typeDefinition); const typeFromConstant = parseValueTypeConstant(typeDefinition); const type = typeFromObject || typeFromDefaultValue || typeFromConstant; if (type) return type; const propertyPath = controller ? `${controller}.${typeDefinition}` : token; throw new Error(`Unknown value type "${propertyPath}" for "${token}" value`); } function defaultValueForDefinition(typeDefinition) { const constant = parseValueTypeConstant(typeDefinition); if (constant) return defaultValuesByType[constant]; const hasDefault = hasProperty(typeDefinition, "default"); const hasType = hasProperty(typeDefinition, "type"); const typeObject = typeDefinition; if (hasDefault) return typeObject.default; if (hasType) { const { type } = typeObject; const constantFromType = parseValueTypeConstant(type); if (constantFromType) return defaultValuesByType[constantFromType]; } return typeDefinition; } function valueDescriptorForTokenAndTypeDefinition(payload) { const { token, typeDefinition } = payload; const key = `${dasherize(token)}-value`; const type = parseValueTypeDefinition(payload); return { type, key, name: camelize(key), get defaultValue() { return defaultValueForDefinition(typeDefinition); }, get hasCustomDefaultValue() { return parseValueTypeDefault(typeDefinition) !== void 0; }, reader: readers[type], writer: writers[type] || writers.default }; } var defaultValuesByType = { get array() { return []; }, boolean: false, number: 0, get object() { return {}; }, string: "" }; var readers = { array(value) { const array = JSON.parse(value); if (!Array.isArray(array)) { throw new TypeError(`expected value of type "array" but instead got value "${value}" of type "${parseValueTypeDefault(array)}"`); } return array; }, boolean(value) { return !(value == "0" || String(value).toLowerCase() == "false"); }, number(value) { return Number(value.replace(/_/g, "")); }, object(value) { const object = JSON.parse(value); if (object === null || typeof object != "object" || Array.isArray(object)) { throw new TypeError(`expected value of type "object" but instead got value "${value}" of type "${parseValueTypeDefault(object)}"`); } return object; }, string(value) { return value; } }; var writers = { default: writeString, array: writeJSON, object: writeJSON }; function writeJSON(value) { return JSON.stringify(value); } function writeString(value) { return `${value}`; } var Controller = class { constructor(context) { this.context = context; } static get shouldLoad() { return true; } static afterLoad(_identifier, _application) { return; } get application() { return this.context.application; } get scope() { return this.context.scope; } get element() { return this.scope.element; } get identifier() { return this.scope.identifier; } get targets() { return this.scope.targets; } get outlets() { return this.scope.outlets; } get classes() { return this.scope.classes; } get data() { return this.scope.data; } initialize() { } connect() { } disconnect() { } dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}) { const type = prefix ? `${prefix}:${eventName}` : eventName; const event = new CustomEvent(type, { detail, bubbles, cancelable }); target.dispatchEvent(event); return event; } }; Controller.blessings = [ ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing, OutletPropertiesBlessing ]; Controller.targets = []; Controller.outlets = []; Controller.values = {}; // src/js/controllers/resource_header_controller.js var resource_header_controller_default = class extends Controller { static targets = ["openIcon", "closeIcon"]; static outlets = ["sidebar"]; static values = { placement: { type: String, default: "left" }, bodyScrolling: { type: Boolean, default: false }, backdrop: { type: Boolean, default: true }, edge: { type: Boolean, default: false }, edgeOffset: { type: String, default: "bottom-[60px]" } }; static classes = { backdrop: "bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-30" }; initialize() { this.visible = false; this.handleEscapeKey = this.handleEscapeKey.bind(this); } connect() { document.addEventListener("keydown", this.handleEscapeKey); } sidebarOutletConnected() { this.#setupDrawer(this.sidebarOutlet.element); } disconnect() { this.#removeBackdrop(); document.removeEventListener("keydown", this.handleEscapeKey); if (!this.bodyScrollingValue) { document.body.classList.remove("overflow-hidden"); } } #setupDrawer(drawerElement) { drawerElement.setAttribute("aria-hidden", "true"); drawerElement.classList.add("transition-transform"); this.#getPlacementClasses(this.placementValue).base.forEach((className) => { drawerElement.classList.add(className); }); } toggleDrawer() { this.visible ? this.hideDrawer() : this.showDrawer(); } showDrawer() { if (this.edgeValue) { this.#toggleEdgePlacementClasses(`${this.placementValue}-edge`, true); } else { this.#togglePlacementClasses(this.placementValue, true); } this.openIconTarget.classList.add("hidden"); this.openIconTarget.setAttribute("aria-hidden", "true"); this.closeIconTarget.classList.remove("hidden"); this.closeIconTarget.setAttribute("aria-hidden", "false"); this.sidebarOutlet.element.setAttribute("aria-modal", "true"); this.sidebarOutlet.element.setAttribute("role", "dialog"); this.sidebarOutlet.element.removeAttribute("aria-hidden"); if (!this.bodyScrollingValue) { document.body.classList.add("overflow-hidden"); } if (this.backdropValue) { this.#createBackdrop(); } this.visible = true; this.dispatch("show"); } hideDrawer() { if (this.edgeValue) { this.#toggleEdgePlacementClasses(`${this.placementValue}-edge`, false); } else { this.#togglePlacementClasses(this.placementValue, false); } this.openIconTarget.classList.remove("hidden"); this.openIconTarget.setAttribute("aria-hidden", "false"); this.closeIconTarget.classList.add("hidden"); this.closeIconTarget.setAttribute("aria-hidden", "true"); this.sidebarOutlet.element.setAttribute("aria-hidden", "true"); this.sidebarOutlet.element.removeAttribute("aria-modal"); this.sidebarOutlet.element.removeAttribute("role"); if (!this.bodyScrollingValue) { document.body.classList.remove("overflow-hidden"); } if (this.backdropValue) { this.#removeBackdrop(); } this.visible = false; this.dispatch("hide"); } handleEscapeKey(event) { if (event.key === "Escape" && this.visible) { this.hideDrawer(); } } #createBackdrop() { if (!this.visible) { const backdrop = document.createElement("div"); backdrop.setAttribute("data-drawer-backdrop", ""); backdrop.classList.add(...this.constructor.classes.backdrop.split(" ")); backdrop.addEventListener("click", () => this.hideDrawer()); document.body.appendChild(backdrop); } } #removeBackdrop() { const backdrop = document.querySelector("[data-drawer-backdrop]"); if (backdrop) { backdrop.remove(); } } #getPlacementClasses(placement) { const placements2 = { top: { base: ["top-0", "left-0", "right-0"], active: ["transform-none"], inactive: ["-translate-y-full"] }, right: { base: ["right-0", "top-0"], active: ["transform-none"], inactive: ["translate-x-full"] }, bottom: { base: ["bottom-0", "left-0", "right-0"], active: ["transform-none"], inactive: ["translate-y-full"] }, left: { base: ["left-0", "top-0"], active: ["transform-none"], inactive: ["-translate-x-full"] }, "bottom-edge": { base: ["left-0", "top-0"], active: ["transform-none"], inactive: ["translate-y-full", this.edgeOffsetValue] } }; return placements2[placement] || placements2.left; } #togglePlacementClasses(placement, show) { const classes = this.#getPlacementClasses(placement); if (show) { classes.active.forEach((c4) => this.sidebarOutlet.element.classList.add(c4)); classes.inactive.forEach((c4) => this.sidebarOutlet.element.classList.remove(c4)); } else { classes.active.forEach((c4) => this.sidebarOutlet.element.classList.remove(c4)); classes.inactive.forEach((c4) => this.sidebarOutlet.element.classList.add(c4)); } } #toggleEdgePlacementClasses(placement, show) { this.#togglePlacementClasses(placement, show); } }; // src/js/controllers/nested_resource_form_fields_controller.js var nested_resource_form_fields_controller_default = class extends Controller { static targets = ["target", "template", "addButton"]; static values = { wrapperSelector: { type: String, default: ".nested-resource-form-fields" }, limit: Number }; connect() { this.updateState(); } add(e4) { e4.preventDefault(); const content = this.templateTarget.innerHTML.replace(/NEW_RECORD/g, (/* @__PURE__ */ new Date()).getTime().toString()); this.targetTarget.insertAdjacentHTML("beforebegin", content); const event = new CustomEvent("nested-resource-form-fields:add", { bubbles: true }); this.element.dispatchEvent(event); this.updateState(); } remove(e4) { e4.preventDefault(); const wrapper = e4.target.closest(this.wrapperSelectorValue); if (wrapper.dataset.newRecord !== void 0) { wrapper.remove(); } else { wrapper.style.display = "none"; wrapper.classList.remove(...wrapper.classList); const input = wrapper.querySelector("input[name*='_destroy']"); input.value = "1"; } const event = new CustomEvent("nested-resource-form-fields:remove", { bubbles: true }); this.element.dispatchEvent(event); this.updateState(); } updateState() { if (!this.hasAddButtonTarget || this.limitValue == 0) return; if (this.childCount >= this.limitValue) this.addButtonTarget.style.display = "none"; else this.addButtonTarget.style.display = "initial"; } get childCount() { return this.element.querySelectorAll(this.wrapperSelectorValue).length; } }; // src/js/controllers/form_controller.js var import_lodash = __toESM(require_lodash(), 1); var form_controller_default = class extends Controller { connect() { } submit() { this.element.requestSubmit(); } }; // node_modules/@popperjs/core/lib/enums.js var top = "top"; var bottom = "bottom"; var right = "right"; var left = "left"; var auto = "auto"; var basePlacements = [top, bottom, right, left]; var start = "start"; var end = "end"; var clippingParents = "clippingParents"; var viewport = "viewport"; var popper = "popper"; var reference = "reference"; var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { return acc.concat([placement + "-" + start, placement + "-" + end]); }, []); var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { return acc.concat([placement, placement + "-" + start, placement + "-" + end]); }, []); var beforeRead = "beforeRead"; var read = "read"; var afterRead = "afterRead"; var beforeMain = "beforeMain"; var main = "main"; var afterMain = "afterMain"; var beforeWrite = "beforeWrite"; var write = "write"; var afterWrite = "afterWrite"; var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; // node_modules/@popperjs/core/lib/dom-utils/getNodeName.js function getNodeName(element) { return element ? (element.nodeName || "").toLowerCase() : null; } // node_modules/@popperjs/core/lib/dom-utils/getWindow.js function getWindow(node) { if (node == null) { return window; } if (node.toString() !== "[object Window]") { var ownerDocument = node.ownerDocument; return ownerDocument ? ownerDocument.defaultView || window : window; } return node; } // node_modules/@popperjs/core/lib/dom-utils/instanceOf.js function isElement(node) { var OwnElement = getWindow(node).Element; return node instanceof OwnElement || node instanceof Element; } function isHTMLElement(node) { var OwnElement = getWindow(node).HTMLElement; return node instanceof OwnElement || node instanceof HTMLElement; } function isShadowRoot(node) { if (typeof ShadowRoot === "undefined") { return false; } var OwnElement = getWindow(node).ShadowRoot; return node instanceof OwnElement || node instanceof ShadowRoot; } // node_modules/@popperjs/core/lib/modifiers/applyStyles.js function applyStyles(_ref) { var state = _ref.state; Object.keys(state.elements).forEach(function(name) { var style = state.styles[name] || {}; var attributes = state.attributes[name] || {}; var element = state.elements[name]; if (!isHTMLElement(element) || !getNodeName(element)) { return; } Object.assign(element.style, style); Object.keys(attributes).forEach(function(name2) { var value = attributes[name2]; if (value === false) { element.removeAttribute(name2); } else { element.setAttribute(name2, value === true ? "" : value); } }); }); } function effect(_ref2) { var state = _ref2.state; var initialStyles = { popper: { position: state.options.strategy, left: "0", top: "0", margin: "0" }, arrow: { position: "absolute" }, reference: {} }; Object.assign(state.elements.popper.style, initialStyles.popper); state.styles = initialStyles; if (state.elements.arrow) { Object.assign(state.elements.arrow.style, initialStyles.arrow); } return function() { Object.keys(state.elements).forEach(function(name) { var element = state.elements[name]; var attributes = state.attributes[name] || {}; var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); var style = styleProperties.reduce(function(style2, property) { style2[property] = ""; return style2; }, {}); if (!isHTMLElement(element) || !getNodeName(element)) { return; } Object.assign(element.style, style); Object.keys(attributes).forEach(function(attribute) { element.removeAttribute(attribute); }); }); }; } var applyStyles_default = { name: "applyStyles", enabled: true, phase: "write", fn: applyStyles, effect, requires: ["computeStyles"] }; // node_modules/@popperjs/core/lib/utils/getBasePlacement.js function getBasePlacement(placement) { return placement.split("-")[0]; } // node_modules/@popperjs/core/lib/utils/math.js var max = Math.max; var min = Math.min; var round = Math.round; // node_modules/@popperjs/core/lib/utils/userAgent.js function getUAString() { var uaData = navigator.userAgentData; if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { return uaData.brands.map(function(item) { return item.brand + "/" + item.version; }).join(" "); } return navigator.userAgent; } // node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js function isLayoutViewport() { return !/^((?!chrome|android).)*safari/i.test(getUAString()); } // node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js function getBoundingClientRect(element, includeScale, isFixedStrategy) { if (includeScale === void 0) { includeScale = false; } if (isFixedStrategy === void 0) { isFixedStrategy = false; } var clientRect = element.getBoundingClientRect(); var scaleX = 1; var scaleY = 1; if (includeScale && isHTMLElement(element)) { scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; } var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport; var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; var x3 = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; var y4 = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; var width = clientRect.width / scaleX; var height = clientRect.height / scaleY; return { width, height, top: y4, right: x3 + width, bottom: y4 + height, left: x3, x: x3, y: y4 }; } // node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js function getLayoutRect(element) { var clientRect = getBoundingClientRect(element); var width = element.offsetWidth; var height = element.offsetHeight; if (Math.abs(clientRect.width - width) <= 1) { width = clientRect.width; } if (Math.abs(clientRect.height - height) <= 1) { height = clientRect.height; } return { x: element.offsetLeft, y: element.offsetTop, width, height }; } // node_modules/@popperjs/core/lib/dom-utils/contains.js function contains(parent, child) { var rootNode = child.getRootNode && child.getRootNode(); if (parent.contains(child)) { return true; } else if (rootNode && isShadowRoot(rootNode)) { var next = child; do { if (next && parent.isSameNode(next)) { return true; } next = next.parentNode || next.host; } while (next); } return false; } // node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js function getComputedStyle(element) { return getWindow(element).getComputedStyle(element); } // node_modules/@popperjs/core/lib/dom-utils/isTableElement.js function isTableElement(element) { return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0; } // node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js function getDocumentElement(element) { return ((isElement(element) ? element.ownerDocument : ( // $FlowFixMe[prop-missing] element.document )) || window.document).documentElement; } // node_modules/@popperjs/core/lib/dom-utils/getParentNode.js function getParentNode(element) { if (getNodeName(element) === "html") { return element; } return ( // this is a quicker (but less type safe) way to save quite some bytes from the bundle // $FlowFixMe[incompatible-return] // $FlowFixMe[prop-missing] element.assignedSlot || // step into the shadow DOM of the parent of a slotted node element.parentNode || // DOM Element detected (isShadowRoot(element) ? element.host : null) || // ShadowRoot detected // $FlowFixMe[incompatible-call]: HTMLElement is a Node getDocumentElement(element) ); } // node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js function getTrueOffsetParent(element) { if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 getComputedStyle(element).position === "fixed") { return null; } return element.offsetParent; } function getContainingBlock(element) { var isFirefox = /firefox/i.test(getUAString()); var isIE = /Trident/i.test(getUAString()); if (isIE && isHTMLElement(element)) { var elementCss = getComputedStyle(element); if (elementCss.position === "fixed") { return null; } } var currentNode = getParentNode(element); if (isShadowRoot(currentNode)) { currentNode = currentNode.host; } while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { var css = getComputedStyle(currentNode); if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { return currentNode; } else { currentNode = currentNode.parentNode; } } return null; } function getOffsetParent(element) { var window2 = getWindow(element); var offsetParent = getTrueOffsetParent(element); while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") { offsetParent = getTrueOffsetParent(offsetParent); } if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) { return window2; } return offsetParent || getContainingBlock(element) || window2; } // node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js function getMainAxisFromPlacement(placement) { return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; } // node_modules/@popperjs/core/lib/utils/within.js function within(min2, value, max2) { return max(min2, min(value, max2)); } function withinMaxClamp(min2, value, max2) { var v4 = within(min2, value, max2); return v4 > max2 ? max2 : v4; } // node_modules/@popperjs/core/lib/utils/getFreshSideObject.js function getFreshSideObject() { return { top: 0, right: 0, bottom: 0, left: 0 }; } // node_modules/@popperjs/core/lib/utils/mergePaddingObject.js function mergePaddingObject(paddingObject) { return Object.assign({}, getFreshSideObject(), paddingObject); } // node_modules/@popperjs/core/lib/utils/expandToHashMap.js function expandToHashMap(value, keys) { return keys.reduce(function(hashMap, key) { hashMap[key] = value; return hashMap; }, {}); } // node_modules/@popperjs/core/lib/modifiers/arrow.js var toPaddingObject = function toPaddingObject2(padding, state) { padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { placement: state.placement })) : padding; return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); }; function arrow(_ref) { var _state$modifiersData$; var state = _ref.state, name = _ref.name, options2 = _ref.options; var arrowElement = state.elements.arrow; var popperOffsets2 = state.modifiersData.popperOffsets; var basePlacement = getBasePlacement(state.placement); var axis = getMainAxisFromPlacement(basePlacement); var isVertical = [left, right].indexOf(basePlacement) >= 0; var len = isVertical ? "height" : "width"; if (!arrowElement || !popperOffsets2) { return; } var paddingObject = toPaddingObject(options2.padding, state); var arrowRect = getLayoutRect(arrowElement); var minProp = axis === "y" ? top : left; var maxProp = axis === "y" ? bottom : right; var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; var arrowOffsetParent = getOffsetParent(arrowElement); var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; var centerToReference = endDiff / 2 - startDiff / 2; var min2 = paddingObject[minProp]; var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; var offset2 = within(min2, center, max2); var axisProp = axis; state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$); } function effect2(_ref2) { var state = _ref2.state, options2 = _ref2.options; var _options$element = options2.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; if (arrowElement == null) { return; } if (typeof arrowElement === "string") { arrowElement = state.elements.popper.querySelector(arrowElement); if (!arrowElement) { return; } } if (!contains(state.elements.popper, arrowElement)) { return; } state.elements.arrow = arrowElement; } var arrow_default = { name: "arrow", enabled: true, phase: "main", fn: arrow, effect: effect2, requires: ["popperOffsets"], requiresIfExists: ["preventOverflow"] }; // node_modules/@popperjs/core/lib/utils/getVariation.js function getVariation(placement) { return placement.split("-")[1]; } // node_modules/@popperjs/core/lib/modifiers/computeStyles.js var unsetSides = { top: "auto", right: "auto", bottom: "auto", left: "auto" }; function roundOffsetsByDPR(_ref, win) { var x3 = _ref.x, y4 = _ref.y; var dpr = win.devicePixelRatio || 1; return { x: round(x3 * dpr) / dpr || 0, y: round(y4 * dpr) / dpr || 0 }; } function mapToStyles(_ref2) { var _Object$assign2; var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; var _offsets$x = offsets.x, x3 = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y4 = _offsets$y === void 0 ? 0 : _offsets$y; var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ x: x3, y: y4 }) : { x: x3, y: y4 }; x3 = _ref3.x; y4 = _ref3.y; var hasX = offsets.hasOwnProperty("x"); var hasY = offsets.hasOwnProperty("y"); var sideX = left; var sideY = top; var win = window; if (adaptive) { var offsetParent = getOffsetParent(popper2); var heightProp = "clientHeight"; var widthProp = "clientWidth"; if (offsetParent === getWindow(popper2)) { offsetParent = getDocumentElement(popper2); if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") { heightProp = "scrollHeight"; widthProp = "scrollWidth"; } } offsetParent = offsetParent; if (placement === top || (placement === left || placement === right) && variation === end) { sideY = bottom; var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : ( // $FlowFixMe[prop-missing] offsetParent[heightProp] ); y4 -= offsetY - popperRect.height; y4 *= gpuAcceleration ? 1 : -1; } if (placement === left || (placement === top || placement === bottom) && variation === end) { sideX = right; var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : ( // $FlowFixMe[prop-missing] offsetParent[widthProp] ); x3 -= offsetX - popperRect.width; x3 *= gpuAcceleration ? 1 : -1; } } var commonStyles = Object.assign({ position }, adaptive && unsetSides); var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ x: x3, y: y4 }, getWindow(popper2)) : { x: x3, y: y4 }; x3 = _ref4.x; y4 = _ref4.y; if (gpuAcceleration) { var _Object$assign; return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x3 + "px, " + y4 + "px)" : "translate3d(" + x3 + "px, " + y4 + "px, 0)", _Object$assign)); } return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y4 + "px" : "", _Object$assign2[sideX] = hasX ? x3 + "px" : "", _Object$assign2.transform = "", _Object$assign2)); } function computeStyles(_ref5) { var state = _ref5.state, options2 = _ref5.options; var _options$gpuAccelerat = options2.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options2.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options2.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; var commonStyles = { placement: getBasePlacement(state.placement), variation: getVariation(state.placement), popper: state.elements.popper, popperRect: state.rects.popper, gpuAcceleration, isFixed: state.options.strategy === "fixed" }; if (state.modifiersData.popperOffsets != null) { state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { offsets: state.modifiersData.popperOffsets, position: state.options.strategy, adaptive, roundOffsets }))); } if (state.modifiersData.arrow != null) { state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { offsets: state.modifiersData.arrow, position: "absolute", adaptive: false, roundOffsets }))); } state.attributes.popper = Object.assign({}, state.attributes.popper, { "data-popper-placement": state.placement }); } var computeStyles_default = { name: "computeStyles", enabled: true, phase: "beforeWrite", fn: computeStyles, data: {} }; // node_modules/@popperjs/core/lib/modifiers/eventListeners.js var passive = { passive: true }; function effect3(_ref) { var state = _ref.state, instance = _ref.instance, options2 = _ref.options; var _options$scroll = options2.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options2.resize, resize = _options$resize === void 0 ? true : _options$resize; var window2 = getWindow(state.elements.popper); var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); if (scroll) { scrollParents.forEach(function(scrollParent) { scrollParent.addEventListener("scroll", instance.update, passive); }); } if (resize) { window2.addEventListener("resize", instance.update, passive); } return function() { if (scroll) { scrollParents.forEach(function(scrollParent) { scrollParent.removeEventListener("scroll", instance.update, passive); }); } if (resize) { window2.removeEventListener("resize", instance.update, passive); } }; } var eventListeners_default = { name: "eventListeners", enabled: true, phase: "write", fn: function fn() { }, effect: effect3, data: {} }; // node_modules/@popperjs/core/lib/utils/getOppositePlacement.js var hash = { left: "right", right: "left", bottom: "top", top: "bottom" }; function getOppositePlacement(placement) { return placement.replace(/left|right|bottom|top/g, function(matched) { return hash[matched]; }); } // node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js var hash2 = { start: "end", end: "start" }; function getOppositeVariationPlacement(placement) { return placement.replace(/start|end/g, function(matched) { return hash2[matched]; }); } // node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js function getWindowScroll(node) { var win = getWindow(node); var scrollLeft = win.pageXOffset; var scrollTop = win.pageYOffset; return { scrollLeft, scrollTop }; } // node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js function getWindowScrollBarX(element) { return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; } // node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js function getViewportRect(element, strategy) { var win = getWindow(element); var html3 = getDocumentElement(element); var visualViewport = win.visualViewport; var width = html3.clientWidth; var height = html3.clientHeight; var x3 = 0; var y4 = 0; if (visualViewport) { width = visualViewport.width; height = visualViewport.height; var layoutViewport = isLayoutViewport(); if (layoutViewport || !layoutViewport && strategy === "fixed") { x3 = visualViewport.offsetLeft; y4 = visualViewport.offsetTop; } } return { width, height, x: x3 + getWindowScrollBarX(element), y: y4 }; } // node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js function getDocumentRect(element) { var _element$ownerDocumen; var html3 = getDocumentElement(element); var winScroll = getWindowScroll(element); var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; var width = max(html3.scrollWidth, html3.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); var height = max(html3.scrollHeight, html3.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); var x3 = -winScroll.scrollLeft + getWindowScrollBarX(element); var y4 = -winScroll.scrollTop; if (getComputedStyle(body || html3).direction === "rtl") { x3 += max(html3.clientWidth, body ? body.clientWidth : 0) - width; } return { width, height, x: x3, y: y4 }; } // node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js function isScrollParent(element) { var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); } // node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js function getScrollParent(node) { if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { return node.ownerDocument.body; } if (isHTMLElement(node) && isScrollParent(node)) { return node; } return getScrollParent(getParentNode(node)); } // node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js function listScrollParents(element, list2) { var _element$ownerDocumen; if (list2 === void 0) { list2 = []; } var scrollParent = getScrollParent(element); var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); var win = getWindow(scrollParent); var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; var updatedList = list2.concat(target); return isBody ? updatedList : ( // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here updatedList.concat(listScrollParents(getParentNode(target))) ); } // node_modules/@popperjs/core/lib/utils/rectToClientRect.js function rectToClientRect(rect) { return Object.assign({}, rect, { left: rect.x, top: rect.y, right: rect.x + rect.width, bottom: rect.y + rect.height }); } // node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js function getInnerBoundingClientRect(element, strategy) { var rect = getBoundingClientRect(element, false, strategy === "fixed"); rect.top = rect.top + element.clientTop; rect.left = rect.left + element.clientLeft; rect.bottom = rect.top + element.clientHeight; rect.right = rect.left + element.clientWidth; rect.width = element.clientWidth; rect.height = element.clientHeight; rect.x = rect.left; rect.y = rect.top; return rect; } function getClientRectFromMixedType(element, clippingParent, strategy) { return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); } function getClippingParents(element) { var clippingParents2 = listScrollParents(getParentNode(element)); var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0; var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; if (!isElement(clipperElement)) { return []; } return clippingParents2.filter(function(clippingParent) { return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; }); } function getClippingRect(element, boundary, rootBoundary, strategy) { var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary); var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); var firstClippingParent = clippingParents2[0]; var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { var rect = getClientRectFromMixedType(element, clippingParent, strategy); accRect.top = max(rect.top, accRect.top); accRect.right = min(rect.right, accRect.right); accRect.bottom = min(rect.bottom, accRect.bottom); accRect.left = max(rect.left, accRect.left); return accRect; }, getClientRectFromMixedType(element, firstClippingParent, strategy)); clippingRect.width = clippingRect.right - clippingRect.left; clippingRect.height = clippingRect.bottom - clippingRect.top; clippingRect.x = clippingRect.left; clippingRect.y = clippingRect.top; return clippingRect; } // node_modules/@popperjs/core/lib/utils/computeOffsets.js function computeOffsets(_ref) { var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement; var basePlacement = placement ? getBasePlacement(placement) : null; var variation = placement ? getVariation(placement) : null; var commonX = reference2.x + reference2.width / 2 - element.width / 2; var commonY = reference2.y + reference2.height / 2 - element.height / 2; var offsets; switch (basePlacement) { case top: offsets = { x: commonX, y: reference2.y - element.height }; break; case bottom: offsets = { x: commonX, y: reference2.y + reference2.height }; break; case right: offsets = { x: reference2.x + reference2.width, y: commonY }; break; case left: offsets = { x: reference2.x - element.width, y: commonY }; break; default: offsets = { x: reference2.x, y: reference2.y }; } var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; if (mainAxis != null) { var len = mainAxis === "y" ? "height" : "width"; switch (variation) { case start: offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2); break; case end: offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2); break; default: } } return offsets; } // node_modules/@popperjs/core/lib/utils/detectOverflow.js function detectOverflow(state, options2) { if (options2 === void 0) { options2 = {}; } var _options = options2, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); var altContext = elementContext === popper ? reference : popper; var popperRect = state.rects.popper; var element = state.elements[altBoundary ? altContext : elementContext]; var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); var referenceClientRect = getBoundingClientRect(state.elements.reference); var popperOffsets2 = computeOffsets({ reference: referenceClientRect, element: popperRect, strategy: "absolute", placement }); var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; var overflowOffsets = { top: clippingClientRect.top - elementClientRect.top + paddingObject.top, bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, left: clippingClientRect.left - elementClientRect.left + paddingObject.left, right: elementClientRect.right - clippingClientRect.right + paddingObject.right }; var offsetData = state.modifiersData.offset; if (elementContext === popper && offsetData) { var offset2 = offsetData[placement]; Object.keys(overflowOffsets).forEach(function(key) { var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; overflowOffsets[key] += offset2[axis] * multiply; }); } return overflowOffsets; } // node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js function computeAutoPlacement(state, options2) { if (options2 === void 0) { options2 = {}; } var _options = options2, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; var variation = getVariation(placement); var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { return getVariation(placement2) === variation; }) : basePlacements; var allowedPlacements = placements2.filter(function(placement2) { return allowedAutoPlacements.indexOf(placement2) >= 0; }); if (allowedPlacements.length === 0) { allowedPlacements = placements2; } var overflows = allowedPlacements.reduce(function(acc, placement2) { acc[placement2] = detectOverflow(state, { placement: placement2, boundary, rootBoundary, padding })[getBasePlacement(placement2)]; return acc; }, {}); return Object.keys(overflows).sort(function(a4, b3) { return overflows[a4] - overflows[b3]; }); } // node_modules/@popperjs/core/lib/modifiers/flip.js function getExpandedFallbackPlacements(placement) { if (getBasePlacement(placement) === auto) { return []; } var oppositePlacement = getOppositePlacement(placement); return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; } function flip(_ref) { var state = _ref.state, options2 = _ref.options, name = _ref.name; if (state.modifiersData[name]._skip) { return; } var _options$mainAxis = options2.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options2.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options2.fallbackPlacements, padding = options2.padding, boundary = options2.boundary, rootBoundary = options2.rootBoundary, altBoundary = options2.altBoundary, _options$flipVariatio = options2.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options2.allowedAutoPlacements; var preferredPlacement = state.options.placement; var basePlacement = getBasePlacement(preferredPlacement); var isBasePlacement = basePlacement === preferredPlacement; var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, { placement: placement2, boundary, rootBoundary, padding, flipVariations, allowedAutoPlacements }) : placement2); }, []); var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var checksMap = /* @__PURE__ */ new Map(); var makeFallbackChecks = true; var firstFittingPlacement = placements2[0]; for (var i4 = 0; i4 < placements2.length; i4++) { var placement = placements2[i4]; var _basePlacement = getBasePlacement(placement); var isStartVariation = getVariation(placement) === start; var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; var len = isVertical ? "width" : "height"; var overflow = detectOverflow(state, { placement, boundary, rootBoundary, altBoundary, padding }); var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; if (referenceRect[len] > popperRect[len]) { mainVariationSide = getOppositePlacement(mainVariationSide); } var altVariationSide = getOppositePlacement(mainVariationSide); var checks = []; if (checkMainAxis) { checks.push(overflow[_basePlacement] <= 0); } if (checkAltAxis) { checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); } if (checks.every(function(check) { return check; })) { firstFittingPlacement = placement; makeFallbackChecks = false; break; } checksMap.set(placement, checks); } if (makeFallbackChecks) { var numberOfChecks = flipVariations ? 3 : 1; var _loop = function _loop2(_i2) { var fittingPlacement = placements2.find(function(placement2) { var checks2 = checksMap.get(placement2); if (checks2) { return checks2.slice(0, _i2).every(function(check) { return check; }); } }); if (fittingPlacement) { firstFittingPlacement = fittingPlacement; return "break"; } }; for (var _i = numberOfChecks; _i > 0; _i--) { var _ret = _loop(_i); if (_ret === "break") break; } } if (state.placement !== firstFittingPlacement) { state.modifiersData[name]._skip = true; state.placement = firstFittingPlacement; state.reset = true; } } var flip_default = { name: "flip", enabled: true, phase: "main", fn: flip, requiresIfExists: ["offset"], data: { _skip: false } }; // node_modules/@popperjs/core/lib/modifiers/hide.js function getSideOffsets(overflow, rect, preventedOffsets) { if (preventedOffsets === void 0) { preventedOffsets = { x: 0, y: 0 }; } return { top: overflow.top - rect.height - preventedOffsets.y, right: overflow.right - rect.width + preventedOffsets.x, bottom: overflow.bottom - rect.height + preventedOffsets.y, left: overflow.left - rect.width - preventedOffsets.x }; } function isAnySideFullyClipped(overflow) { return [top, right, bottom, left].some(function(side) { return overflow[side] >= 0; }); } function hide(_ref) { var state = _ref.state, name = _ref.name; var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var preventedOffsets = state.modifiersData.preventOverflow; var referenceOverflow = detectOverflow(state, { elementContext: "reference" }); var popperAltOverflow = detectOverflow(state, { altBoundary: true }); var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); state.modifiersData[name] = { referenceClippingOffsets, popperEscapeOffsets, isReferenceHidden, hasPopperEscaped }; state.attributes.popper = Object.assign({}, state.attributes.popper, { "data-popper-reference-hidden": isReferenceHidden, "data-popper-escaped": hasPopperEscaped }); } var hide_default = { name: "hide", enabled: true, phase: "main", requiresIfExists: ["preventOverflow"], fn: hide }; // node_modules/@popperjs/core/lib/modifiers/offset.js function distanceAndSkiddingToXY(placement, rects, offset2) { var basePlacement = getBasePlacement(placement); var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, { placement })) : offset2, skidding = _ref[0], distance = _ref[1]; skidding = skidding || 0; distance = (distance || 0) * invertDistance; return [left, right].indexOf(basePlacement) >= 0 ? { x: distance, y: skidding } : { x: skidding, y: distance }; } function offset(_ref2) { var state = _ref2.state, options2 = _ref2.options, name = _ref2.name; var _options$offset = options2.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset; var data = placements.reduce(function(acc, placement) { acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2); return acc; }, {}); var _data$state$placement = data[state.placement], x3 = _data$state$placement.x, y4 = _data$state$placement.y; if (state.modifiersData.popperOffsets != null) { state.modifiersData.popperOffsets.x += x3; state.modifiersData.popperOffsets.y += y4; } state.modifiersData[name] = data; } var offset_default = { name: "offset", enabled: true, phase: "main", requires: ["popperOffsets"], fn: offset }; // node_modules/@popperjs/core/lib/modifiers/popperOffsets.js function popperOffsets(_ref) { var state = _ref.state, name = _ref.name; state.modifiersData[name] = computeOffsets({ reference: state.rects.reference, element: state.rects.popper, strategy: "absolute", placement: state.placement }); } var popperOffsets_default = { name: "popperOffsets", enabled: true, phase: "read", fn: popperOffsets, data: {} }; // node_modules/@popperjs/core/lib/utils/getAltAxis.js function getAltAxis(axis) { return axis === "x" ? "y" : "x"; } // node_modules/@popperjs/core/lib/modifiers/preventOverflow.js function preventOverflow(_ref) { var state = _ref.state, options2 = _ref.options, name = _ref.name; var _options$mainAxis = options2.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options2.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options2.boundary, rootBoundary = options2.rootBoundary, altBoundary = options2.altBoundary, padding = options2.padding, _options$tether = options2.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options2.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; var overflow = detectOverflow(state, { boundary, rootBoundary, padding, altBoundary }); var basePlacement = getBasePlacement(state.placement); var variation = getVariation(state.placement); var isBasePlacement = !variation; var mainAxis = getMainAxisFromPlacement(basePlacement); var altAxis = getAltAxis(mainAxis); var popperOffsets2 = state.modifiersData.popperOffsets; var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { placement: state.placement })) : tetherOffset; var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { mainAxis: tetherOffsetValue, altAxis: tetherOffsetValue } : Object.assign({ mainAxis: 0, altAxis: 0 }, tetherOffsetValue); var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; var data = { x: 0, y: 0 }; if (!popperOffsets2) { return; } if (checkMainAxis) { var _offsetModifierState$; var mainSide = mainAxis === "y" ? top : left; var altSide = mainAxis === "y" ? bottom : right; var len = mainAxis === "y" ? "height" : "width"; var offset2 = popperOffsets2[mainAxis]; var min2 = offset2 + overflow[mainSide]; var max2 = offset2 - overflow[altSide]; var additive = tether ? -popperRect[len] / 2 : 0; var minLen = variation === start ? referenceRect[len] : popperRect[len]; var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; var arrowElement = state.elements.arrow; var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { width: 0, height: 0 }; var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); var arrowPaddingMin = arrowPaddingObject[mainSide]; var arrowPaddingMax = arrowPaddingObject[altSide]; var arrowLen = within(0, referenceRect[len], arrowRect[len]); var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset; var tetherMax = offset2 + maxOffset - offsetModifierValue; var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2); popperOffsets2[mainAxis] = preventedOffset; data[mainAxis] = preventedOffset - offset2; } if (checkAltAxis) { var _offsetModifierState$2; var _mainSide = mainAxis === "x" ? top : left; var _altSide = mainAxis === "x" ? bottom : right; var _offset = popperOffsets2[altAxis]; var _len = altAxis === "y" ? "height" : "width"; var _min = _offset + overflow[_mainSide]; var _max = _offset - overflow[_altSide]; var isOriginSide = [top, left].indexOf(basePlacement) !== -1; var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); popperOffsets2[altAxis] = _preventedOffset; data[altAxis] = _preventedOffset - _offset; } state.modifiersData[name] = data; } var preventOverflow_default = { name: "preventOverflow", enabled: true, phase: "main", fn: preventOverflow, requiresIfExists: ["offset"] }; // node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js function getHTMLElementScroll(element) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; } // node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js function getNodeScroll(node) { if (node === getWindow(node) || !isHTMLElement(node)) { return getWindowScroll(node); } else { return getHTMLElementScroll(node); } } // node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js function isElementScaled(element) { var rect = element.getBoundingClientRect(); var scaleX = round(rect.width) / element.offsetWidth || 1; var scaleY = round(rect.height) / element.offsetHeight || 1; return scaleX !== 1 || scaleY !== 1; } function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { if (isFixed === void 0) { isFixed = false; } var isOffsetParentAnElement = isHTMLElement(offsetParent); var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); var documentElement = getDocumentElement(offsetParent); var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); var scroll = { scrollLeft: 0, scrollTop: 0 }; var offsets = { x: 0, y: 0 }; if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== "body" || // https://github.com/popperjs/popper-core/issues/1078 isScrollParent(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isHTMLElement(offsetParent)) { offsets = getBoundingClientRect(offsetParent, true); offsets.x += offsetParent.clientLeft; offsets.y += offsetParent.clientTop; } else if (documentElement) { offsets.x = getWindowScrollBarX(documentElement); } } return { x: rect.left + scroll.scrollLeft - offsets.x, y: rect.top + scroll.scrollTop - offsets.y, width: rect.width, height: rect.height }; } // node_modules/@popperjs/core/lib/utils/orderModifiers.js function order(modifiers) { var map = /* @__PURE__ */ new Map(); var visited = /* @__PURE__ */ new Set(); var result = []; modifiers.forEach(function(modifier) { map.set(modifier.name, modifier); }); function sort(modifier) { visited.add(modifier.name); var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); requires.forEach(function(dep) { if (!visited.has(dep)) { var depModifier = map.get(dep); if (depModifier) { sort(depModifier); } } }); result.push(modifier); } modifiers.forEach(function(modifier) { if (!visited.has(modifier.name)) { sort(modifier); } }); return result; } function orderModifiers(modifiers) { var orderedModifiers = order(modifiers); return modifierPhases.reduce(function(acc, phase) { return acc.concat(orderedModifiers.filter(function(modifier) { return modifier.phase === phase; })); }, []); } // node_modules/@popperjs/core/lib/utils/debounce.js function debounce2(fn2) { var pending; return function() { if (!pending) { pending = new Promise(function(resolve) { Promise.resolve().then(function() { pending = void 0; resolve(fn2()); }); }); } return pending; }; } // node_modules/@popperjs/core/lib/utils/mergeByName.js function mergeByName(modifiers) { var merged = modifiers.reduce(function(merged2, current) { var existing = merged2[current.name]; merged2[current.name] = existing ? Object.assign({}, existing, current, { options: Object.assign({}, existing.options, current.options), data: Object.assign({}, existing.data, current.data) }) : current; return merged2; }, {}); return Object.keys(merged).map(function(key) { return merged[key]; }); } // node_modules/@popperjs/core/lib/createPopper.js var DEFAULT_OPTIONS = { placement: "bottom", modifiers: [], strategy: "absolute" }; function areValidElements() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return !args.some(function(element) { return !(element && typeof element.getBoundingClientRect === "function"); }); } function popperGenerator(generatorOptions) { if (generatorOptions === void 0) { generatorOptions = {}; } var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions8 = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; return function createPopper2(reference2, popper2, options2) { if (options2 === void 0) { options2 = defaultOptions8; } var state = { placement: "bottom", orderedModifiers: [], options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions8), modifiersData: {}, elements: { reference: reference2, popper: popper2 }, attributes: {}, styles: {} }; var effectCleanupFns = []; var isDestroyed = false; var instance = { state, setOptions: function setOptions2(setOptionsAction) { var options3 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; cleanupModifierEffects(); state.options = Object.assign({}, defaultOptions8, state.options, options3); state.scrollParents = { reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], popper: listScrollParents(popper2) }; var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); state.orderedModifiers = orderedModifiers.filter(function(m4) { return m4.enabled; }); runModifierEffects(); return instance.update(); }, // Sync update – it will always be executed, even if not necessary. This // is useful for low frequency updates where sync behavior simplifies the // logic. // For high frequency updates (e.g. `resize` and `scroll` events), always // prefer the async Popper#update method forceUpdate: function forceUpdate() { if (isDestroyed) { return; } var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; if (!areValidElements(reference3, popper3)) { return; } state.rects = { reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), popper: getLayoutRect(popper3) }; state.reset = false; state.placement = state.options.placement; state.orderedModifiers.forEach(function(modifier) { return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); }); for (var index = 0; index < state.orderedModifiers.length; index++) { if (state.reset === true) { state.reset = false; index = -1; continue; } var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; if (typeof fn2 === "function") { state = fn2({ state, options: _options, name, instance }) || state; } } }, // Async and optimistically optimized update – it will not be executed if // not necessary (debounced to run at most once-per-tick) update: debounce2(function() { return new Promise(function(resolve) { instance.forceUpdate(); resolve(state); }); }), destroy: function destroy() { cleanupModifierEffects(); isDestroyed = true; } }; if (!areValidElements(reference2, popper2)) { return instance; } instance.setOptions(options2).then(function(state2) { if (!isDestroyed && options2.onFirstUpdate) { options2.onFirstUpdate(state2); } }); function runModifierEffects() { state.orderedModifiers.forEach(function(_ref) { var name = _ref.name, _ref$options = _ref.options, options3 = _ref$options === void 0 ? {} : _ref$options, effect4 = _ref.effect; if (typeof effect4 === "function") { var cleanupFn = effect4({ state, name, instance, options: options3 }); var noopFn = function noopFn2() { }; effectCleanupFns.push(cleanupFn || noopFn); } }); } function cleanupModifierEffects() { effectCleanupFns.forEach(function(fn2) { return fn2(); }); effectCleanupFns = []; } return instance; }; } // node_modules/@popperjs/core/lib/popper.js var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default]; var createPopper = /* @__PURE__ */ popperGenerator({ defaultModifiers }); // src/js/controllers/resource_drop_down_controller.js var resource_drop_down_controller_default = class extends Controller { static targets = ["trigger", "menu"]; connect() { this.visible = false; this.initialized = false; this.options = { placement: "bottom", triggerType: "click", offsetSkidding: 0, offsetDistance: 10, delay: 300, ignoreClickOutsideClass: false }; this.init(); } init() { if (this.triggerTarget && this.menuTarget && !this.initialized) { this.popperInstance = createPopper(this.triggerTarget, this.menuTarget, { placement: this.options.placement, modifiers: [ { name: "offset", options: { offset: [this.options.offsetSkidding, this.options.offsetDistance] } } ] }); this.setupEventListeners(); this.initialized = true; } } disconnect() { if (this.initialized) { if (this.options.triggerType === "click") { this.triggerTarget.removeEventListener("click", this.clickHandler); } if (this.options.triggerType === "hover") { this.triggerTarget.removeEventListener("mouseenter", this.hoverShowTriggerHandler); this.menuTarget.removeEventListener("mouseenter", this.hoverShowMenuHandler); this.triggerTarget.removeEventListener("mouseleave", this.hoverHideHandler); this.menuTarget.removeEventListener("mouseleave", this.hoverHideHandler); } this.removeClickOutsideListener(); this.popperInstance.destroy(); this.initialized = false; } } setupEventListeners() { this.clickHandler = this.toggle.bind(this); this.hoverShowTriggerHandler = (ev) => { if (ev.type === "click") { this.toggle(); } else { setTimeout(() => { this.show(); }, this.options.delay); } }; this.hoverShowMenuHandler = () => { this.show(); }; this.hoverHideHandler = () => { setTimeout(() => { if (!this.menuTarget.matches(":hover")) { this.hide(); } }, this.options.delay); }; if (this.options.triggerType === "click") { this.triggerTarget.addEventListener("click", this.clickHandler); } else if (this.options.triggerType === "hover") { this.triggerTarget.addEventListener("mouseenter", this.hoverShowTriggerHandler); this.menuTarget.addEventListener("mouseenter", this.hoverShowMenuHandler); this.triggerTarget.addEventListener("mouseleave", this.hoverHideHandler); this.menuTarget.addEventListener("mouseleave", this.hoverHideHandler); } } setupClickOutsideListener() { this.clickOutsideHandler = (ev) => { const clickedEl = ev.target; const ignoreClickOutsideClass = this.options.ignoreClickOutsideClass; let isIgnored = false; if (ignoreClickOutsideClass) { const ignoredEls = document.querySelectorAll(`.${ignoreClickOutsideClass}`); ignoredEls.forEach((el) => { if (el.contains(clickedEl)) { isIgnored = true; return; } }); } if (clickedEl !== this.menuTarget && !this.menuTarget.contains(clickedEl) && !this.triggerTarget.contains(clickedEl) && !isIgnored && this.visible) { this.hide(); } }; document.body.addEventListener("click", this.clickOutsideHandler, true); } removeClickOutsideListener() { if (this.clickOutsideHandler) { document.body.removeEventListener("click", this.clickOutsideHandler, true); } } toggle() { if (this.visible) { this.hide(); } else { this.show(); } } show() { this.menuTarget.classList.remove("hidden"); this.menuTarget.classList.add("block"); this.menuTarget.removeAttribute("aria-hidden"); this.popperInstance.setOptions((options2) => ({ ...options2, modifiers: [ ...options2.modifiers, { name: "eventListeners", enabled: true } ] })); this.setupClickOutsideListener(); this.popperInstance.update(); this.visible = true; } hide() { this.menuTarget.classList.remove("block"); this.menuTarget.classList.add("hidden"); this.menuTarget.setAttribute("aria-hidden", "true"); this.popperInstance.setOptions((options2) => ({ ...options2, modifiers: [ ...options2.modifiers, { name: "eventListeners", enabled: false } ] })); this.removeClickOutsideListener(); this.visible = false; } }; // src/js/controllers/resource_collapse_controller.js var resource_collapse_controller_default = class extends Controller { static targets = ["trigger", "menu"]; connect() { if (!this.element.hasAttribute("data-visible")) { this.element.setAttribute("data-visible", "false"); } this.#updateState(); } toggle() { const isVisible = this.element.getAttribute("data-visible") === "true"; this.element.setAttribute("data-visible", (!isVisible).toString()); this.#updateState(); } #updateState() { const isVisible = this.element.getAttribute("data-visible") === "true"; if (isVisible) { this.menuTarget.classList.remove("hidden"); this.triggerTarget.setAttribute("aria-expanded", "true"); this.dispatch("expand"); } else { this.menuTarget.classList.add("hidden"); this.triggerTarget.setAttribute("aria-expanded", "false"); this.dispatch("collapse"); } } }; // src/js/controllers/resource_dismiss_controller.js var resource_dismiss_controller_default = class extends Controller { static values = { after: Number }; connect() { if (this.hasAfterValue && this.afterValue > 0) { this.autoDismissTimeout = setTimeout(() => { this.dismiss(); this.autoDismissTimeout = null; }, this.afterValue); } } disconnect() { if (this.autoDismissTimeout) clearTimeout(this.autoDismissTimeout); this.autoDismissTimeout = null; } dismiss() { this.element.remove(); } }; // src/js/controllers/frame_navigator_controller.js var frame_navigator_controller_default = class extends Controller { static targets = ["frame", "refreshButton", "backButton", "homeButton", "maximizeLink"]; connect() { this.#loadingStarted(); this.srcHistory = []; this.originalFrameSrc = this.frameTarget.src; if (this.hasRefreshButtonTarget) { this.refreshButtonTarget.style.display = ""; this.refreshButtonClicked = this.refreshButtonClicked.bind(this); this.refreshButtonTarget.addEventListener("click", this.refreshButtonClicked); } if (this.hasBackButtonTarget) { this.backButtonClicked = this.backButtonClicked.bind(this); this.backButtonTarget.addEventListener("click", this.backButtonClicked); } if (this.hasHomeButtonTarget) { this.homeButtonClicked = this.homeButtonClicked.bind(this); this.homeButtonTarget.addEventListener("click", this.homeButtonClicked); } this.frameLoaded = this.frameLoaded.bind(this); this.frameTarget.addEventListener("turbo:frame-load", this.frameLoaded); this.frameLoading = this.frameLoading.bind(this); this.frameTarget.addEventListener("turbo:click", this.frameLoading); this.frameTarget.addEventListener("turbo:submit-start", this.frameLoading); this.frameFailed = this.frameFailed.bind(this); this.frameTarget.addEventListener("turbo:fetch-request-error", this.frameFailed); } disconnect() { if (this.hasRefreshButtonTarget) this.refreshButtonTarget.removeEventListener("click", this.refreshButtonClicked); if (this.hasBackButtonTarget) this.backButtonTarget.removeEventListener("click", this.backButtonClicked); if (this.hasHomeButtonTarget) this.homeButtonTarget.removeEventListener("click", this.homeButtonClicked); this.frameTarget.removeEventListener("turbo:frame-load", this.frameLoaded); this.frameTarget.removeEventListener("turbo:click", this.frameLoading); this.frameTarget.removeEventListener("turbo:submit-start", this.frameLoading); this.frameTarget.removeEventListener("turbo:fetch-request-error", this.frameFailed); } frameLoading(event) { this.#loadingStarted(); } frameFailed(event) { this.#loadingStopped(); } frameLoaded(event) { this.#loadingStopped(); let src = event.target.src; this.#notifySrcChanged(src); } refreshButtonClicked(event) { this.frameLoading(null); this.frameTarget.reload(); } backButtonClicked(event) { this.frameLoading(null); this.srcHistory.pop(); this.frameTarget.src = this.currentSrc; } homeButtonClicked(event) { this.frameLoading(null); this.frameTarget.src = this.originalFrameSrc; } get currentSrc() { return this.srcHistory[this.srcHistory.length - 1]; } #notifySrcChanged(src) { if (src == this.currentSrc) { } else if (src == this.originalFrameSrc) this.srcHistory = [src]; else this.srcHistory.push(src); this.#updateNavigationButtonsDisplay(); if (this.hasMaximizeLinkTarget) this.maximizeLinkTarget.href = src; } #loadingStarted() { if (this.hasRefreshButtonTarget) this.refreshButtonTarget.classList.add("motion-safe:animate-spin"); this.frameTarget.classList.add("motion-safe:animate-pulse"); } #loadingStopped() { if (this.hasRefreshButtonTarget) this.refreshButtonTarget.classList.remove("motion-safe:animate-spin"); this.frameTarget.classList.remove("motion-safe:animate-pulse"); } #updateNavigationButtonsDisplay() { if (this.hasHomeButtonTarget) { this.homeButtonTarget.style.display = this.srcHistory.length > 2 ? "" : "none"; } if (this.hasBackButtonTarget) { this.backButtonTarget.style.display = this.srcHistory.length > 1 ? "" : "none"; } } }; // src/js/controllers/color_mode_controller.js var color_mode_controller_default = class extends Controller { // static targets = ["trigger", "menu"] connect() { this.updateColorMode(); } disconnect() { } updateColorMode() { if (localStorage.theme === "dark" || !("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches) { document.documentElement.classList.add("dark"); } else { document.documentElement.classList.remove("dark"); } } setLightColorMode() { localStorage.theme = "light"; this.updateColorMode(); } setDarkColorMode() { localStorage.theme = "dark"; this.updateColorMode(); } setSystemColorMode() { localStorage.removeItem("theme"); this.updateColorMode(); } }; // node_modules/dompurify/dist/purify.es.mjs var { entries, setPrototypeOf, isFrozen, getPrototypeOf, getOwnPropertyDescriptor } = Object; var { freeze, seal, create } = Object; var { apply, construct } = typeof Reflect !== "undefined" && Reflect; if (!freeze) { freeze = function freeze2(x3) { return x3; }; } if (!seal) { seal = function seal2(x3) { return x3; }; } if (!apply) { apply = function apply2(fun, thisValue, args) { return fun.apply(thisValue, args); }; } if (!construct) { construct = function construct2(Func, args) { return new Func(...args); }; } var arrayForEach = unapply(Array.prototype.forEach); var arrayPop = unapply(Array.prototype.pop); var arrayPush = unapply(Array.prototype.push); var stringToLowerCase = unapply(String.prototype.toLowerCase); var stringToString = unapply(String.prototype.toString); var stringMatch = unapply(String.prototype.match); var stringReplace = unapply(String.prototype.replace); var stringIndexOf = unapply(String.prototype.indexOf); var stringTrim = unapply(String.prototype.trim); var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); var regExpTest = unapply(RegExp.prototype.test); var typeErrorCreate = unconstruct(TypeError); function unapply(func) { return function(thisArg) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return apply(func, thisArg, args); }; } function unconstruct(func) { return function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return construct(func, args); }; } function addToSet(set, array) { let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; if (setPrototypeOf) { setPrototypeOf(set, null); } let l4 = array.length; while (l4--) { let element = array[l4]; if (typeof element === "string") { const lcElement = transformCaseFunc(element); if (lcElement !== element) { if (!isFrozen(array)) { array[l4] = lcElement; } element = lcElement; } } set[element] = true; } return set; } function cleanArray(array) { for (let index = 0; index < array.length; index++) { const isPropertyExist = objectHasOwnProperty(array, index); if (!isPropertyExist) { array[index] = null; } } return array; } function clone(object) { const newObject = create(null); for (const [property, value] of entries(object)) { const isPropertyExist = objectHasOwnProperty(object, property); if (isPropertyExist) { if (Array.isArray(value)) { newObject[property] = cleanArray(value); } else if (value && typeof value === "object" && value.constructor === Object) { newObject[property] = clone(value); } else { newObject[property] = value; } } } return newObject; } function lookupGetter(object, prop) { while (object !== null) { const desc = getOwnPropertyDescriptor(object, prop); if (desc) { if (desc.get) { return unapply(desc.get); } if (typeof desc.value === "function") { return unapply(desc.value); } } object = getPrototypeOf(object); } function fallbackValue() { return null; } return fallbackValue; } var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]); var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]); var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]); var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]); var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]); var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]); var text = freeze(["#text"]); var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]); var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]); var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]); var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]); var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm); var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); var ARIA_ATTR = seal(/^aria-[\-\w]+$/); var IS_ALLOWED_URI = seal( /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape ); var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); var ATTR_WHITESPACE = seal( /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex ); var DOCTYPE_NAME = seal(/^html$/i); var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); var EXPRESSIONS = /* @__PURE__ */ Object.freeze({ __proto__: null, ARIA_ATTR, ATTR_WHITESPACE, CUSTOM_ELEMENT, DATA_ATTR, DOCTYPE_NAME, ERB_EXPR, IS_ALLOWED_URI, IS_SCRIPT_OR_DATA, MUSTACHE_EXPR, TMPLIT_EXPR }); var NODE_TYPE = { element: 1, attribute: 2, text: 3, cdataSection: 4, entityReference: 5, // Deprecated entityNode: 6, // Deprecated progressingInstruction: 7, comment: 8, document: 9, documentType: 10, documentFragment: 11, notation: 12 // Deprecated }; var getGlobal = function getGlobal2() { return typeof window === "undefined" ? null : window; }; var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) { if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") { return null; } let suffix = null; const ATTR_NAME = "data-tt-policy-suffix"; if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { suffix = purifyHostElement.getAttribute(ATTR_NAME); } const policyName = "dompurify" + (suffix ? "#" + suffix : ""); try { return trustedTypes.createPolicy(policyName, { createHTML(html3) { return html3; }, createScriptURL(scriptUrl) { return scriptUrl; } }); } catch (_3) { console.warn("TrustedTypes policy " + policyName + " could not be created."); return null; } }; var _createHooksMap = function _createHooksMap2() { return { afterSanitizeAttributes: [], afterSanitizeElements: [], afterSanitizeShadowDOM: [], beforeSanitizeAttributes: [], beforeSanitizeElements: [], beforeSanitizeShadowDOM: [], uponSanitizeAttribute: [], uponSanitizeElement: [], uponSanitizeShadowNode: [] }; }; function createDOMPurify() { let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); const DOMPurify = (root) => createDOMPurify(root); DOMPurify.version = "3.2.2"; DOMPurify.removed = []; if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document) { DOMPurify.isSupported = false; return DOMPurify; } let { document: document2 } = window2; const originalDocument = document2; const currentScript = originalDocument.currentScript; const { DocumentFragment, HTMLTemplateElement: HTMLTemplateElement2, Node: Node2, Element: Element2, NodeFilter, NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap, HTMLFormElement: HTMLFormElement2, DOMParser: DOMParser2, trustedTypes } = window2; const ElementPrototype = Element2.prototype; const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); const remove = lookupGetter(ElementPrototype, "remove"); const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); const getParentNode2 = lookupGetter(ElementPrototype, "parentNode"); if (typeof HTMLTemplateElement2 === "function") { const template = document2.createElement("template"); if (template.content && template.content.ownerDocument) { document2 = template.content.ownerDocument; } } let trustedTypesPolicy; let emptyHTML = ""; const { implementation, createNodeIterator, createDocumentFragment: createDocumentFragment2, getElementsByTagName } = document2; const { importNode } = originalDocument; let hooks = _createHooksMap(); DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode2 === "function" && implementation && implementation.createHTMLDocument !== void 0; const { MUSTACHE_EXPR: MUSTACHE_EXPR2, ERB_EXPR: ERB_EXPR2, TMPLIT_EXPR: TMPLIT_EXPR2, DATA_ATTR: DATA_ATTR2, ARIA_ATTR: ARIA_ATTR2, IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2, ATTR_WHITESPACE: ATTR_WHITESPACE2, CUSTOM_ELEMENT: CUSTOM_ELEMENT2 } = EXPRESSIONS; let { IS_ALLOWED_URI: IS_ALLOWED_URI$1 } = EXPRESSIONS; let ALLOWED_TAGS = null; const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); let ALLOWED_ATTR = null; const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { tagNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, allowCustomizedBuiltInElements: { writable: true, configurable: false, enumerable: true, value: false } })); let FORBID_TAGS = null; let FORBID_ATTR = null; let ALLOW_ARIA_ATTR = true; let ALLOW_DATA_ATTR = true; let ALLOW_UNKNOWN_PROTOCOLS = false; let ALLOW_SELF_CLOSE_IN_ATTR = true; let SAFE_FOR_TEMPLATES = false; let SAFE_FOR_XML = true; let WHOLE_DOCUMENT = false; let SET_CONFIG = false; let FORCE_BODY = false; let RETURN_DOM = false; let RETURN_DOM_FRAGMENT = false; let RETURN_TRUSTED_TYPE = false; let SANITIZE_DOM = true; let SANITIZE_NAMED_PROPS = false; const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; let KEEP_CONTENT = true; let IN_PLACE = false; let USE_PROFILES = {}; let FORBID_CONTENTS = null; const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]); let DATA_URI_TAGS = null; const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]); let URI_SAFE_ATTRIBUTES = null; const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]); const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; let NAMESPACE = HTML_NAMESPACE; let IS_EMPTY_INPUT = false; let ALLOWED_NAMESPACES = null; const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]); let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]); const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]); let PARSER_MEDIA_TYPE = null; const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"]; const DEFAULT_PARSER_MEDIA_TYPE = "text/html"; let transformCaseFunc = null; let CONFIG = null; const formElement = document2.createElement("form"); const isRegexOrFunction = function isRegexOrFunction2(testValue) { return testValue instanceof RegExp || testValue instanceof Function; }; const _parseConfig = function _parseConfig2() { let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; if (CONFIG && CONFIG === cfg) { return; } if (!cfg || typeof cfg !== "object") { cfg = {}; } cfg = clone(cfg); PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase; ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {}; FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {}; USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false; ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; RETURN_DOM = cfg.RETURN_DOM || false; RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; FORCE_BODY = cfg.FORCE_BODY || false; SANITIZE_DOM = cfg.SANITIZE_DOM !== false; SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; KEEP_CONTENT = cfg.KEEP_CONTENT !== false; IN_PLACE = cfg.IN_PLACE || false; IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; } if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; } if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") { CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; } if (SAFE_FOR_TEMPLATES) { ALLOW_DATA_ATTR = false; } if (RETURN_DOM_FRAGMENT) { RETURN_DOM = true; } if (USE_PROFILES) { ALLOWED_TAGS = addToSet({}, text); ALLOWED_ATTR = []; if (USE_PROFILES.html === true) { addToSet(ALLOWED_TAGS, html$1); addToSet(ALLOWED_ATTR, html); } if (USE_PROFILES.svg === true) { addToSet(ALLOWED_TAGS, svg$1); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.svgFilters === true) { addToSet(ALLOWED_TAGS, svgFilters); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.mathMl === true) { addToSet(ALLOWED_TAGS, mathMl$1); addToSet(ALLOWED_ATTR, mathMl); addToSet(ALLOWED_ATTR, xml); } } if (cfg.ADD_TAGS) { if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { ALLOWED_TAGS = clone(ALLOWED_TAGS); } addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); } if (cfg.ADD_ATTR) { if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { ALLOWED_ATTR = clone(ALLOWED_ATTR); } addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); } if (cfg.ADD_URI_SAFE_ATTR) { addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); } if (cfg.FORBID_CONTENTS) { if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { FORBID_CONTENTS = clone(FORBID_CONTENTS); } addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); } if (KEEP_CONTENT) { ALLOWED_TAGS["#text"] = true; } if (WHOLE_DOCUMENT) { addToSet(ALLOWED_TAGS, ["html", "head", "body"]); } if (ALLOWED_TAGS.table) { addToSet(ALLOWED_TAGS, ["tbody"]); delete FORBID_TAGS.tbody; } if (cfg.TRUSTED_TYPES_POLICY) { if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") { throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); } if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") { throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); } trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; emptyHTML = trustedTypesPolicy.createHTML(""); } else { if (trustedTypesPolicy === void 0) { trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); } if (trustedTypesPolicy !== null && typeof emptyHTML === "string") { emptyHTML = trustedTypesPolicy.createHTML(""); } } if (freeze) { freeze(cfg); } CONFIG = cfg; }; const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); const _checkValidNamespace = function _checkValidNamespace2(element) { let parent = getParentNode2(element); if (!parent || !parent.tagName) { parent = { namespaceURI: NAMESPACE, tagName: "template" }; } const tagName = stringToLowerCase(element.tagName); const parentTagName = stringToLowerCase(parent.tagName); if (!ALLOWED_NAMESPACES[element.namespaceURI]) { return false; } if (element.namespaceURI === SVG_NAMESPACE) { if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === "svg"; } if (parent.namespaceURI === MATHML_NAMESPACE) { return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); } return Boolean(ALL_SVG_TAGS[tagName]); } if (element.namespaceURI === MATHML_NAMESPACE) { if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === "math"; } if (parent.namespaceURI === SVG_NAMESPACE) { return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName]; } return Boolean(ALL_MATHML_TAGS[tagName]); } if (element.namespaceURI === HTML_NAMESPACE) { if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { return false; } if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { return false; } return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); } if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) { return true; } return false; }; const _forceRemove = function _forceRemove2(node) { arrayPush(DOMPurify.removed, { element: node }); try { getParentNode2(node).removeChild(node); } catch (_3) { remove(node); } }; const _removeAttribute = function _removeAttribute2(name, element) { try { arrayPush(DOMPurify.removed, { attribute: element.getAttributeNode(name), from: element }); } catch (_3) { arrayPush(DOMPurify.removed, { attribute: null, from: element }); } element.removeAttribute(name); if (name === "is") { if (RETURN_DOM || RETURN_DOM_FRAGMENT) { try { _forceRemove(element); } catch (_3) { } } else { try { element.setAttribute(name, ""); } catch (_3) { } } } }; const _initDocument = function _initDocument2(dirty) { let doc = null; let leadingWhitespace = null; if (FORCE_BODY) { dirty = "" + dirty; } else { const matches = stringMatch(dirty, /^[\r\n\t ]+/); leadingWhitespace = matches && matches[0]; } if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) { dirty = '' + dirty + ""; } const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; if (NAMESPACE === HTML_NAMESPACE) { try { doc = new DOMParser2().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); } catch (_3) { } } if (!doc || !doc.documentElement) { doc = implementation.createDocument(NAMESPACE, "template", null); try { doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; } catch (_3) { } } const body = doc.body || doc.documentElement; if (dirty && leadingWhitespace) { body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null); } if (NAMESPACE === HTML_NAMESPACE) { return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0]; } return WHOLE_DOCUMENT ? doc.documentElement : body; }; const _createNodeIterator = function _createNodeIterator2(root) { return createNodeIterator.call( root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null ); }; const _isClobbered = function _isClobbered2(element) { return element instanceof HTMLFormElement2 && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function"); }; const _isNode = function _isNode2(value) { return typeof Node2 === "function" && value instanceof Node2; }; function _executeHooks(hooks2, currentNode, data) { arrayForEach(hooks2, (hook) => { hook.call(DOMPurify, currentNode, data, CONFIG); }); } const _sanitizeElements = function _sanitizeElements2(currentNode) { let content = null; _executeHooks(hooks.beforeSanitizeElements, currentNode, null); if (_isClobbered(currentNode)) { _forceRemove(currentNode); return true; } const tagName = transformCaseFunc(currentNode.nodeName); _executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: ALLOWED_TAGS }); if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { _forceRemove(currentNode); return true; } if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { _forceRemove(currentNode); return true; } if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { _forceRemove(currentNode); return true; } if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { return false; } if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { return false; } } if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { const parentNode = getParentNode2(currentNode) || currentNode.parentNode; const childNodes = getChildNodes(currentNode) || currentNode.childNodes; if (childNodes && parentNode) { const childCount = childNodes.length; for (let i4 = childCount - 1; i4 >= 0; --i4) { const childClone = cloneNode(childNodes[i4], true); childClone.__removalCount = (currentNode.__removalCount || 0) + 1; parentNode.insertBefore(childClone, getNextSibling(currentNode)); } } } _forceRemove(currentNode); return true; } if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) { _forceRemove(currentNode); return true; } if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { _forceRemove(currentNode); return true; } if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { content = currentNode.textContent; arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { content = stringReplace(content, expr, " "); }); if (currentNode.textContent !== content) { arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() }); currentNode.textContent = content; } } _executeHooks(hooks.afterSanitizeElements, currentNode, null); return false; }; const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) { if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) { return false; } if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)) ) ; else { return false; } } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ; else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ; else if (value) { return false; } else ; return true; }; const _isBasicCustomElement = function _isBasicCustomElement2(tagName) { return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2); }; const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) { _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); const { attributes } = currentNode; if (!attributes) { return; } const hookEvent = { attrName: "", attrValue: "", keepAttr: true, allowedAttributes: ALLOWED_ATTR, forceKeepAttr: void 0 }; let l4 = attributes.length; while (l4--) { const attr = attributes[l4]; const { name, namespaceURI, value: attrValue } = attr; const lcName = transformCaseFunc(name); let value = name === "value" ? attrValue : stringTrim(attrValue); hookEvent.attrName = lcName; hookEvent.attrValue = value; hookEvent.keepAttr = true; hookEvent.forceKeepAttr = void 0; _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); value = hookEvent.attrValue; if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) { _removeAttribute(name, currentNode); value = SANITIZE_NAMED_PROPS_PREFIX + value; } if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title)/i, value)) { _removeAttribute(name, currentNode); continue; } if (hookEvent.forceKeepAttr) { continue; } _removeAttribute(name, currentNode); if (!hookEvent.keepAttr) { continue; } if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { _removeAttribute(name, currentNode); continue; } if (SAFE_FOR_TEMPLATES) { arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { value = stringReplace(value, expr, " "); }); } const lcTag = transformCaseFunc(currentNode.nodeName); if (!_isValidAttribute(lcTag, lcName, value)) { continue; } if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") { if (namespaceURI) ; else { switch (trustedTypes.getAttributeType(lcTag, lcName)) { case "TrustedHTML": { value = trustedTypesPolicy.createHTML(value); break; } case "TrustedScriptURL": { value = trustedTypesPolicy.createScriptURL(value); break; } } } } try { if (namespaceURI) { currentNode.setAttributeNS(namespaceURI, name, value); } else { currentNode.setAttribute(name, value); } if (_isClobbered(currentNode)) { _forceRemove(currentNode); } else { arrayPop(DOMPurify.removed); } } catch (_3) { } } _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); }; const _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) { let shadowNode = null; const shadowIterator = _createNodeIterator(fragment); _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); while (shadowNode = shadowIterator.nextNode()) { _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); if (_sanitizeElements(shadowNode)) { continue; } if (shadowNode.content instanceof DocumentFragment) { _sanitizeShadowDOM2(shadowNode.content); } _sanitizeAttributes(shadowNode); } _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); }; DOMPurify.sanitize = function(dirty) { let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; let body = null; let importedNode = null; let currentNode = null; let returnNode = null; IS_EMPTY_INPUT = !dirty; if (IS_EMPTY_INPUT) { dirty = ""; } if (typeof dirty !== "string" && !_isNode(dirty)) { if (typeof dirty.toString === "function") { dirty = dirty.toString(); if (typeof dirty !== "string") { throw typeErrorCreate("dirty is not a string, aborting"); } } else { throw typeErrorCreate("toString is not a function"); } } if (!DOMPurify.isSupported) { return dirty; } if (!SET_CONFIG) { _parseConfig(cfg); } DOMPurify.removed = []; if (typeof dirty === "string") { IN_PLACE = false; } if (IN_PLACE) { if (dirty.nodeName) { const tagName = transformCaseFunc(dirty.nodeName); if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place"); } } } else if (dirty instanceof Node2) { body = _initDocument(""); importedNode = body.ownerDocument.importNode(dirty, true); if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") { body = importedNode; } else if (importedNode.nodeName === "HTML") { body = importedNode; } else { body.appendChild(importedNode); } } else { if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes dirty.indexOf("<") === -1) { return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; } body = _initDocument(dirty); if (!body) { return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ""; } } if (body && FORCE_BODY) { _forceRemove(body.firstChild); } const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); while (currentNode = nodeIterator.nextNode()) { if (_sanitizeElements(currentNode)) { continue; } if (currentNode.content instanceof DocumentFragment) { _sanitizeShadowDOM(currentNode.content); } _sanitizeAttributes(currentNode); } if (IN_PLACE) { return dirty; } if (RETURN_DOM) { if (RETURN_DOM_FRAGMENT) { returnNode = createDocumentFragment2.call(body.ownerDocument); while (body.firstChild) { returnNode.appendChild(body.firstChild); } } else { returnNode = body; } if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { returnNode = importNode.call(originalDocument, returnNode, true); } return returnNode; } let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { serializedHTML = "\n" + serializedHTML; } if (SAFE_FOR_TEMPLATES) { arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { serializedHTML = stringReplace(serializedHTML, expr, " "); }); } return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; }; DOMPurify.setConfig = function() { let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; _parseConfig(cfg); SET_CONFIG = true; }; DOMPurify.clearConfig = function() { CONFIG = null; SET_CONFIG = false; }; DOMPurify.isValidAttribute = function(tag2, attr, value) { if (!CONFIG) { _parseConfig({}); } const lcTag = transformCaseFunc(tag2); const lcName = transformCaseFunc(attr); return _isValidAttribute(lcTag, lcName, value); }; DOMPurify.addHook = function(entryPoint, hookFunction) { if (typeof hookFunction !== "function") { return; } arrayPush(hooks[entryPoint], hookFunction); }; DOMPurify.removeHook = function(entryPoint) { return arrayPop(hooks[entryPoint]); }; DOMPurify.removeHooks = function(entryPoint) { hooks[entryPoint] = []; }; DOMPurify.removeAllHooks = function() { hooks = _createHooksMap(); }; return DOMPurify; } var purify = createDOMPurify(); // node_modules/marked/lib/marked.esm.js function _getDefaults() { return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null }; } var _defaults = _getDefaults(); function changeDefaults(newDefaults) { _defaults = newDefaults; } var noopTest = { exec: () => null }; function edit(regex, opt = "") { let source = typeof regex === "string" ? regex : regex.source; const obj = { replace: (name, val) => { let valSource = typeof val === "string" ? val : val.source; valSource = valSource.replace(other.caret, "$1"); source = source.replace(name, valSource); return obj; }, getRegex: () => { return new RegExp(source, opt); } }; return obj; } var other = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceTabs: /^\t+/, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] /, listReplaceTask: /^\[[ xX]\] +/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`), hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`), htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, "i") }; var newline = /^(?:[ \t]*(?:\n|$))+/; var blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; var fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; var hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; var heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; var bullet = /(?:[*+-]|\d{1,9}[.)])/; var lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex(); var _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; var blockText = /^[^\n]+/; var _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/; var def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(); var list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex(); var _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; var _comment = /|$))/; var html2 = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); var paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex(); var blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex(); var blockNormal = { blockquote, code: blockCode, def, fences, heading, hr, html: html2, lheading, list, newline, paragraph, table: noopTest, text: blockText }; var gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex(); var blockGfm = { ...blockNormal, table: gfmTable, paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex() }; var blockPedantic = { ...blockNormal, html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: noopTest, // fences not supported lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }; var escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; var inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; var br = /^( {2,}|\\)\n(?!\s*$)/; var inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g; var emStrongLDelim = edit(/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex(); var emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex(); var emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex(); var anyPunctuation = edit(/\\(punct)/, "gu").replace(/punct/g, _punctuation).getRegex(); var autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(); var _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex(); var tag = edit("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(); var _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; var link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(); var reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex(); var nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex(); var reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex(); var inlineNormal = { _backpedal: noopTest, // only used for GFM url anyPunctuation, autolink, blockSkip, br, code: inlineCode, del: noopTest, emStrongLDelim, emStrongRDelimAst, emStrongRDelimUnd, escape: escape$1, link, nolink, punctuation, reflink, reflinkSearch, tag, text: inlineText, url: noopTest }; var inlinePedantic = { ...inlineNormal, link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(), reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex() }; var inlineGfm = { ...inlineNormal, escape: edit(escape$1).replace("])", "~|])").getRegex(), url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/, text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">", '"': """, "'": "'" }; var getEscapeReplacement = (ch) => escapeReplacements[ch]; function escape2(html3, encode) { if (encode) { if (other.escapeTest.test(html3)) { return html3.replace(other.escapeReplace, getEscapeReplacement); } } else { if (other.escapeTestNoEncode.test(html3)) { return html3.replace(other.escapeReplaceNoEncode, getEscapeReplacement); } } return html3; } function cleanUrl(href) { try { href = encodeURI(href).replace(other.percentDecode, "%"); } catch { return null; } return href; } function splitCells(tableRow, count) { const row = tableRow.replace(other.findPipe, (match2, offset2, str) => { let escaped = false; let curr = offset2; while (--curr >= 0 && str[curr] === "\\") escaped = !escaped; if (escaped) { return "|"; } else { return " |"; } }), cells = row.split(other.splitPipe); let i4 = 0; if (!cells[0].trim()) { cells.shift(); } if (cells.length > 0 && !cells.at(-1)?.trim()) { cells.pop(); } if (count) { if (cells.length > count) { cells.splice(count); } else { while (cells.length < count) cells.push(""); } } for (; i4 < cells.length; i4++) { cells[i4] = cells[i4].trim().replace(other.slashPipe, "|"); } return cells; } function rtrim(str, c4, invert) { const l4 = str.length; if (l4 === 0) { return ""; } let suffLen = 0; while (suffLen < l4) { const currChar = str.charAt(l4 - suffLen - 1); if (currChar === c4 && !invert) { suffLen++; } else if (currChar !== c4 && invert) { suffLen++; } else { break; } } return str.slice(0, l4 - suffLen); } function findClosingBracket(str, b3) { if (str.indexOf(b3[1]) === -1) { return -1; } let level = 0; for (let i4 = 0; i4 < str.length; i4++) { if (str[i4] === "\\") { i4++; } else if (str[i4] === b3[0]) { level++; } else if (str[i4] === b3[1]) { level--; if (level < 0) { return i4; } } } return -1; } function outputLink(cap, link2, raw, lexer2, rules) { const href = link2.href; const title = link2.title || null; const text2 = cap[1].replace(rules.other.outputLinkReplace, "$1"); if (cap[0].charAt(0) !== "!") { lexer2.state.inLink = true; const token = { type: "link", raw, href, title, text: text2, tokens: lexer2.inlineTokens(text2) }; lexer2.state.inLink = false; return token; } return { type: "image", raw, href, title, text: text2 }; } function indentCodeCompensation(raw, text2, rules) { const matchIndentToCode = raw.match(rules.other.indentCodeCompensation); if (matchIndentToCode === null) { return text2; } const indentToCode = matchIndentToCode[1]; return text2.split("\n").map((node) => { const matchIndentInNode = node.match(rules.other.beginningSpace); if (matchIndentInNode === null) { return node; } const [indentInNode] = matchIndentInNode; if (indentInNode.length >= indentToCode.length) { return node.slice(indentToCode.length); } return node; }).join("\n"); } var _Tokenizer = class { options; rules; // set by the lexer lexer; // set by the lexer constructor(options2) { this.options = options2 || _defaults; } space(src) { const cap = this.rules.block.newline.exec(src); if (cap && cap[0].length > 0) { return { type: "space", raw: cap[0] }; } } code(src) { const cap = this.rules.block.code.exec(src); if (cap) { const text2 = cap[0].replace(this.rules.other.codeRemoveIndent, ""); return { type: "code", raw: cap[0], codeBlockStyle: "indented", text: !this.options.pedantic ? rtrim(text2, "\n") : text2 }; } } fences(src) { const cap = this.rules.block.fences.exec(src); if (cap) { const raw = cap[0]; const text2 = indentCodeCompensation(raw, cap[3] || "", this.rules); return { type: "code", raw, lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2], text: text2 }; } } heading(src) { const cap = this.rules.block.heading.exec(src); if (cap) { let text2 = cap[2].trim(); if (this.rules.other.endingHash.test(text2)) { const trimmed = rtrim(text2, "#"); if (this.options.pedantic) { text2 = trimmed.trim(); } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) { text2 = trimmed.trim(); } } return { type: "heading", raw: cap[0], depth: cap[1].length, text: text2, tokens: this.lexer.inline(text2) }; } } hr(src) { const cap = this.rules.block.hr.exec(src); if (cap) { return { type: "hr", raw: rtrim(cap[0], "\n") }; } } blockquote(src) { const cap = this.rules.block.blockquote.exec(src); if (cap) { let lines = rtrim(cap[0], "\n").split("\n"); let raw = ""; let text2 = ""; const tokens = []; while (lines.length > 0) { let inBlockquote = false; const currentLines = []; let i4; for (i4 = 0; i4 < lines.length; i4++) { if (this.rules.other.blockquoteStart.test(lines[i4])) { currentLines.push(lines[i4]); inBlockquote = true; } else if (!inBlockquote) { currentLines.push(lines[i4]); } else { break; } } lines = lines.slice(i4); const currentRaw = currentLines.join("\n"); const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, "\n $1").replace(this.rules.other.blockquoteSetextReplace2, ""); raw = raw ? `${raw} ${currentRaw}` : currentRaw; text2 = text2 ? `${text2} ${currentText}` : currentText; const top2 = this.lexer.state.top; this.lexer.state.top = true; this.lexer.blockTokens(currentText, tokens, true); this.lexer.state.top = top2; if (lines.length === 0) { break; } const lastToken = tokens.at(-1); if (lastToken?.type === "code") { break; } else if (lastToken?.type === "blockquote") { const oldToken = lastToken; const newText = oldToken.raw + "\n" + lines.join("\n"); const newToken = this.blockquote(newText); tokens[tokens.length - 1] = newToken; raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw; text2 = text2.substring(0, text2.length - oldToken.text.length) + newToken.text; break; } else if (lastToken?.type === "list") { const oldToken = lastToken; const newText = oldToken.raw + "\n" + lines.join("\n"); const newToken = this.list(newText); tokens[tokens.length - 1] = newToken; raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw; text2 = text2.substring(0, text2.length - oldToken.raw.length) + newToken.raw; lines = newText.substring(tokens.at(-1).raw.length).split("\n"); continue; } } return { type: "blockquote", raw, tokens, text: text2 }; } } list(src) { let cap = this.rules.block.list.exec(src); if (cap) { let bull = cap[1].trim(); const isordered = bull.length > 1; const list2 = { type: "list", raw: "", ordered: isordered, start: isordered ? +bull.slice(0, -1) : "", loose: false, items: [] }; bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; if (this.options.pedantic) { bull = isordered ? bull : "[*+-]"; } const itemRegex = this.rules.other.listItemRegex(bull); let endsWithBlankLine = false; while (src) { let endEarly = false; let raw = ""; let itemContents = ""; if (!(cap = itemRegex.exec(src))) { break; } if (this.rules.block.hr.test(src)) { break; } raw = cap[0]; src = src.substring(raw.length); let line = cap[2].split("\n", 1)[0].replace(this.rules.other.listReplaceTabs, (t4) => " ".repeat(3 * t4.length)); let nextLine = src.split("\n", 1)[0]; let blankLine = !line.trim(); let indent = 0; if (this.options.pedantic) { indent = 2; itemContents = line.trimStart(); } else if (blankLine) { indent = cap[1].length + 1; } else { indent = cap[2].search(this.rules.other.nonSpaceChar); indent = indent > 4 ? 1 : indent; itemContents = line.slice(indent); indent += cap[1].length; } if (blankLine && this.rules.other.blankLine.test(nextLine)) { raw += nextLine + "\n"; src = src.substring(nextLine.length + 1); endEarly = true; } if (!endEarly) { const nextBulletRegex = this.rules.other.nextBulletRegex(indent); const hrRegex = this.rules.other.hrRegex(indent); const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent); const headingBeginRegex = this.rules.other.headingBeginRegex(indent); const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); while (src) { const rawLine = src.split("\n", 1)[0]; let nextLineWithoutTabs; nextLine = rawLine; if (this.options.pedantic) { nextLine = nextLine.replace(this.rules.other.listReplaceNesting, " "); nextLineWithoutTabs = nextLine; } else { nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, " "); } if (fencesBeginRegex.test(nextLine)) { break; } if (headingBeginRegex.test(nextLine)) { break; } if (htmlBeginRegex.test(nextLine)) { break; } if (nextBulletRegex.test(nextLine)) { break; } if (hrRegex.test(nextLine)) { break; } if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { itemContents += "\n" + nextLineWithoutTabs.slice(indent); } else { if (blankLine) { break; } if (line.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4) { break; } if (fencesBeginRegex.test(line)) { break; } if (headingBeginRegex.test(line)) { break; } if (hrRegex.test(line)) { break; } itemContents += "\n" + nextLine; } if (!blankLine && !nextLine.trim()) { blankLine = true; } raw += rawLine + "\n"; src = src.substring(rawLine.length + 1); line = nextLineWithoutTabs.slice(indent); } } if (!list2.loose) { if (endsWithBlankLine) { list2.loose = true; } else if (this.rules.other.doubleBlankLine.test(raw)) { endsWithBlankLine = true; } } let istask = null; let ischecked; if (this.options.gfm) { istask = this.rules.other.listIsTask.exec(itemContents); if (istask) { ischecked = istask[0] !== "[ ] "; itemContents = itemContents.replace(this.rules.other.listReplaceTask, ""); } } list2.items.push({ type: "list_item", raw, task: !!istask, checked: ischecked, loose: false, text: itemContents, tokens: [] }); list2.raw += raw; } const lastItem = list2.items.at(-1); if (lastItem) { lastItem.raw = lastItem.raw.trimEnd(); lastItem.text = lastItem.text.trimEnd(); } list2.raw = list2.raw.trimEnd(); for (let i4 = 0; i4 < list2.items.length; i4++) { this.lexer.state.top = false; list2.items[i4].tokens = this.lexer.blockTokens(list2.items[i4].text, []); if (!list2.loose) { const spacers = list2.items[i4].tokens.filter((t4) => t4.type === "space"); const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t4) => this.rules.other.anyLine.test(t4.raw)); list2.loose = hasMultipleLineBreaks; } } if (list2.loose) { for (let i4 = 0; i4 < list2.items.length; i4++) { list2.items[i4].loose = true; } } return list2; } } html(src) { const cap = this.rules.block.html.exec(src); if (cap) { const token = { type: "html", block: true, raw: cap[0], pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style", text: cap[0] }; return token; } } def(src) { const cap = this.rules.block.def.exec(src); if (cap) { const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "); const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : ""; const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3]; return { type: "def", tag: tag2, raw: cap[0], href, title }; } } table(src) { const cap = this.rules.block.table.exec(src); if (!cap) { return; } if (!this.rules.other.tableDelimiter.test(cap[2])) { return; } const headers = splitCells(cap[1]); const aligns = cap[2].replace(this.rules.other.tableAlignChars, "").split("|"); const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, "").split("\n") : []; const item = { type: "table", raw: cap[0], header: [], align: [], rows: [] }; if (headers.length !== aligns.length) { return; } for (const align of aligns) { if (this.rules.other.tableAlignRight.test(align)) { item.align.push("right"); } else if (this.rules.other.tableAlignCenter.test(align)) { item.align.push("center"); } else if (this.rules.other.tableAlignLeft.test(align)) { item.align.push("left"); } else { item.align.push(null); } } for (let i4 = 0; i4 < headers.length; i4++) { item.header.push({ text: headers[i4], tokens: this.lexer.inline(headers[i4]), header: true, align: item.align[i4] }); } for (const row of rows) { item.rows.push(splitCells(row, item.header.length).map((cell, i4) => { return { text: cell, tokens: this.lexer.inline(cell), header: false, align: item.align[i4] }; })); } return item; } lheading(src) { const cap = this.rules.block.lheading.exec(src); if (cap) { return { type: "heading", raw: cap[0], depth: cap[2].charAt(0) === "=" ? 1 : 2, text: cap[1], tokens: this.lexer.inline(cap[1]) }; } } paragraph(src) { const cap = this.rules.block.paragraph.exec(src); if (cap) { const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1]; return { type: "paragraph", raw: cap[0], text: text2, tokens: this.lexer.inline(text2) }; } } text(src) { const cap = this.rules.block.text.exec(src); if (cap) { return { type: "text", raw: cap[0], text: cap[0], tokens: this.lexer.inline(cap[0]) }; } } escape(src) { const cap = this.rules.inline.escape.exec(src); if (cap) { return { type: "escape", raw: cap[0], text: cap[1] }; } } tag(src) { const cap = this.rules.inline.tag.exec(src); if (cap) { if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) { this.lexer.state.inLink = true; } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) { this.lexer.state.inLink = false; } if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) { this.lexer.state.inRawBlock = true; } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) { this.lexer.state.inRawBlock = false; } return { type: "html", raw: cap[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: cap[0] }; } } link(src) { const cap = this.rules.inline.link.exec(src); if (cap) { const trimmedUrl = cap[2].trim(); if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) { if (!this.rules.other.endAngleBracket.test(trimmedUrl)) { return; } const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\"); if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) { return; } } else { const lastParenIndex = findClosingBracket(cap[2], "()"); if (lastParenIndex > -1) { const start3 = cap[0].indexOf("!") === 0 ? 5 : 4; const linkLen = start3 + cap[1].length + lastParenIndex; cap[2] = cap[2].substring(0, lastParenIndex); cap[0] = cap[0].substring(0, linkLen).trim(); cap[3] = ""; } } let href = cap[2]; let title = ""; if (this.options.pedantic) { const link2 = this.rules.other.pedanticHrefTitle.exec(href); if (link2) { href = link2[1]; title = link2[3]; } } else { title = cap[3] ? cap[3].slice(1, -1) : ""; } href = href.trim(); if (this.rules.other.startAngleBracket.test(href)) { if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) { href = href.slice(1); } else { href = href.slice(1, -1); } } return outputLink(cap, { href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href, title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title }, cap[0], this.lexer, this.rules); } } reflink(src, links) { let cap; if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, " "); const link2 = links[linkString.toLowerCase()]; if (!link2) { const text2 = cap[0].charAt(0); return { type: "text", raw: text2, text: text2 }; } return outputLink(cap, link2, cap[0], this.lexer, this.rules); } } emStrong(src, maskedSrc, prevChar = "") { let match2 = this.rules.inline.emStrongLDelim.exec(src); if (!match2) return; if (match2[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return; const nextChar = match2[1] || match2[2] || ""; if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) { const lLength = [...match2[0]].length - 1; let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; const endReg = match2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; endReg.lastIndex = 0; maskedSrc = maskedSrc.slice(-1 * src.length + lLength); while ((match2 = endReg.exec(maskedSrc)) != null) { rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6]; if (!rDelim) continue; rLength = [...rDelim].length; if (match2[3] || match2[4]) { delimTotal += rLength; continue; } else if (match2[5] || match2[6]) { if (lLength % 3 && !((lLength + rLength) % 3)) { midDelimTotal += rLength; continue; } } delimTotal -= rLength; if (delimTotal > 0) continue; rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); const lastCharLength = [...match2[0]][0].length; const raw = src.slice(0, lLength + match2.index + lastCharLength + rLength); if (Math.min(lLength, rLength) % 2) { const text3 = raw.slice(1, -1); return { type: "em", raw, text: text3, tokens: this.lexer.inlineTokens(text3) }; } const text2 = raw.slice(2, -2); return { type: "strong", raw, text: text2, tokens: this.lexer.inlineTokens(text2) }; } } } codespan(src) { const cap = this.rules.inline.code.exec(src); if (cap) { let text2 = cap[2].replace(this.rules.other.newLineCharGlobal, " "); const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text2); const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text2) && this.rules.other.endingSpaceChar.test(text2); if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { text2 = text2.substring(1, text2.length - 1); } return { type: "codespan", raw: cap[0], text: text2 }; } } br(src) { const cap = this.rules.inline.br.exec(src); if (cap) { return { type: "br", raw: cap[0] }; } } del(src) { const cap = this.rules.inline.del.exec(src); if (cap) { return { type: "del", raw: cap[0], text: cap[2], tokens: this.lexer.inlineTokens(cap[2]) }; } } autolink(src) { const cap = this.rules.inline.autolink.exec(src); if (cap) { let text2, href; if (cap[2] === "@") { text2 = cap[1]; href = "mailto:" + text2; } else { text2 = cap[1]; href = text2; } return { type: "link", raw: cap[0], text: text2, href, tokens: [ { type: "text", raw: text2, text: text2 } ] }; } } url(src) { let cap; if (cap = this.rules.inline.url.exec(src)) { let text2, href; if (cap[2] === "@") { text2 = cap[0]; href = "mailto:" + text2; } else { let prevCapZero; do { prevCapZero = cap[0]; cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? ""; } while (prevCapZero !== cap[0]); text2 = cap[0]; if (cap[1] === "www.") { href = "http://" + cap[0]; } else { href = cap[0]; } } return { type: "link", raw: cap[0], text: text2, href, tokens: [ { type: "text", raw: text2, text: text2 } ] }; } } inlineText(src) { const cap = this.rules.inline.text.exec(src); if (cap) { const escaped = this.lexer.state.inRawBlock; return { type: "text", raw: cap[0], text: cap[0], escaped }; } } }; var _Lexer = class __Lexer { tokens; options; state; tokenizer; inlineQueue; constructor(options2) { this.tokens = []; this.tokens.links = /* @__PURE__ */ Object.create(null); this.options = options2 || _defaults; this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); this.tokenizer = this.options.tokenizer; this.tokenizer.options = this.options; this.tokenizer.lexer = this; this.inlineQueue = []; this.state = { inLink: false, inRawBlock: false, top: true }; const rules = { other, block: block.normal, inline: inline.normal }; if (this.options.pedantic) { rules.block = block.pedantic; rules.inline = inline.pedantic; } else if (this.options.gfm) { rules.block = block.gfm; if (this.options.breaks) { rules.inline = inline.breaks; } else { rules.inline = inline.gfm; } } this.tokenizer.rules = rules; } /** * Expose Rules */ static get rules() { return { block, inline }; } /** * Static Lex Method */ static lex(src, options2) { const lexer2 = new __Lexer(options2); return lexer2.lex(src); } /** * Static Lex Inline Method */ static lexInline(src, options2) { const lexer2 = new __Lexer(options2); return lexer2.inlineTokens(src); } /** * Preprocessing */ lex(src) { src = src.replace(other.carriageReturn, "\n"); this.blockTokens(src, this.tokens); for (let i4 = 0; i4 < this.inlineQueue.length; i4++) { const next = this.inlineQueue[i4]; this.inlineTokens(next.src, next.tokens); } this.inlineQueue = []; return this.tokens; } blockTokens(src, tokens = [], lastParagraphClipped = false) { if (this.options.pedantic) { src = src.replace(other.tabCharGlobal, " ").replace(other.spaceLine, ""); } while (src) { let token; if (this.options.extensions?.block?.some((extTokenizer) => { if (token = extTokenizer.call({ lexer: this }, src, tokens)) { src = src.substring(token.raw.length); tokens.push(token); return true; } return false; })) { continue; } if (token = this.tokenizer.space(src)) { src = src.substring(token.raw.length); const lastToken = tokens.at(-1); if (token.raw.length === 1 && lastToken !== void 0) { lastToken.raw += "\n"; } else { tokens.push(token); } continue; } if (token = this.tokenizer.code(src)) { src = src.substring(token.raw.length); const lastToken = tokens.at(-1); if (lastToken?.type === "paragraph" || lastToken?.type === "text") { lastToken.raw += "\n" + token.raw; lastToken.text += "\n" + token.text; this.inlineQueue.at(-1).src = lastToken.text; } else { tokens.push(token); } continue; } if (token = this.tokenizer.fences(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.heading(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.hr(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.blockquote(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.list(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.html(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.def(src)) { src = src.substring(token.raw.length); const lastToken = tokens.at(-1); if (lastToken?.type === "paragraph" || lastToken?.type === "text") { lastToken.raw += "\n" + token.raw; lastToken.text += "\n" + token.raw; this.inlineQueue.at(-1).src = lastToken.text; } else if (!this.tokens.links[token.tag]) { this.tokens.links[token.tag] = { href: token.href, title: token.title }; } continue; } if (token = this.tokenizer.table(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.lheading(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } let cutSrc = src; if (this.options.extensions?.startBlock) { let startIndex = Infinity; const tempSrc = src.slice(1); let tempStart; this.options.extensions.startBlock.forEach((getStartIndex) => { tempStart = getStartIndex.call({ lexer: this }, tempSrc); if (typeof tempStart === "number" && tempStart >= 0) { startIndex = Math.min(startIndex, tempStart); } }); if (startIndex < Infinity && startIndex >= 0) { cutSrc = src.substring(0, startIndex + 1); } } if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) { const lastToken = tokens.at(-1); if (lastParagraphClipped && lastToken?.type === "paragraph") { lastToken.raw += "\n" + token.raw; lastToken.text += "\n" + token.text; this.inlineQueue.pop(); this.inlineQueue.at(-1).src = lastToken.text; } else { tokens.push(token); } lastParagraphClipped = cutSrc.length !== src.length; src = src.substring(token.raw.length); continue; } if (token = this.tokenizer.text(src)) { src = src.substring(token.raw.length); const lastToken = tokens.at(-1); if (lastToken?.type === "text") { lastToken.raw += "\n" + token.raw; lastToken.text += "\n" + token.text; this.inlineQueue.pop(); this.inlineQueue.at(-1).src = lastToken.text; } else { tokens.push(token); } continue; } if (src) { const errMsg = "Infinite loop on byte: " + src.charCodeAt(0); if (this.options.silent) { console.error(errMsg); break; } else { throw new Error(errMsg); } } } this.state.top = true; return tokens; } inline(src, tokens = []) { this.inlineQueue.push({ src, tokens }); return tokens; } /** * Lexing/Compiling */ inlineTokens(src, tokens = []) { let maskedSrc = src; let match2 = null; if (this.tokens.links) { const links = Object.keys(this.tokens.links); if (links.length > 0) { while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { if (links.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) { maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); } } } } while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); } while ((match2 = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) { maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); } let keepPrevChar = false; let prevChar = ""; while (src) { if (!keepPrevChar) { prevChar = ""; } keepPrevChar = false; let token; if (this.options.extensions?.inline?.some((extTokenizer) => { if (token = extTokenizer.call({ lexer: this }, src, tokens)) { src = src.substring(token.raw.length); tokens.push(token); return true; } return false; })) { continue; } if (token = this.tokenizer.escape(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.tag(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.link(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.reflink(src, this.tokens.links)) { src = src.substring(token.raw.length); const lastToken = tokens.at(-1); if (token.type === "text" && lastToken?.type === "text") { lastToken.raw += token.raw; lastToken.text += token.text; } else { tokens.push(token); } continue; } if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.codespan(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.br(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.del(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (token = this.tokenizer.autolink(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } if (!this.state.inLink && (token = this.tokenizer.url(src))) { src = src.substring(token.raw.length); tokens.push(token); continue; } let cutSrc = src; if (this.options.extensions?.startInline) { let startIndex = Infinity; const tempSrc = src.slice(1); let tempStart; this.options.extensions.startInline.forEach((getStartIndex) => { tempStart = getStartIndex.call({ lexer: this }, tempSrc); if (typeof tempStart === "number" && tempStart >= 0) { startIndex = Math.min(startIndex, tempStart); } }); if (startIndex < Infinity && startIndex >= 0) { cutSrc = src.substring(0, startIndex + 1); } } if (token = this.tokenizer.inlineText(cutSrc)) { src = src.substring(token.raw.length); if (token.raw.slice(-1) !== "_") { prevChar = token.raw.slice(-1); } keepPrevChar = true; const lastToken = tokens.at(-1); if (lastToken?.type === "text") { lastToken.raw += token.raw; lastToken.text += token.text; } else { tokens.push(token); } continue; } if (src) { const errMsg = "Infinite loop on byte: " + src.charCodeAt(0); if (this.options.silent) { console.error(errMsg); break; } else { throw new Error(errMsg); } } } return tokens; } }; var _Renderer = class { options; parser; // set by the parser constructor(options2) { this.options = options2 || _defaults; } space(token) { return ""; } code({ text: text2, lang, escaped }) { const langString = (lang || "").match(other.notSpaceStart)?.[0]; const code = text2.replace(other.endingNewline, "") + "\n"; if (!langString) { return "
" + (escaped ? code : escape2(code, true)) + "
\n"; } return '
' + (escaped ? code : escape2(code, true)) + "
\n"; } blockquote({ tokens }) { const body = this.parser.parse(tokens); return `
${body}
`; } html({ text: text2 }) { return text2; } heading({ tokens, depth }) { return `${this.parser.parseInline(tokens)} `; } hr(token) { return "
\n"; } list(token) { const ordered = token.ordered; const start3 = token.start; let body = ""; for (let j4 = 0; j4 < token.items.length; j4++) { const item = token.items[j4]; body += this.listitem(item); } const type = ordered ? "ol" : "ul"; const startAttr = ordered && start3 !== 1 ? ' start="' + start3 + '"' : ""; return "<" + type + startAttr + ">\n" + body + "\n"; } listitem(item) { let itemBody = ""; if (item.task) { const checkbox = this.checkbox({ checked: !!item.checked }); if (item.loose) { if (item.tokens[0]?.type === "paragraph") { item.tokens[0].text = checkbox + " " + item.tokens[0].text; if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") { item.tokens[0].tokens[0].text = checkbox + " " + escape2(item.tokens[0].tokens[0].text); item.tokens[0].tokens[0].escaped = true; } } else { item.tokens.unshift({ type: "text", raw: checkbox + " ", text: checkbox + " ", escaped: true }); } } else { itemBody += checkbox + " "; } } itemBody += this.parser.parse(item.tokens, !!item.loose); return `
  • ${itemBody}
  • `; } checkbox({ checked }) { return "'; } paragraph({ tokens }) { return `

    ${this.parser.parseInline(tokens)}

    `; } table(token) { let header = ""; let cell = ""; for (let j4 = 0; j4 < token.header.length; j4++) { cell += this.tablecell(token.header[j4]); } header += this.tablerow({ text: cell }); let body = ""; for (let j4 = 0; j4 < token.rows.length; j4++) { const row = token.rows[j4]; cell = ""; for (let k4 = 0; k4 < row.length; k4++) { cell += this.tablecell(row[k4]); } body += this.tablerow({ text: cell }); } if (body) body = `${body}`; return "\n\n" + header + "\n" + body + "
    \n"; } tablerow({ text: text2 }) { return ` ${text2} `; } tablecell(token) { const content = this.parser.parseInline(token.tokens); const type = token.header ? "th" : "td"; const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`; return tag2 + content + ` `; } /** * span level renderer */ strong({ tokens }) { return `${this.parser.parseInline(tokens)}`; } em({ tokens }) { return `${this.parser.parseInline(tokens)}`; } codespan({ text: text2 }) { return `${escape2(text2, true)}`; } br(token) { return "
    "; } del({ tokens }) { return `${this.parser.parseInline(tokens)}`; } link({ href, title, tokens }) { const text2 = this.parser.parseInline(tokens); const cleanHref = cleanUrl(href); if (cleanHref === null) { return text2; } href = cleanHref; let out = '
    "; return out; } image({ href, title, text: text2 }) { const cleanHref = cleanUrl(href); if (cleanHref === null) { return escape2(text2); } href = cleanHref; let out = `${text2} { const tokens2 = genericToken[childTokens].flat(Infinity); values = values.concat(this.walkTokens(tokens2, callback)); }); } else if (genericToken.tokens) { values = values.concat(this.walkTokens(genericToken.tokens, callback)); } } } } return values; } use(...args) { const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} }; args.forEach((pack) => { const opts = { ...pack }; opts.async = this.defaults.async || opts.async || false; if (pack.extensions) { pack.extensions.forEach((ext) => { if (!ext.name) { throw new Error("extension name required"); } if ("renderer" in ext) { const prevRenderer = extensions.renderers[ext.name]; if (prevRenderer) { extensions.renderers[ext.name] = function(...args2) { let ret = ext.renderer.apply(this, args2); if (ret === false) { ret = prevRenderer.apply(this, args2); } return ret; }; } else { extensions.renderers[ext.name] = ext.renderer; } } if ("tokenizer" in ext) { if (!ext.level || ext.level !== "block" && ext.level !== "inline") { throw new Error("extension level must be 'block' or 'inline'"); } const extLevel = extensions[ext.level]; if (extLevel) { extLevel.unshift(ext.tokenizer); } else { extensions[ext.level] = [ext.tokenizer]; } if (ext.start) { if (ext.level === "block") { if (extensions.startBlock) { extensions.startBlock.push(ext.start); } else { extensions.startBlock = [ext.start]; } } else if (ext.level === "inline") { if (extensions.startInline) { extensions.startInline.push(ext.start); } else { extensions.startInline = [ext.start]; } } } } if ("childTokens" in ext && ext.childTokens) { extensions.childTokens[ext.name] = ext.childTokens; } }); opts.extensions = extensions; } if (pack.renderer) { const renderer = this.defaults.renderer || new _Renderer(this.defaults); for (const prop in pack.renderer) { if (!(prop in renderer)) { throw new Error(`renderer '${prop}' does not exist`); } if (["options", "parser"].includes(prop)) { continue; } const rendererProp = prop; const rendererFunc = pack.renderer[rendererProp]; const prevRenderer = renderer[rendererProp]; renderer[rendererProp] = (...args2) => { let ret = rendererFunc.apply(renderer, args2); if (ret === false) { ret = prevRenderer.apply(renderer, args2); } return ret || ""; }; } opts.renderer = renderer; } if (pack.tokenizer) { const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); for (const prop in pack.tokenizer) { if (!(prop in tokenizer)) { throw new Error(`tokenizer '${prop}' does not exist`); } if (["options", "rules", "lexer"].includes(prop)) { continue; } const tokenizerProp = prop; const tokenizerFunc = pack.tokenizer[tokenizerProp]; const prevTokenizer = tokenizer[tokenizerProp]; tokenizer[tokenizerProp] = (...args2) => { let ret = tokenizerFunc.apply(tokenizer, args2); if (ret === false) { ret = prevTokenizer.apply(tokenizer, args2); } return ret; }; } opts.tokenizer = tokenizer; } if (pack.hooks) { const hooks = this.defaults.hooks || new _Hooks(); for (const prop in pack.hooks) { if (!(prop in hooks)) { throw new Error(`hook '${prop}' does not exist`); } if (["options", "block"].includes(prop)) { continue; } const hooksProp = prop; const hooksFunc = pack.hooks[hooksProp]; const prevHook = hooks[hooksProp]; if (_Hooks.passThroughHooks.has(prop)) { hooks[hooksProp] = (arg) => { if (this.defaults.async) { return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => { return prevHook.call(hooks, ret2); }); } const ret = hooksFunc.call(hooks, arg); return prevHook.call(hooks, ret); }; } else { hooks[hooksProp] = (...args2) => { let ret = hooksFunc.apply(hooks, args2); if (ret === false) { ret = prevHook.apply(hooks, args2); } return ret; }; } } opts.hooks = hooks; } if (pack.walkTokens) { const walkTokens2 = this.defaults.walkTokens; const packWalktokens = pack.walkTokens; opts.walkTokens = function(token) { let values = []; values.push(packWalktokens.call(this, token)); if (walkTokens2) { values = values.concat(walkTokens2.call(this, token)); } return values; }; } this.defaults = { ...this.defaults, ...opts }; }); return this; } setOptions(opt) { this.defaults = { ...this.defaults, ...opt }; return this; } lexer(src, options2) { return _Lexer.lex(src, options2 ?? this.defaults); } parser(tokens, options2) { return _Parser.parse(tokens, options2 ?? this.defaults); } parseMarkdown(blockType) { const parse = (src, options2) => { const origOpt = { ...options2 }; const opt = { ...this.defaults, ...origOpt }; const throwError = this.onError(!!opt.silent, !!opt.async); if (this.defaults.async === true && origOpt.async === false) { return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.")); } if (typeof src === "undefined" || src === null) { return throwError(new Error("marked(): input parameter is undefined or null")); } if (typeof src !== "string") { return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected")); } if (opt.hooks) { opt.hooks.options = opt; opt.hooks.block = blockType; } const lexer2 = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline; const parser2 = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline; if (opt.async) { return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html3) => opt.hooks ? opt.hooks.postprocess(html3) : html3).catch(throwError); } try { if (opt.hooks) { src = opt.hooks.preprocess(src); } let tokens = lexer2(src, opt); if (opt.hooks) { tokens = opt.hooks.processAllTokens(tokens); } if (opt.walkTokens) { this.walkTokens(tokens, opt.walkTokens); } let html3 = parser2(tokens, opt); if (opt.hooks) { html3 = opt.hooks.postprocess(html3); } return html3; } catch (e4) { return throwError(e4); } }; return parse; } onError(silent, async) { return (e4) => { e4.message += "\nPlease report this to https://github.com/markedjs/marked."; if (silent) { const msg = "

    An error occurred:

    " + escape2(e4.message + "", true) + "
    "; if (async) { return Promise.resolve(msg); } return msg; } if (async) { return Promise.reject(e4); } throw e4; }; } }; var markedInstance = new Marked(); function marked(src, opt) { return markedInstance.parse(src, opt); } marked.options = marked.setOptions = function(options2) { markedInstance.setOptions(options2); marked.defaults = markedInstance.defaults; changeDefaults(marked.defaults); return marked; }; marked.getDefaults = _getDefaults; marked.defaults = _defaults; marked.use = function(...args) { markedInstance.use(...args); marked.defaults = markedInstance.defaults; changeDefaults(marked.defaults); return marked; }; marked.walkTokens = function(tokens, callback) { return markedInstance.walkTokens(tokens, callback); }; marked.parseInline = markedInstance.parseInline; marked.Parser = _Parser; marked.parser = _Parser.parse; marked.Renderer = _Renderer; marked.TextRenderer = _TextRenderer; marked.Lexer = _Lexer; marked.lexer = _Lexer.lex; marked.Tokenizer = _Tokenizer; marked.Hooks = _Hooks; marked.parse = marked; var options = marked.options; var setOptions = marked.setOptions; var use = marked.use; var walkTokens = marked.walkTokens; var parseInline = marked.parseInline; var parser = _Parser.parse; var lexer = _Lexer.lex; // src/js/controllers/easymde_controller.js var easymde_controller_default = class extends Controller { connect() { this.easyMDE = new EasyMDE(this.#buildOptions()); this.element.setAttribute("data-action", "turbo:morph-element->easymde#reconnect"); } disconnect() { this.easyMDE.toTextArea(); this.easyMDE = null; } reconnect() { this.disconnect(); this.connect(); } #buildOptions() { let options2 = { element: this.element, promptURLs: true, spellChecker: false, // Override the default preview renderer previewRender: (plainText) => { const cleanedText = purify.sanitize(plainText, { ALLOWED_TAGS: ["strong", "em", "sub", "sup", "details", "summary"], ALLOWED_ATTR: [] }); const cleanedHTML = marked(cleanedText); return purify.sanitize(cleanedHTML, { USE_PROFILES: { html: true } }); } }; if (this.element.attributes.id.value) { options2.autosave = { enabled: true, uniqueId: this.element.attributes.id.value, delay: 1e3 }; } return options2; } }; // src/js/controllers/slim_select_controller.js var slim_select_controller_default = class extends Controller { connect() { this.slimSelect = new SlimSelect({ select: this.element }); this.element.setAttribute("data-action", "turbo:morph-element->slim-select#reconnect"); } disconnect() { this.slimSelect.destroy(); this.slimSelect = null; } reconnect() { this.disconnect(); setTimeout(() => this.connect(), 10); } }; // src/js/controllers/flatpickr_controller.js var flatpickr_controller_default = class extends Controller { connect() { this.picker = new flatpickr(this.element, this.#buildOptions()); this.element.setAttribute("data-action", "turbo:morph-element->flatpickr#reconnect"); } disconnect() { this.picker.destroy(); this.picker = null; } reconnect() { this.disconnect(); this.connect(); } #buildOptions() { let options2 = { altInput: true }; if (this.element.attributes.type.value == "datetime-local") { options2.enableTime = true; } else if (this.element.attributes.type.value == "time") { options2.enableTime = true; options2.noCalendar = true; } return options2; } }; // src/js/controllers/intl_tel_input_controller.js var intl_tel_input_controller_default = class extends Controller { static targets = ["input"]; connect() { } disconnect() { this.inputTargetDisconnected(); } inputTargetConnected() { if (!this.hasInputTarget) return; this.iti = window.intlTelInput(this.inputTarget, this.#buildOptions()); this.inputTarget.setAttribute("data-action", "turbo:morph-element->intl-tel-input#reconnect"); } inputTargetDisconnected() { if (this.iti) this.iti.destroy(); this.iti = null; } reconnect() { this.inputTargetDisconnected(); this.inputTargetConnected(); } #buildOptions() { return { strictMode: true, hiddenInput: () => ({ phone: this.inputTarget.attributes.name.value }), loadUtilsOnInit: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.8.1/build/js/utils.js" }; } }; // src/js/controllers/select_navigator.js var select_navigator_default = class extends Controller { static targets = ["select"]; navigate(_3) { const url = this.selectTarget.value; const anchor = document.createElement("a"); anchor.href = url; this.element.appendChild(anchor); anchor.click(); anchor.remove(); } }; // src/js/controllers/resource_tab_list_controller.js var resource_tab_list_controller_default = class extends Controller { static targets = ["btn", "tab"]; static values = { defaultTab: String, activeClasses: String, inActiveClasses: String }; connect() { this.activeClasses = this.hasActiveClassesValue ? this.activeClassesValue.split(" ") : []; this.inActiveClasses = this.hasInActiveClassesValue ? this.inActiveClassesValue.split(" ") : []; this.#selectInternal(this.defaultTabValue || this.btnTargets[0].id); } select(event) { this.#selectInternal(event.currentTarget.id); } #selectInternal(id12) { const selectedBtn = this.btnTargets.find((element) => element.id === id12); if (!selectedBtn) { console.error(`Tab Button with id "${id12}" not found`); return; } const selectedTab = this.tabTargets.find((element) => element.id === selectedBtn.dataset.target); if (!selectedTab) { console.error(`Tab Panel with id "${selectedBtn.dataset.target}" not found`); return; } this.tabTargets.forEach((tab) => { tab.hidden = true; tab.setAttribute("aria-hidden", "true"); }); this.btnTargets.forEach((btn) => { btn.setAttribute("aria-selected", "false"); btn.setAttribute("tabindex", "-1"); btn.classList.remove(...this.activeClasses); btn.classList.add(...this.inActiveClasses); }); selectedBtn.setAttribute("aria-selected", "true"); selectedBtn.setAttribute("tabindex", "0"); selectedBtn.classList.remove(...this.inActiveClasses); selectedBtn.classList.add(...this.activeClasses); selectedTab.hidden = false; selectedTab.setAttribute("aria-hidden", "false"); if (selectedBtn !== document.activeElement) { selectedBtn.focus(); } } }; // node_modules/@uppy/utils/lib/Translator.js function _classPrivateFieldLooseBase(e4, t4) { if (!{}.hasOwnProperty.call(e4, t4)) throw new TypeError("attempted to use private field on non-instance"); return e4; } var id = 0; function _classPrivateFieldLooseKey(e4) { return "__private_" + id++ + "_" + e4; } function insertReplacement(source, rx, replacement) { const newParts = []; source.forEach((chunk) => { if (typeof chunk !== "string") { return newParts.push(chunk); } return rx[Symbol.split](chunk).forEach((raw, i4, list2) => { if (raw !== "") { newParts.push(raw); } if (i4 < list2.length - 1) { newParts.push(replacement); } }); }); return newParts; } function interpolate(phrase, options2) { const dollarRegex = /\$/g; const dollarBillsYall = "$$$$"; let interpolated = [phrase]; if (options2 == null) return interpolated; for (const arg of Object.keys(options2)) { if (arg !== "_") { let replacement = options2[arg]; if (typeof replacement === "string") { replacement = dollarRegex[Symbol.replace](replacement, dollarBillsYall); } interpolated = insertReplacement(interpolated, new RegExp(`%\\{${arg}\\}`, "g"), replacement); } } return interpolated; } var defaultOnMissingKey = (key) => { throw new Error(`missing string: ${key}`); }; var _onMissingKey = /* @__PURE__ */ _classPrivateFieldLooseKey("onMissingKey"); var _apply = /* @__PURE__ */ _classPrivateFieldLooseKey("apply"); var Translator = class { constructor(locales, _temp) { let { onMissingKey = defaultOnMissingKey } = _temp === void 0 ? {} : _temp; Object.defineProperty(this, _apply, { value: _apply2 }); Object.defineProperty(this, _onMissingKey, { writable: true, value: void 0 }); this.locale = { strings: {}, pluralize(n3) { if (n3 === 1) { return 0; } return 1; } }; if (Array.isArray(locales)) { locales.forEach(_classPrivateFieldLooseBase(this, _apply)[_apply], this); } else { _classPrivateFieldLooseBase(this, _apply)[_apply](locales); } _classPrivateFieldLooseBase(this, _onMissingKey)[_onMissingKey] = onMissingKey; } /** * Public translate method * * @param key * @param options with values that will be used later to replace placeholders in string * @returns string translated (and interpolated) */ translate(key, options2) { return this.translateArray(key, options2).join(""); } /** * Get a translation and return the translated and interpolated parts as an array. * * @returns The translated and interpolated parts, in order. */ translateArray(key, options2) { let string = this.locale.strings[key]; if (string == null) { _classPrivateFieldLooseBase(this, _onMissingKey)[_onMissingKey](key); string = key; } const hasPluralForms = typeof string === "object"; if (hasPluralForms) { if (options2 && typeof options2.smart_count !== "undefined") { const plural = this.locale.pluralize(options2.smart_count); return interpolate(string[plural], options2); } throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}"); } if (typeof string !== "string") { throw new Error(`string was not a string`); } return interpolate(string, options2); } }; function _apply2(locale) { if (!(locale != null && locale.strings)) { return; } const prevLocale = this.locale; Object.assign(this.locale, { strings: { ...prevLocale.strings, ...locale.strings }, pluralize: locale.pluralize || prevLocale.pluralize }); } // node_modules/@uppy/core/lib/Uppy.js var import_namespace_emitter = __toESM(require_namespace_emitter(), 1); // node_modules/@uppy/core/node_modules/nanoid/non-secure/index.js var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; var nanoid = (size = 21) => { let id12 = ""; let i4 = size | 0; while (i4--) { id12 += urlAlphabet[Math.random() * 64 | 0]; } return id12; }; // node_modules/@uppy/core/lib/Uppy.js var import_throttle = __toESM(require_throttle(), 1); // node_modules/@uppy/store-default/lib/index.js function _classPrivateFieldLooseBase2(e4, t4) { if (!{}.hasOwnProperty.call(e4, t4)) throw new TypeError("attempted to use private field on non-instance"); return e4; } var id2 = 0; function _classPrivateFieldLooseKey2(e4) { return "__private_" + id2++ + "_" + e4; } var packageJson = { "version": "4.1.2" }; var _callbacks = /* @__PURE__ */ _classPrivateFieldLooseKey2("callbacks"); var _publish = /* @__PURE__ */ _classPrivateFieldLooseKey2("publish"); var DefaultStore = class { constructor() { Object.defineProperty(this, _publish, { value: _publish2 }); this.state = {}; Object.defineProperty(this, _callbacks, { writable: true, value: /* @__PURE__ */ new Set() }); } getState() { return this.state; } setState(patch) { const prevState = { ...this.state }; const nextState = { ...this.state, ...patch }; this.state = nextState; _classPrivateFieldLooseBase2(this, _publish)[_publish](prevState, nextState, patch); } subscribe(listener) { _classPrivateFieldLooseBase2(this, _callbacks)[_callbacks].add(listener); return () => { _classPrivateFieldLooseBase2(this, _callbacks)[_callbacks].delete(listener); }; } }; function _publish2() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _classPrivateFieldLooseBase2(this, _callbacks)[_callbacks].forEach((listener) => { listener(...args); }); } DefaultStore.VERSION = packageJson.version; var lib_default = DefaultStore; // node_modules/@uppy/utils/lib/getFileNameAndExtension.js function getFileNameAndExtension(fullFileName) { const lastDot = fullFileName.lastIndexOf("."); if (lastDot === -1 || lastDot === fullFileName.length - 1) { return { name: fullFileName, extension: void 0 }; } return { name: fullFileName.slice(0, lastDot), extension: fullFileName.slice(lastDot + 1) }; } // node_modules/@uppy/utils/lib/mimeTypes.js var mimeTypes_default = { __proto__: null, md: "text/markdown", markdown: "text/markdown", mp4: "video/mp4", mp3: "audio/mp3", svg: "image/svg+xml", jpg: "image/jpeg", png: "image/png", webp: "image/webp", gif: "image/gif", heic: "image/heic", heif: "image/heif", yaml: "text/yaml", yml: "text/yaml", csv: "text/csv", tsv: "text/tab-separated-values", tab: "text/tab-separated-values", avi: "video/x-msvideo", mks: "video/x-matroska", mkv: "video/x-matroska", mov: "video/quicktime", dicom: "application/dicom", doc: "application/msword", docm: "application/vnd.ms-word.document.macroenabled.12", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", dot: "application/msword", dotm: "application/vnd.ms-word.template.macroenabled.12", dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml.template", xla: "application/vnd.ms-excel", xlam: "application/vnd.ms-excel.addin.macroenabled.12", xlc: "application/vnd.ms-excel", xlf: "application/x-xliff+xml", xlm: "application/vnd.ms-excel", xls: "application/vnd.ms-excel", xlsb: "application/vnd.ms-excel.sheet.binary.macroenabled.12", xlsm: "application/vnd.ms-excel.sheet.macroenabled.12", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", xlt: "application/vnd.ms-excel", xltm: "application/vnd.ms-excel.template.macroenabled.12", xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template", xlw: "application/vnd.ms-excel", txt: "text/plain", text: "text/plain", conf: "text/plain", log: "text/plain", pdf: "application/pdf", zip: "application/zip", "7z": "application/x-7z-compressed", rar: "application/x-rar-compressed", tar: "application/x-tar", gz: "application/gzip", dmg: "application/x-apple-diskimage" }; // node_modules/@uppy/utils/lib/getFileType.js function getFileType(file) { var _getFileNameAndExtens; if (file.type) return file.type; const fileExtension = file.name ? (_getFileNameAndExtens = getFileNameAndExtension(file.name).extension) == null ? void 0 : _getFileNameAndExtens.toLowerCase() : null; if (fileExtension && fileExtension in mimeTypes_default) { return mimeTypes_default[fileExtension]; } return "application/octet-stream"; } // node_modules/@uppy/utils/lib/generateFileID.js function encodeCharacter(character) { return character.charCodeAt(0).toString(32); } function encodeFilename(name) { let suffix = ""; return name.replace(/[^A-Z0-9]/gi, (character) => { suffix += `-${encodeCharacter(character)}`; return "/"; }) + suffix; } function generateFileID(file, instanceId) { let id12 = instanceId || "uppy"; if (typeof file.name === "string") { id12 += `-${encodeFilename(file.name.toLowerCase())}`; } if (file.type !== void 0) { id12 += `-${file.type}`; } if (file.meta && typeof file.meta.relativePath === "string") { id12 += `-${encodeFilename(file.meta.relativePath.toLowerCase())}`; } if (file.data.size !== void 0) { id12 += `-${file.data.size}`; } if (file.data.lastModified !== void 0) { id12 += `-${file.data.lastModified}`; } return id12; } function hasFileStableId(file) { if (!file.isRemote || !file.remote) return false; const stableIdProviders = /* @__PURE__ */ new Set(["box", "dropbox", "drive", "facebook", "unsplash"]); return stableIdProviders.has(file.remote.provider); } function getSafeFileId(file, instanceId) { if (hasFileStableId(file)) return file.id; const fileType = getFileType(file); return generateFileID({ ...file, type: fileType }, instanceId); } // node_modules/@uppy/core/lib/supportsUploadProgress.js function supportsUploadProgress(userAgent) { if (userAgent == null && typeof navigator !== "undefined") { userAgent = navigator.userAgent; } if (!userAgent) return true; const m4 = /Edge\/(\d+\.\d+)/.exec(userAgent); if (!m4) return true; const edgeVersion = m4[1]; const version = edgeVersion.split(".", 2); const major = parseInt(version[0], 10); const minor = parseInt(version[1], 10); if (major < 15 || major === 15 && minor < 15063) { return true; } if (major > 18 || major === 18 && minor >= 18218) { return true; } return false; } // node_modules/@uppy/core/lib/getFileName.js function getFileName(fileType, fileDescriptor) { if (fileDescriptor.name) { return fileDescriptor.name; } if (fileType.split("/")[0] === "image") { return `${fileType.split("/")[0]}.${fileType.split("/")[1]}`; } return "noname"; } // node_modules/@uppy/utils/lib/getTimeStamp.js function pad(number) { return number < 10 ? `0${number}` : number.toString(); } function getTimeStamp() { const date = /* @__PURE__ */ new Date(); const hours = pad(date.getHours()); const minutes = pad(date.getMinutes()); const seconds = pad(date.getSeconds()); return `${hours}:${minutes}:${seconds}`; } // node_modules/@uppy/core/lib/loggers.js var justErrorsLogger = { debug: () => { }, warn: () => { }, error: function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return console.error(`[Uppy] [${getTimeStamp()}]`, ...args); } }; var debugLogger = { debug: function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return console.debug(`[Uppy] [${getTimeStamp()}]`, ...args); }, warn: function() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return console.warn(`[Uppy] [${getTimeStamp()}]`, ...args); }, error: function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return console.error(`[Uppy] [${getTimeStamp()}]`, ...args); } }; // node_modules/@uppy/core/lib/Restricter.js var import_prettier_bytes = __toESM(require_prettierBytes(), 1); var import_mime_match = __toESM(require_mime_match(), 1); var defaultOptions = { maxFileSize: null, minFileSize: null, maxTotalFileSize: null, maxNumberOfFiles: null, minNumberOfFiles: null, allowedFileTypes: null, requiredMetaFields: [] }; var RestrictionError = class extends Error { constructor(message, opts) { var _opts$isUserFacing; super(message); this.isRestriction = true; this.isUserFacing = (_opts$isUserFacing = opts == null ? void 0 : opts.isUserFacing) != null ? _opts$isUserFacing : true; if (opts != null && opts.file) { this.file = opts.file; } } }; var Restricter = class { constructor(getOpts, getI18n) { this.getI18n = getI18n; this.getOpts = () => { var _opts$restrictions; const opts = getOpts(); if (((_opts$restrictions = opts.restrictions) == null ? void 0 : _opts$restrictions.allowedFileTypes) != null && !Array.isArray(opts.restrictions.allowedFileTypes)) { throw new TypeError("`restrictions.allowedFileTypes` must be an array"); } return opts; }; } // Because these operations are slow, we cannot run them for every file (if we are adding multiple files) validateAggregateRestrictions(existingFiles, addingFiles) { const { maxTotalFileSize, maxNumberOfFiles } = this.getOpts().restrictions; if (maxNumberOfFiles) { const nonGhostFiles = existingFiles.filter((f4) => !f4.isGhost); if (nonGhostFiles.length + addingFiles.length > maxNumberOfFiles) { throw new RestrictionError(`${this.getI18n()("youCanOnlyUploadX", { smart_count: maxNumberOfFiles })}`); } } if (maxTotalFileSize) { const totalFilesSize = [...existingFiles, ...addingFiles].reduce((total, f4) => { var _f$size; return total + ((_f$size = f4.size) != null ? _f$size : 0); }, 0); if (totalFilesSize > maxTotalFileSize) { throw new RestrictionError(this.getI18n()("aggregateExceedsSize", { sizeAllowed: (0, import_prettier_bytes.default)(maxTotalFileSize), size: (0, import_prettier_bytes.default)(totalFilesSize) })); } } } validateSingleFile(file) { const { maxFileSize, minFileSize, allowedFileTypes } = this.getOpts().restrictions; if (allowedFileTypes) { const isCorrectFileType = allowedFileTypes.some((type) => { if (type.includes("/")) { if (!file.type) return false; return (0, import_mime_match.default)(file.type.replace(/;.*?$/, ""), type); } if (type[0] === "." && file.extension) { return file.extension.toLowerCase() === type.slice(1).toLowerCase(); } return false; }); if (!isCorrectFileType) { const allowedFileTypesString = allowedFileTypes.join(", "); throw new RestrictionError(this.getI18n()("youCanOnlyUploadFileTypes", { types: allowedFileTypesString }), { file }); } } if (maxFileSize && file.size != null && file.size > maxFileSize) { var _file$name; throw new RestrictionError(this.getI18n()("exceedsSize", { size: (0, import_prettier_bytes.default)(maxFileSize), file: (_file$name = file.name) != null ? _file$name : this.getI18n()("unnamed") }), { file }); } if (minFileSize && file.size != null && file.size < minFileSize) { throw new RestrictionError(this.getI18n()("inferiorSize", { size: (0, import_prettier_bytes.default)(minFileSize) }), { file }); } } validate(existingFiles, addingFiles) { addingFiles.forEach((addingFile) => { this.validateSingleFile(addingFile); }); this.validateAggregateRestrictions(existingFiles, addingFiles); } validateMinNumberOfFiles(files) { const { minNumberOfFiles } = this.getOpts().restrictions; if (minNumberOfFiles && Object.keys(files).length < minNumberOfFiles) { throw new RestrictionError(this.getI18n()("youHaveToAtLeastSelectX", { smart_count: minNumberOfFiles })); } } getMissingRequiredMetaFields(file) { var _file$name2; const error2 = new RestrictionError(this.getI18n()("missingRequiredMetaFieldOnFile", { fileName: (_file$name2 = file.name) != null ? _file$name2 : this.getI18n()("unnamed") })); const { requiredMetaFields } = this.getOpts().restrictions; const missingFields = []; for (const field of requiredMetaFields) { if (!Object.hasOwn(file.meta, field) || file.meta[field] === "") { missingFields.push(field); } } return { missingFields, error: error2 }; } }; // node_modules/@uppy/core/lib/locale.js var locale_default = { strings: { addBulkFilesFailed: { 0: "Failed to add %{smart_count} file due to an internal error", 1: "Failed to add %{smart_count} files due to internal errors" }, youCanOnlyUploadX: { 0: "You can only upload %{smart_count} file", 1: "You can only upload %{smart_count} files" }, youHaveToAtLeastSelectX: { 0: "You have to select at least %{smart_count} file", 1: "You have to select at least %{smart_count} files" }, aggregateExceedsSize: "You selected %{size} of files, but maximum allowed size is %{sizeAllowed}", exceedsSize: "%{file} exceeds maximum allowed size of %{size}", missingRequiredMetaField: "Missing required meta fields", missingRequiredMetaFieldOnFile: "Missing required meta fields in %{fileName}", inferiorSize: "This file is smaller than the allowed size of %{size}", youCanOnlyUploadFileTypes: "You can only upload: %{types}", noMoreFilesAllowed: "Cannot add more files", noDuplicates: "Cannot add the duplicate file '%{fileName}', it already exists", companionError: "Connection with Companion failed", authAborted: "Authentication aborted", companionUnauthorizeHint: "To unauthorize to your %{provider} account, please go to %{url}", failedToUpload: "Failed to upload %{file}", noInternetConnection: "No Internet connection", connectedToInternet: "Connected to the Internet", // Strings for remote providers noFilesFound: "You have no files or folders here", noSearchResults: "Unfortunately, there are no results for this search", selectX: { 0: "Select %{smart_count}", 1: "Select %{smart_count}" }, allFilesFromFolderNamed: "All files from folder %{name}", openFolderNamed: "Open folder %{name}", cancel: "Cancel", logOut: "Log out", logIn: "Log in", pickFiles: "Pick files", pickPhotos: "Pick photos", filter: "Filter", resetFilter: "Reset filter", loading: "Loading...", loadedXFiles: "Loaded %{numFiles} files", authenticateWithTitle: "Please authenticate with %{pluginName} to select files", authenticateWith: "Connect to %{pluginName}", signInWithGoogle: "Sign in with Google", searchImages: "Search for images", enterTextToSearch: "Enter text to search for images", search: "Search", resetSearch: "Reset search", emptyFolderAdded: "No files were added from empty folder", addedNumFiles: "Added %{numFiles} file(s)", folderAlreadyAdded: 'The folder "%{folder}" was already added', folderAdded: { 0: "Added %{smart_count} file from %{folder}", 1: "Added %{smart_count} files from %{folder}" }, additionalRestrictionsFailed: "%{count} additional restrictions were not fulfilled", unnamed: "Unnamed", pleaseWait: "Please wait" } }; // node_modules/@uppy/core/lib/Uppy.js function _classPrivateFieldLooseBase3(e4, t4) { if (!{}.hasOwnProperty.call(e4, t4)) throw new TypeError("attempted to use private field on non-instance"); return e4; } var id3 = 0; function _classPrivateFieldLooseKey3(e4) { return "__private_" + id3++ + "_" + e4; } var packageJson2 = { "version": "4.3.1" }; var defaultUploadState = { totalProgress: 0, allowNewUpload: true, error: null, recoveredState: null }; var _plugins = /* @__PURE__ */ _classPrivateFieldLooseKey3("plugins"); var _restricter = /* @__PURE__ */ _classPrivateFieldLooseKey3("restricter"); var _storeUnsubscribe = /* @__PURE__ */ _classPrivateFieldLooseKey3("storeUnsubscribe"); var _emitter = /* @__PURE__ */ _classPrivateFieldLooseKey3("emitter"); var _preProcessors = /* @__PURE__ */ _classPrivateFieldLooseKey3("preProcessors"); var _uploaders = /* @__PURE__ */ _classPrivateFieldLooseKey3("uploaders"); var _postProcessors = /* @__PURE__ */ _classPrivateFieldLooseKey3("postProcessors"); var _informAndEmit = /* @__PURE__ */ _classPrivateFieldLooseKey3("informAndEmit"); var _checkRequiredMetaFieldsOnFile = /* @__PURE__ */ _classPrivateFieldLooseKey3("checkRequiredMetaFieldsOnFile"); var _checkRequiredMetaFields = /* @__PURE__ */ _classPrivateFieldLooseKey3("checkRequiredMetaFields"); var _assertNewUploadAllowed = /* @__PURE__ */ _classPrivateFieldLooseKey3("assertNewUploadAllowed"); var _transformFile = /* @__PURE__ */ _classPrivateFieldLooseKey3("transformFile"); var _startIfAutoProceed = /* @__PURE__ */ _classPrivateFieldLooseKey3("startIfAutoProceed"); var _checkAndUpdateFileState = /* @__PURE__ */ _classPrivateFieldLooseKey3("checkAndUpdateFileState"); var _handleUploadProgress = /* @__PURE__ */ _classPrivateFieldLooseKey3("handleUploadProgress"); var _updateTotalProgress = /* @__PURE__ */ _classPrivateFieldLooseKey3("updateTotalProgress"); var _updateTotalProgressThrottled = /* @__PURE__ */ _classPrivateFieldLooseKey3("updateTotalProgressThrottled"); var _calculateTotalProgress = /* @__PURE__ */ _classPrivateFieldLooseKey3("calculateTotalProgress"); var _addListeners = /* @__PURE__ */ _classPrivateFieldLooseKey3("addListeners"); var _updateOnlineStatus = /* @__PURE__ */ _classPrivateFieldLooseKey3("updateOnlineStatus"); var _requestClientById = /* @__PURE__ */ _classPrivateFieldLooseKey3("requestClientById"); var _createUpload = /* @__PURE__ */ _classPrivateFieldLooseKey3("createUpload"); var _getUpload = /* @__PURE__ */ _classPrivateFieldLooseKey3("getUpload"); var _removeUpload = /* @__PURE__ */ _classPrivateFieldLooseKey3("removeUpload"); var _runUpload = /* @__PURE__ */ _classPrivateFieldLooseKey3("runUpload"); var Uppy = class _Uppy { /** * Instantiate Uppy */ constructor(_opts) { Object.defineProperty(this, _runUpload, { value: _runUpload2 }); Object.defineProperty(this, _removeUpload, { value: _removeUpload2 }); Object.defineProperty(this, _getUpload, { value: _getUpload2 }); Object.defineProperty(this, _createUpload, { value: _createUpload2 }); Object.defineProperty(this, _addListeners, { value: _addListeners2 }); Object.defineProperty(this, _calculateTotalProgress, { value: _calculateTotalProgress2 }); Object.defineProperty(this, _updateTotalProgress, { value: _updateTotalProgress2 }); Object.defineProperty(this, _checkAndUpdateFileState, { value: _checkAndUpdateFileState2 }); Object.defineProperty(this, _startIfAutoProceed, { value: _startIfAutoProceed2 }); Object.defineProperty(this, _transformFile, { value: _transformFile2 }); Object.defineProperty(this, _assertNewUploadAllowed, { value: _assertNewUploadAllowed2 }); Object.defineProperty(this, _checkRequiredMetaFields, { value: _checkRequiredMetaFields2 }); Object.defineProperty(this, _checkRequiredMetaFieldsOnFile, { value: _checkRequiredMetaFieldsOnFile2 }); Object.defineProperty(this, _informAndEmit, { value: _informAndEmit2 }); Object.defineProperty(this, _plugins, { writable: true, value: /* @__PURE__ */ Object.create(null) }); Object.defineProperty(this, _restricter, { writable: true, value: void 0 }); Object.defineProperty(this, _storeUnsubscribe, { writable: true, value: void 0 }); Object.defineProperty(this, _emitter, { writable: true, value: (0, import_namespace_emitter.default)() }); Object.defineProperty(this, _preProcessors, { writable: true, value: /* @__PURE__ */ new Set() }); Object.defineProperty(this, _uploaders, { writable: true, value: /* @__PURE__ */ new Set() }); Object.defineProperty(this, _postProcessors, { writable: true, value: /* @__PURE__ */ new Set() }); this.scheduledAutoProceed = null; this.wasOffline = false; Object.defineProperty(this, _handleUploadProgress, { writable: true, value: (file, progress) => { const fileInState = file ? this.getFile(file.id) : void 0; if (file == null || !fileInState) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } if (fileInState.progress.percentage === 100) { this.log(`Not setting progress for a file that has been already uploaded: ${file.id}`); return; } const newProgress = { bytesTotal: progress.bytesTotal, // bytesTotal may be null or zero; in that case we can't divide by it percentage: progress.bytesTotal != null && Number.isFinite(progress.bytesTotal) && progress.bytesTotal > 0 ? Math.round(progress.bytesUploaded / progress.bytesTotal * 100) : void 0 }; if (fileInState.progress.uploadStarted != null) { this.setFileState(file.id, { progress: { ...fileInState.progress, ...newProgress, bytesUploaded: progress.bytesUploaded } }); } else { this.setFileState(file.id, { progress: { ...fileInState.progress, ...newProgress } }); } _classPrivateFieldLooseBase3(this, _updateTotalProgressThrottled)[_updateTotalProgressThrottled](); } }); Object.defineProperty(this, _updateTotalProgressThrottled, { writable: true, value: (0, import_throttle.default)(() => _classPrivateFieldLooseBase3(this, _updateTotalProgress)[_updateTotalProgress](), 500, { leading: true, trailing: true }) }); Object.defineProperty(this, _updateOnlineStatus, { writable: true, value: this.updateOnlineStatus.bind(this) }); Object.defineProperty(this, _requestClientById, { writable: true, value: /* @__PURE__ */ new Map() }); this.defaultLocale = locale_default; const defaultOptions8 = { id: "uppy", autoProceed: false, allowMultipleUploadBatches: true, debug: false, restrictions: defaultOptions, meta: {}, onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id), onBeforeUpload: (files) => files, store: new lib_default(), logger: justErrorsLogger, infoTimeout: 5e3 }; const merged = { ...defaultOptions8, ..._opts }; this.opts = { ...merged, restrictions: { ...defaultOptions8.restrictions, ..._opts && _opts.restrictions } }; if (_opts && _opts.logger && _opts.debug) { this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.", "warning"); } else if (_opts && _opts.debug) { this.opts.logger = debugLogger; } this.log(`Using Core v${_Uppy.VERSION}`); this.i18nInit(); this.store = this.opts.store; this.setState({ ...defaultUploadState, plugins: {}, files: {}, currentUploads: {}, capabilities: { uploadProgress: supportsUploadProgress(), individualCancellation: true, resumableUploads: false }, meta: { ...this.opts.meta }, info: [] }); _classPrivateFieldLooseBase3(this, _restricter)[_restricter] = new Restricter(() => this.opts, () => this.i18n); _classPrivateFieldLooseBase3(this, _storeUnsubscribe)[_storeUnsubscribe] = this.store.subscribe((prevState, nextState, patch) => { this.emit("state-update", prevState, nextState, patch); this.updateAll(nextState); }); if (this.opts.debug && typeof window !== "undefined") { window[this.opts.id] = this; } _classPrivateFieldLooseBase3(this, _addListeners)[_addListeners](); } emit(event) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } _classPrivateFieldLooseBase3(this, _emitter)[_emitter].emit(event, ...args); } on(event, callback) { _classPrivateFieldLooseBase3(this, _emitter)[_emitter].on(event, callback); return this; } once(event, callback) { _classPrivateFieldLooseBase3(this, _emitter)[_emitter].once(event, callback); return this; } off(event, callback) { _classPrivateFieldLooseBase3(this, _emitter)[_emitter].off(event, callback); return this; } /** * Iterate on all plugins and run `update` on them. * Called each time state changes. * */ updateAll(state) { this.iteratePlugins((plugin) => { plugin.update(state); }); } /** * Updates state with a patch */ setState(patch) { this.store.setState(patch); } /** * Returns current state. */ getState() { return this.store.getState(); } patchFilesState(filesWithNewState) { const existingFilesState = this.getState().files; this.setState({ files: { ...existingFilesState, ...Object.fromEntries(Object.entries(filesWithNewState).map((_ref) => { let [fileID, newFileState] = _ref; return [fileID, { ...existingFilesState[fileID], ...newFileState }]; })) } }); } /** * Shorthand to set state for a specific file. */ setFileState(fileID, state) { if (!this.getState().files[fileID]) { throw new Error(`Can\u2019t set state for ${fileID} (the file could have been removed)`); } this.patchFilesState({ [fileID]: state }); } i18nInit() { const onMissingKey = (key) => this.log(`Missing i18n string: ${key}`, "error"); const translator = new Translator([this.defaultLocale, this.opts.locale], { onMissingKey }); this.i18n = translator.translate.bind(translator); this.i18nArray = translator.translateArray.bind(translator); this.locale = translator.locale; } setOptions(newOpts) { this.opts = { ...this.opts, ...newOpts, restrictions: { ...this.opts.restrictions, ...newOpts == null ? void 0 : newOpts.restrictions } }; if (newOpts.meta) { this.setMeta(newOpts.meta); } this.i18nInit(); if (newOpts.locale) { this.iteratePlugins((plugin) => { plugin.setOptions(newOpts); }); } this.setState(void 0); } resetProgress() { const defaultProgress = { percentage: 0, bytesUploaded: false, uploadComplete: false, uploadStarted: null }; const files = { ...this.getState().files }; const updatedFiles = /* @__PURE__ */ Object.create(null); Object.keys(files).forEach((fileID) => { updatedFiles[fileID] = { ...files[fileID], progress: { ...files[fileID].progress, ...defaultProgress }, // @ts-expect-error these typed are inserted // into the namespace in their respective packages // but core isn't ware of those tus: void 0, transloadit: void 0 }; }); this.setState({ files: updatedFiles, ...defaultUploadState }); } clear() { const { capabilities, currentUploads } = this.getState(); if (Object.keys(currentUploads).length > 0 && !capabilities.individualCancellation) { throw new Error("The installed uploader plugin does not allow removing files during an upload."); } this.setState({ ...defaultUploadState, files: {} }); } addPreProcessor(fn2) { _classPrivateFieldLooseBase3(this, _preProcessors)[_preProcessors].add(fn2); } removePreProcessor(fn2) { return _classPrivateFieldLooseBase3(this, _preProcessors)[_preProcessors].delete(fn2); } addPostProcessor(fn2) { _classPrivateFieldLooseBase3(this, _postProcessors)[_postProcessors].add(fn2); } removePostProcessor(fn2) { return _classPrivateFieldLooseBase3(this, _postProcessors)[_postProcessors].delete(fn2); } addUploader(fn2) { _classPrivateFieldLooseBase3(this, _uploaders)[_uploaders].add(fn2); } removeUploader(fn2) { return _classPrivateFieldLooseBase3(this, _uploaders)[_uploaders].delete(fn2); } setMeta(data) { const updatedMeta = { ...this.getState().meta, ...data }; const updatedFiles = { ...this.getState().files }; Object.keys(updatedFiles).forEach((fileID) => { updatedFiles[fileID] = { ...updatedFiles[fileID], meta: { ...updatedFiles[fileID].meta, ...data } }; }); this.log("Adding metadata:"); this.log(data); this.setState({ meta: updatedMeta, files: updatedFiles }); } setFileMeta(fileID, data) { const updatedFiles = { ...this.getState().files }; if (!updatedFiles[fileID]) { this.log(`Was trying to set metadata for a file that has been removed: ${fileID}`); return; } const newMeta = { ...updatedFiles[fileID].meta, ...data }; updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }; this.setState({ files: updatedFiles }); } /** * Get a file object. */ getFile(fileID) { return this.getState().files[fileID]; } /** * Get all files in an array. */ getFiles() { const { files } = this.getState(); return Object.values(files); } getFilesByIds(ids) { return ids.map((id12) => this.getFile(id12)); } getObjectOfFilesPerState() { const { files: filesObject, totalProgress, error: error2 } = this.getState(); const files = Object.values(filesObject); const inProgressFiles = []; const newFiles = []; const startedFiles = []; const uploadStartedFiles = []; const pausedFiles = []; const completeFiles = []; const erroredFiles = []; const inProgressNotPausedFiles = []; const processingFiles = []; for (const file of files) { const { progress } = file; if (!progress.uploadComplete && progress.uploadStarted) { inProgressFiles.push(file); if (!file.isPaused) { inProgressNotPausedFiles.push(file); } } if (!progress.uploadStarted) { newFiles.push(file); } if (progress.uploadStarted || progress.preprocess || progress.postprocess) { startedFiles.push(file); } if (progress.uploadStarted) { uploadStartedFiles.push(file); } if (file.isPaused) { pausedFiles.push(file); } if (progress.uploadComplete) { completeFiles.push(file); } if (file.error) { erroredFiles.push(file); } if (progress.preprocess || progress.postprocess) { processingFiles.push(file); } } return { newFiles, startedFiles, uploadStartedFiles, pausedFiles, completeFiles, erroredFiles, inProgressFiles, inProgressNotPausedFiles, processingFiles, isUploadStarted: uploadStartedFiles.length > 0, isAllComplete: totalProgress === 100 && completeFiles.length === files.length && processingFiles.length === 0, isAllErrored: !!error2 && erroredFiles.length === files.length, isAllPaused: inProgressFiles.length !== 0 && pausedFiles.length === inProgressFiles.length, isUploadInProgress: inProgressFiles.length > 0, isSomeGhost: files.some((file) => file.isGhost) }; } validateRestrictions(file, files) { if (files === void 0) { files = this.getFiles(); } try { _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validate(files, [file]); } catch (err) { return err; } return null; } validateSingleFile(file) { try { _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validateSingleFile(file); } catch (err) { return err.message; } return null; } validateAggregateRestrictions(files) { const existingFiles = this.getFiles(); try { _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validateAggregateRestrictions(existingFiles, files); } catch (err) { return err.message; } return null; } checkIfFileAlreadyExists(fileID) { const { files } = this.getState(); if (files[fileID] && !files[fileID].isGhost) { return true; } return false; } /** * Add a new file to `state.files`. This will run `onBeforeFileAdded`, * try to guess file type in a clever way, check file against restrictions, * and start an upload if `autoProceed === true`. */ addFile(file) { _classPrivateFieldLooseBase3(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](file); const { nextFilesState, validFilesToAdd, errors } = _classPrivateFieldLooseBase3(this, _checkAndUpdateFileState)[_checkAndUpdateFileState]([file]); const restrictionErrors = errors.filter((error2) => error2.isRestriction); _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit](restrictionErrors); if (errors.length > 0) throw errors[0]; this.setState({ files: nextFilesState }); const [firstValidFileToAdd] = validFilesToAdd; this.emit("file-added", firstValidFileToAdd); this.emit("files-added", validFilesToAdd); this.log(`Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`); _classPrivateFieldLooseBase3(this, _startIfAutoProceed)[_startIfAutoProceed](); return firstValidFileToAdd.id; } /** * Add multiple files to `state.files`. See the `addFile()` documentation. * * If an error occurs while adding a file, it is logged and the user is notified. * This is good for UI plugins, but not for programmatic use. * Programmatic users should usually still use `addFile()` on individual files. */ addFiles(fileDescriptors) { _classPrivateFieldLooseBase3(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](); const { nextFilesState, validFilesToAdd, errors } = _classPrivateFieldLooseBase3(this, _checkAndUpdateFileState)[_checkAndUpdateFileState](fileDescriptors); const restrictionErrors = errors.filter((error2) => error2.isRestriction); _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit](restrictionErrors); const nonRestrictionErrors = errors.filter((error2) => !error2.isRestriction); if (nonRestrictionErrors.length > 0) { let message = "Multiple errors occurred while adding files:\n"; nonRestrictionErrors.forEach((subError) => { message += ` * ${subError.message}`; }); this.info({ message: this.i18n("addBulkFilesFailed", { smart_count: nonRestrictionErrors.length }), details: message }, "error", this.opts.infoTimeout); if (typeof AggregateError === "function") { throw new AggregateError(nonRestrictionErrors, message); } else { const err = new Error(message); err.errors = nonRestrictionErrors; throw err; } } this.setState({ files: nextFilesState }); validFilesToAdd.forEach((file) => { this.emit("file-added", file); }); this.emit("files-added", validFilesToAdd); if (validFilesToAdd.length > 5) { this.log(`Added batch of ${validFilesToAdd.length} files`); } else { Object.values(validFilesToAdd).forEach((file) => { this.log(`Added file: ${file.name} id: ${file.id} type: ${file.type}`); }); } if (validFilesToAdd.length > 0) { _classPrivateFieldLooseBase3(this, _startIfAutoProceed)[_startIfAutoProceed](); } } removeFiles(fileIDs) { const { files, currentUploads } = this.getState(); const updatedFiles = { ...files }; const updatedUploads = { ...currentUploads }; const removedFiles = /* @__PURE__ */ Object.create(null); fileIDs.forEach((fileID) => { if (files[fileID]) { removedFiles[fileID] = files[fileID]; delete updatedFiles[fileID]; } }); function fileIsNotRemoved(uploadFileID) { return removedFiles[uploadFileID] === void 0; } Object.keys(updatedUploads).forEach((uploadID) => { const newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved); if (newFileIDs.length === 0) { delete updatedUploads[uploadID]; return; } const { capabilities } = this.getState(); if (newFileIDs.length !== currentUploads[uploadID].fileIDs.length && !capabilities.individualCancellation) { throw new Error("The installed uploader plugin does not allow removing files during an upload."); } updatedUploads[uploadID] = { ...currentUploads[uploadID], fileIDs: newFileIDs }; }); const stateUpdate = { currentUploads: updatedUploads, files: updatedFiles }; if (Object.keys(updatedFiles).length === 0) { stateUpdate.allowNewUpload = true; stateUpdate.error = null; stateUpdate.recoveredState = null; } this.setState(stateUpdate); _classPrivateFieldLooseBase3(this, _updateTotalProgressThrottled)[_updateTotalProgressThrottled](); const removedFileIDs = Object.keys(removedFiles); removedFileIDs.forEach((fileID) => { this.emit("file-removed", removedFiles[fileID]); }); if (removedFileIDs.length > 5) { this.log(`Removed ${removedFileIDs.length} files`); } else { this.log(`Removed files: ${removedFileIDs.join(", ")}`); } } removeFile(fileID) { this.removeFiles([fileID]); } pauseResume(fileID) { if (!this.getState().capabilities.resumableUploads || this.getFile(fileID).progress.uploadComplete) { return void 0; } const file = this.getFile(fileID); const wasPaused = file.isPaused || false; const isPaused = !wasPaused; this.setFileState(fileID, { isPaused }); this.emit("upload-pause", file, isPaused); return isPaused; } pauseAll() { const updatedFiles = { ...this.getState().files }; const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => { return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted; }); inProgressUpdatedFiles.forEach((file) => { const updatedFile = { ...updatedFiles[file], isPaused: true }; updatedFiles[file] = updatedFile; }); this.setState({ files: updatedFiles }); this.emit("pause-all"); } resumeAll() { const updatedFiles = { ...this.getState().files }; const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => { return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted; }); inProgressUpdatedFiles.forEach((file) => { const updatedFile = { ...updatedFiles[file], isPaused: false, error: null }; updatedFiles[file] = updatedFile; }); this.setState({ files: updatedFiles }); this.emit("resume-all"); } retryAll() { const updatedFiles = { ...this.getState().files }; const filesToRetry = Object.keys(updatedFiles).filter((file) => { return updatedFiles[file].error; }); filesToRetry.forEach((file) => { const updatedFile = { ...updatedFiles[file], isPaused: false, error: null }; updatedFiles[file] = updatedFile; }); this.setState({ files: updatedFiles, error: null }); this.emit("retry-all", Object.values(updatedFiles)); if (filesToRetry.length === 0) { return Promise.resolve({ successful: [], failed: [] }); } const uploadID = _classPrivateFieldLooseBase3(this, _createUpload)[_createUpload](filesToRetry, { forceAllowNewUpload: true // create new upload even if allowNewUpload: false }); return _classPrivateFieldLooseBase3(this, _runUpload)[_runUpload](uploadID); } cancelAll() { this.emit("cancel-all"); const { files } = this.getState(); const fileIDs = Object.keys(files); if (fileIDs.length) { this.removeFiles(fileIDs); } this.setState(defaultUploadState); } retryUpload(fileID) { this.setFileState(fileID, { error: null, isPaused: false }); this.emit("upload-retry", this.getFile(fileID)); const uploadID = _classPrivateFieldLooseBase3(this, _createUpload)[_createUpload]([fileID], { forceAllowNewUpload: true // create new upload even if allowNewUpload: false }); return _classPrivateFieldLooseBase3(this, _runUpload)[_runUpload](uploadID); } logout() { this.iteratePlugins((plugin) => { var _provider; ; (_provider = plugin.provider) == null || _provider.logout == null || _provider.logout(); }); } // eslint-disable-next-line class-methods-use-this, @typescript-eslint/explicit-module-boundary-types [Symbol.for("uppy test: updateTotalProgress")]() { return _classPrivateFieldLooseBase3(this, _updateTotalProgress)[_updateTotalProgress](); } updateOnlineStatus() { var _window$navigator$onL; const online = (_window$navigator$onL = window.navigator.onLine) != null ? _window$navigator$onL : true; if (!online) { this.emit("is-offline"); this.info(this.i18n("noInternetConnection"), "error", 0); this.wasOffline = true; } else { this.emit("is-online"); if (this.wasOffline) { this.emit("back-online"); this.info(this.i18n("connectedToInternet"), "success", 3e3); this.wasOffline = false; } } } getID() { return this.opts.id; } /** * Registers a plugin with Core. */ use(Plugin) { if (typeof Plugin !== "function") { const msg = `Expected a plugin class, but got ${Plugin === null ? "null" : typeof Plugin}. Please verify that the plugin was imported and spelled correctly.`; throw new TypeError(msg); } for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } const plugin = new Plugin(this, ...args); const pluginId = plugin.id; if (!pluginId) { throw new Error("Your plugin must have an id"); } if (!plugin.type) { throw new Error("Your plugin must have a type"); } const existsPluginAlready = this.getPlugin(pluginId); if (existsPluginAlready) { const msg = `Already found a plugin named '${existsPluginAlready.id}'. Tried to use: '${pluginId}'. Uppy plugins must have unique \`id\` options.`; throw new Error(msg); } if (Plugin.VERSION) { this.log(`Using ${pluginId} v${Plugin.VERSION}`); } if (plugin.type in _classPrivateFieldLooseBase3(this, _plugins)[_plugins]) { _classPrivateFieldLooseBase3(this, _plugins)[_plugins][plugin.type].push(plugin); } else { _classPrivateFieldLooseBase3(this, _plugins)[_plugins][plugin.type] = [plugin]; } plugin.install(); this.emit("plugin-added", plugin); return this; } /** * Find one Plugin by name. */ getPlugin(id12) { for (const plugins of Object.values(_classPrivateFieldLooseBase3(this, _plugins)[_plugins])) { const foundPlugin = plugins.find((plugin) => plugin.id === id12); if (foundPlugin != null) return foundPlugin; } return void 0; } [Symbol.for("uppy test: getPlugins")](type) { return _classPrivateFieldLooseBase3(this, _plugins)[_plugins][type]; } /** * Iterate through all `use`d plugins. * */ iteratePlugins(method) { Object.values(_classPrivateFieldLooseBase3(this, _plugins)[_plugins]).flat(1).forEach(method); } /** * Uninstall and remove a plugin. * * @param {object} instance The plugin instance to remove. */ removePlugin(instance) { this.log(`Removing plugin ${instance.id}`); this.emit("plugin-remove", instance); if (instance.uninstall) { instance.uninstall(); } const list2 = _classPrivateFieldLooseBase3(this, _plugins)[_plugins][instance.type]; const index = list2.findIndex((item) => item.id === instance.id); if (index !== -1) { list2.splice(index, 1); } const state = this.getState(); const updatedState = { plugins: { ...state.plugins, [instance.id]: void 0 } }; this.setState(updatedState); } /** * Uninstall all plugins and close down this Uppy instance. */ destroy() { this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`); this.cancelAll(); _classPrivateFieldLooseBase3(this, _storeUnsubscribe)[_storeUnsubscribe](); this.iteratePlugins((plugin) => { this.removePlugin(plugin); }); if (typeof window !== "undefined" && window.removeEventListener) { window.removeEventListener("online", _classPrivateFieldLooseBase3(this, _updateOnlineStatus)[_updateOnlineStatus]); window.removeEventListener("offline", _classPrivateFieldLooseBase3(this, _updateOnlineStatus)[_updateOnlineStatus]); } } hideInfo() { const { info } = this.getState(); this.setState({ info: info.slice(1) }); this.emit("info-hidden"); } /** * Set info message in `state.info`, so that UI plugins like `Informer` * can display the message. */ info(message, type, duration2) { if (type === void 0) { type = "info"; } if (duration2 === void 0) { duration2 = 3e3; } const isComplexMessage = typeof message === "object"; this.setState({ info: [...this.getState().info, { type, message: isComplexMessage ? message.message : message, details: isComplexMessage ? message.details : null }] }); setTimeout(() => this.hideInfo(), duration2); this.emit("info-visible"); } /** * Passes messages to a function, provided in `opts.logger`. * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console. */ log(message, type) { const { logger } = this.opts; switch (type) { case "error": logger.error(message); break; case "warning": logger.warn(message); break; default: logger.debug(message); break; } } registerRequestClient(id12, client) { _classPrivateFieldLooseBase3(this, _requestClientById)[_requestClientById].set(id12, client); } /** @protected */ getRequestClientForFile(file) { if (!file.remote) throw new Error(`Tried to get RequestClient for a non-remote file ${file.id}`); const requestClient = _classPrivateFieldLooseBase3(this, _requestClientById)[_requestClientById].get(file.remote.requestClientId); if (requestClient == null) throw new Error(`requestClientId "${file.remote.requestClientId}" not registered for file "${file.id}"`); return requestClient; } /** * Restore an upload by its ID. */ restore(uploadID) { this.log(`Core: attempting to restore upload "${uploadID}"`); if (!this.getState().currentUploads[uploadID]) { _classPrivateFieldLooseBase3(this, _removeUpload)[_removeUpload](uploadID); return Promise.reject(new Error("Nonexistent upload")); } return _classPrivateFieldLooseBase3(this, _runUpload)[_runUpload](uploadID); } [Symbol.for("uppy test: createUpload")]() { return _classPrivateFieldLooseBase3(this, _createUpload)[_createUpload](...arguments); } /** * Add data to an upload's result object. */ addResultData(uploadID, data) { if (!_classPrivateFieldLooseBase3(this, _getUpload)[_getUpload](uploadID)) { this.log(`Not setting result for an upload that has been removed: ${uploadID}`); return; } const { currentUploads } = this.getState(); const currentUpload = { ...currentUploads[uploadID], result: { ...currentUploads[uploadID].result, ...data } }; this.setState({ currentUploads: { ...currentUploads, [uploadID]: currentUpload } }); } /** * Start an upload for all the files that are not currently being uploaded. */ upload() { var _classPrivateFieldLoo; if (!((_classPrivateFieldLoo = _classPrivateFieldLooseBase3(this, _plugins)[_plugins]["uploader"]) != null && _classPrivateFieldLoo.length)) { this.log("No uploader type plugins are used", "warning"); } let { files } = this.getState(); const onBeforeUploadResult = this.opts.onBeforeUpload(files); if (onBeforeUploadResult === false) { return Promise.reject(new Error("Not starting the upload because onBeforeUpload returned false")); } if (onBeforeUploadResult && typeof onBeforeUploadResult === "object") { files = onBeforeUploadResult; this.setState({ files }); } return Promise.resolve().then(() => _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validateMinNumberOfFiles(files)).catch((err) => { _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit]([err]); throw err; }).then(() => { if (!_classPrivateFieldLooseBase3(this, _checkRequiredMetaFields)[_checkRequiredMetaFields](files)) { throw new RestrictionError(this.i18n("missingRequiredMetaField")); } }).catch((err) => { throw err; }).then(() => { const { currentUploads } = this.getState(); const currentlyUploadingFiles = Object.values(currentUploads).flatMap((curr) => curr.fileIDs); const waitingFileIDs = []; Object.keys(files).forEach((fileID) => { const file = this.getFile(fileID); if (!file.progress.uploadStarted && currentlyUploadingFiles.indexOf(fileID) === -1) { waitingFileIDs.push(file.id); } }); const uploadID = _classPrivateFieldLooseBase3(this, _createUpload)[_createUpload](waitingFileIDs); return _classPrivateFieldLooseBase3(this, _runUpload)[_runUpload](uploadID); }).catch((err) => { this.emit("error", err); this.log(err, "error"); throw err; }); } }; function _informAndEmit2(errors) { for (const error2 of errors) { if (error2.isRestriction) { this.emit("restriction-failed", error2.file, error2); } else { this.emit("error", error2, error2.file); } this.log(error2, "warning"); } const userFacingErrors = errors.filter((error2) => error2.isUserFacing); const maxNumToShow = 4; const firstErrors = userFacingErrors.slice(0, maxNumToShow); const additionalErrors = userFacingErrors.slice(maxNumToShow); firstErrors.forEach((_ref2) => { let { message, details = "" } = _ref2; this.info({ message, details }, "error", this.opts.infoTimeout); }); if (additionalErrors.length > 0) { this.info({ message: this.i18n("additionalRestrictionsFailed", { count: additionalErrors.length }) }); } } function _checkRequiredMetaFieldsOnFile2(file) { const { missingFields, error: error2 } = _classPrivateFieldLooseBase3(this, _restricter)[_restricter].getMissingRequiredMetaFields(file); if (missingFields.length > 0) { this.setFileState(file.id, { missingRequiredMetaFields: missingFields }); this.log(error2.message); this.emit("restriction-failed", file, error2); return false; } return true; } function _checkRequiredMetaFields2(files) { let success = true; for (const file of Object.values(files)) { if (!_classPrivateFieldLooseBase3(this, _checkRequiredMetaFieldsOnFile)[_checkRequiredMetaFieldsOnFile](file)) { success = false; } } return success; } function _assertNewUploadAllowed2(file) { const { allowNewUpload } = this.getState(); if (allowNewUpload === false) { const error2 = new RestrictionError(this.i18n("noMoreFilesAllowed"), { file }); _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit]([error2]); throw error2; } } function _transformFile2(fileDescriptorOrFile) { const file = fileDescriptorOrFile instanceof File ? { name: fileDescriptorOrFile.name, type: fileDescriptorOrFile.type, size: fileDescriptorOrFile.size, data: fileDescriptorOrFile } : fileDescriptorOrFile; const fileType = getFileType(file); const fileName = getFileName(fileType, file); const fileExtension = getFileNameAndExtension(fileName).extension; const id12 = getSafeFileId(file, this.getID()); const meta = file.meta || {}; meta.name = fileName; meta.type = fileType; const size = Number.isFinite(file.data.size) ? file.data.size : null; return { source: file.source || "", id: id12, name: fileName, extension: fileExtension || "", meta: { ...this.getState().meta, ...meta }, type: fileType, data: file.data, progress: { percentage: 0, bytesUploaded: false, bytesTotal: size, uploadComplete: false, uploadStarted: null }, size, isGhost: false, isRemote: file.isRemote || false, remote: file.remote, preview: file.preview }; } function _startIfAutoProceed2() { if (this.opts.autoProceed && !this.scheduledAutoProceed) { this.scheduledAutoProceed = setTimeout(() => { this.scheduledAutoProceed = null; this.upload().catch((err) => { if (!err.isRestriction) { this.log(err.stack || err.message || err); } }); }, 4); } } function _checkAndUpdateFileState2(filesToAdd) { const { files: existingFiles } = this.getState(); const nextFilesState = { ...existingFiles }; const validFilesToAdd = []; const errors = []; for (const fileToAdd of filesToAdd) { try { var _existingFiles$newFil; let newFile = _classPrivateFieldLooseBase3(this, _transformFile)[_transformFile](fileToAdd); const isGhost = (_existingFiles$newFil = existingFiles[newFile.id]) == null ? void 0 : _existingFiles$newFil.isGhost; if (isGhost) { const existingFileState = existingFiles[newFile.id]; newFile = { ...existingFileState, isGhost: false, data: fileToAdd.data }; this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`); } const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, nextFilesState); if (!onBeforeFileAddedResult && this.checkIfFileAlreadyExists(newFile.id)) { var _newFile$name; throw new RestrictionError(this.i18n("noDuplicates", { fileName: (_newFile$name = newFile.name) != null ? _newFile$name : this.i18n("unnamed") }), { file: fileToAdd }); } if (onBeforeFileAddedResult === false && !isGhost) { throw new RestrictionError("Cannot add the file because onBeforeFileAdded returned false.", { isUserFacing: false, file: fileToAdd }); } else if (typeof onBeforeFileAddedResult === "object" && onBeforeFileAddedResult !== null) { newFile = onBeforeFileAddedResult; } _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validateSingleFile(newFile); nextFilesState[newFile.id] = newFile; validFilesToAdd.push(newFile); } catch (err) { errors.push(err); } } try { _classPrivateFieldLooseBase3(this, _restricter)[_restricter].validateAggregateRestrictions(Object.values(existingFiles), validFilesToAdd); } catch (err) { errors.push(err); return { nextFilesState: existingFiles, validFilesToAdd: [], errors }; } return { nextFilesState, validFilesToAdd, errors }; } function _updateTotalProgress2() { var _totalProgressPercent, _totalProgressPercent2; const totalProgress = _classPrivateFieldLooseBase3(this, _calculateTotalProgress)[_calculateTotalProgress](); let totalProgressPercent = null; if (totalProgress != null) { totalProgressPercent = Math.round(totalProgress * 100); if (totalProgressPercent > 100) totalProgressPercent = 100; else if (totalProgressPercent < 0) totalProgressPercent = 0; } this.emit("progress", (_totalProgressPercent = totalProgressPercent) != null ? _totalProgressPercent : 0); this.setState({ totalProgress: (_totalProgressPercent2 = totalProgressPercent) != null ? _totalProgressPercent2 : 0 }); } function _calculateTotalProgress2() { const files = this.getFiles(); const filesInProgress = files.filter((file) => { return file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess; }); if (filesInProgress.length === 0) { return 0; } if (filesInProgress.every((file) => file.progress.uploadComplete)) { return 1; } const isSizedFile = (file) => file.progress.bytesTotal != null && file.progress.bytesTotal !== 0; const sizedFilesInProgress = filesInProgress.filter(isSizedFile); const unsizedFilesInProgress = filesInProgress.filter((file) => !isSizedFile(file)); if (sizedFilesInProgress.every((file) => file.progress.uploadComplete) && unsizedFilesInProgress.length > 0 && !unsizedFilesInProgress.every((file) => file.progress.uploadComplete)) { return null; } const totalFilesSize = sizedFilesInProgress.reduce((acc, file) => { var _file$progress$bytesT; return acc + ((_file$progress$bytesT = file.progress.bytesTotal) != null ? _file$progress$bytesT : 0); }, 0); const totalUploadedSize = sizedFilesInProgress.reduce((acc, file) => acc + (file.progress.bytesUploaded || 0), 0); return totalFilesSize === 0 ? 0 : totalUploadedSize / totalFilesSize; } function _addListeners2() { const errorHandler = (error2, file, response) => { let errorMsg = error2.message || "Unknown error"; if (error2.details) { errorMsg += ` ${error2.details}`; } this.setState({ error: errorMsg }); if (file != null && file.id in this.getState().files) { this.setFileState(file.id, { error: errorMsg, response }); } }; this.on("error", errorHandler); this.on("upload-error", (file, error2, response) => { errorHandler(error2, file, response); if (typeof error2 === "object" && error2.message) { var _file$name; this.log(error2.message, "error"); const newError = new Error(this.i18n("failedToUpload", { file: (_file$name = file == null ? void 0 : file.name) != null ? _file$name : "" })); newError.isUserFacing = true; newError.details = error2.message; if (error2.details) { newError.details += ` ${error2.details}`; } _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit]([newError]); } else { _classPrivateFieldLooseBase3(this, _informAndEmit)[_informAndEmit]([error2]); } }); let uploadStalledWarningRecentlyEmitted = null; this.on("upload-stalled", (error2, files) => { const { message } = error2; const details = files.map((file) => file.meta.name).join(", "); if (!uploadStalledWarningRecentlyEmitted) { this.info({ message, details }, "warning", this.opts.infoTimeout); uploadStalledWarningRecentlyEmitted = setTimeout(() => { uploadStalledWarningRecentlyEmitted = null; }, this.opts.infoTimeout); } this.log(`${message} ${details}`.trim(), "warning"); }); this.on("upload", () => { this.setState({ error: null }); }); const onUploadStarted = (files) => { const filesFiltered = files.filter((file) => { const exists = file != null && this.getFile(file.id); if (!exists) this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return exists; }); const filesState = Object.fromEntries(filesFiltered.map((file) => [file.id, { progress: { uploadStarted: Date.now(), uploadComplete: false, bytesUploaded: 0, bytesTotal: file.size } }])); this.patchFilesState(filesState); }; this.on("upload-start", onUploadStarted); this.on("upload-progress", _classPrivateFieldLooseBase3(this, _handleUploadProgress)[_handleUploadProgress]); this.on("upload-success", (file, uploadResp) => { if (file == null || !this.getFile(file.id)) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } const currentProgress = this.getFile(file.id).progress; this.setFileState(file.id, { progress: { ...currentProgress, postprocess: _classPrivateFieldLooseBase3(this, _postProcessors)[_postProcessors].size > 0 ? { mode: "indeterminate" } : void 0, uploadComplete: true, percentage: 100, bytesUploaded: currentProgress.bytesTotal }, response: uploadResp, uploadURL: uploadResp.uploadURL, isPaused: false }); if (file.size == null) { this.setFileState(file.id, { size: uploadResp.bytesUploaded || currentProgress.bytesTotal }); } _classPrivateFieldLooseBase3(this, _updateTotalProgressThrottled)[_updateTotalProgressThrottled](); }); this.on("preprocess-progress", (file, progress) => { if (file == null || !this.getFile(file.id)) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } this.setFileState(file.id, { progress: { ...this.getFile(file.id).progress, preprocess: progress } }); }); this.on("preprocess-complete", (file) => { if (file == null || !this.getFile(file.id)) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } const files = { ...this.getState().files }; files[file.id] = { ...files[file.id], progress: { ...files[file.id].progress } }; delete files[file.id].progress.preprocess; this.setState({ files }); }); this.on("postprocess-progress", (file, progress) => { if (file == null || !this.getFile(file.id)) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } this.setFileState(file.id, { progress: { ...this.getState().files[file.id].progress, postprocess: progress } }); }); this.on("postprocess-complete", (file) => { if (file == null || !this.getFile(file.id)) { this.log(`Not setting progress for a file that has been removed: ${file == null ? void 0 : file.id}`); return; } const files = { ...this.getState().files }; files[file.id] = { ...files[file.id], progress: { ...files[file.id].progress } }; delete files[file.id].progress.postprocess; this.setState({ files }); }); this.on("restored", () => { _classPrivateFieldLooseBase3(this, _updateTotalProgressThrottled)[_updateTotalProgressThrottled](); }); this.on("dashboard:file-edit-complete", (file) => { if (file) { _classPrivateFieldLooseBase3(this, _checkRequiredMetaFieldsOnFile)[_checkRequiredMetaFieldsOnFile](file); } }); if (typeof window !== "undefined" && window.addEventListener) { window.addEventListener("online", _classPrivateFieldLooseBase3(this, _updateOnlineStatus)[_updateOnlineStatus]); window.addEventListener("offline", _classPrivateFieldLooseBase3(this, _updateOnlineStatus)[_updateOnlineStatus]); setTimeout(_classPrivateFieldLooseBase3(this, _updateOnlineStatus)[_updateOnlineStatus], 3e3); } } function _createUpload2(fileIDs, opts) { if (opts === void 0) { opts = {}; } const { forceAllowNewUpload = false } = opts; const { allowNewUpload, currentUploads } = this.getState(); if (!allowNewUpload && !forceAllowNewUpload) { throw new Error("Cannot create a new upload: already uploading."); } const uploadID = nanoid(); this.emit("upload", uploadID, this.getFilesByIds(fileIDs)); this.setState({ allowNewUpload: this.opts.allowMultipleUploadBatches !== false && this.opts.allowMultipleUploads !== false, currentUploads: { ...currentUploads, [uploadID]: { fileIDs, step: 0, result: {} } } }); return uploadID; } function _getUpload2(uploadID) { const { currentUploads } = this.getState(); return currentUploads[uploadID]; } function _removeUpload2(uploadID) { const currentUploads = { ...this.getState().currentUploads }; delete currentUploads[uploadID]; this.setState({ currentUploads }); } async function _runUpload2(uploadID) { const getCurrentUpload = () => { const { currentUploads } = this.getState(); return currentUploads[uploadID]; }; let currentUpload = getCurrentUpload(); const steps = [..._classPrivateFieldLooseBase3(this, _preProcessors)[_preProcessors], ..._classPrivateFieldLooseBase3(this, _uploaders)[_uploaders], ..._classPrivateFieldLooseBase3(this, _postProcessors)[_postProcessors]]; try { for (let step = currentUpload.step || 0; step < steps.length; step++) { if (!currentUpload) { break; } const fn2 = steps[step]; this.setState({ currentUploads: { ...this.getState().currentUploads, [uploadID]: { ...currentUpload, step } } }); const { fileIDs } = currentUpload; await fn2(fileIDs, uploadID); currentUpload = getCurrentUpload(); } } catch (err) { _classPrivateFieldLooseBase3(this, _removeUpload)[_removeUpload](uploadID); throw err; } if (currentUpload) { currentUpload.fileIDs.forEach((fileID) => { const file = this.getFile(fileID); if (file && file.progress.postprocess) { this.emit("postprocess-complete", file); } }); const files = currentUpload.fileIDs.map((fileID) => this.getFile(fileID)); const successful = files.filter((file) => !file.error); const failed = files.filter((file) => file.error); this.addResultData(uploadID, { successful, failed, uploadID }); currentUpload = getCurrentUpload(); } let result; if (currentUpload) { result = currentUpload.result; this.emit("complete", result); _classPrivateFieldLooseBase3(this, _removeUpload)[_removeUpload](uploadID); } if (result == null) { this.log(`Not setting result for an upload that has been removed: ${uploadID}`); } return result; } Uppy.VERSION = packageJson2.version; var Uppy_default = Uppy; // node_modules/preact/dist/preact.module.js var n; var l; var u; var t; var i; var o; var r; var f; var e; var c; var s; var a; var h = {}; var v = []; var p = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i; var y = Array.isArray; function d(n3, l4) { for (var u4 in l4) n3[u4] = l4[u4]; return n3; } function w(n3) { n3 && n3.parentNode && n3.parentNode.removeChild(n3); } function _(l4, u4, t4) { var i4, o4, r4, f4 = {}; for (r4 in u4) "key" == r4 ? i4 = u4[r4] : "ref" == r4 ? o4 = u4[r4] : f4[r4] = u4[r4]; if (arguments.length > 2 && (f4.children = arguments.length > 3 ? n.call(arguments, 2) : t4), "function" == typeof l4 && null != l4.defaultProps) for (r4 in l4.defaultProps) void 0 === f4[r4] && (f4[r4] = l4.defaultProps[r4]); return g(l4, f4, i4, o4, null); } function g(n3, t4, i4, o4, r4) { var f4 = { type: n3, props: t4, key: i4, ref: o4, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, constructor: void 0, __v: null == r4 ? ++u : r4, __i: -1, __u: 0 }; return null == r4 && null != l.vnode && l.vnode(f4), f4; } function m() { return { current: null }; } function b(n3) { return n3.children; } function k(n3, l4) { this.props = n3, this.context = l4; } function x(n3, l4) { if (null == l4) return n3.__ ? x(n3.__, n3.__i + 1) : null; for (var u4; l4 < n3.__k.length; l4++) if (null != (u4 = n3.__k[l4]) && null != u4.__e) return u4.__e; return "function" == typeof n3.type ? x(n3) : null; } function C(n3) { var l4, u4; if (null != (n3 = n3.__) && null != n3.__c) { for (n3.__e = n3.__c.base = null, l4 = 0; l4 < n3.__k.length; l4++) if (null != (u4 = n3.__k[l4]) && null != u4.__e) { n3.__e = n3.__c.base = u4.__e; break; } return C(n3); } } function S(n3) { (!n3.__d && (n3.__d = true) && i.push(n3) && !M.__r++ || o !== l.debounceRendering) && ((o = l.debounceRendering) || r)(M); } function M() { var n3, u4, t4, o4, r4, e4, c4, s4; for (i.sort(f); n3 = i.shift(); ) n3.__d && (u4 = i.length, o4 = void 0, e4 = (r4 = (t4 = n3).__v).__e, c4 = [], s4 = [], t4.__P && ((o4 = d({}, r4)).__v = r4.__v + 1, l.vnode && l.vnode(o4), O(t4.__P, o4, r4, t4.__n, t4.__P.namespaceURI, 32 & r4.__u ? [e4] : null, c4, null == e4 ? x(r4) : e4, !!(32 & r4.__u), s4), o4.__v = r4.__v, o4.__.__k[o4.__i] = o4, j(c4, o4, s4), o4.__e != e4 && C(o4)), i.length > u4 && i.sort(f)); M.__r = 0; } function P(n3, l4, u4, t4, i4, o4, r4, f4, e4, c4, s4) { var a4, p4, y4, d4, w4, _3 = t4 && t4.__k || v, g3 = l4.length; for (u4.__d = e4, $(u4, l4, _3), e4 = u4.__d, a4 = 0; a4 < g3; a4++) null != (y4 = u4.__k[a4]) && (p4 = -1 === y4.__i ? h : _3[y4.__i] || h, y4.__i = a4, O(n3, y4, p4, i4, o4, r4, f4, e4, c4, s4), d4 = y4.__e, y4.ref && p4.ref != y4.ref && (p4.ref && N(p4.ref, null, y4), s4.push(y4.ref, y4.__c || d4, y4)), null == w4 && null != d4 && (w4 = d4), 65536 & y4.__u || p4.__k === y4.__k ? e4 = I(y4, e4, n3) : "function" == typeof y4.type && void 0 !== y4.__d ? e4 = y4.__d : d4 && (e4 = d4.nextSibling), y4.__d = void 0, y4.__u &= -196609); u4.__d = e4, u4.__e = w4; } function $(n3, l4, u4) { var t4, i4, o4, r4, f4, e4 = l4.length, c4 = u4.length, s4 = c4, a4 = 0; for (n3.__k = [], t4 = 0; t4 < e4; t4++) null != (i4 = l4[t4]) && "boolean" != typeof i4 && "function" != typeof i4 ? (r4 = t4 + a4, (i4 = n3.__k[t4] = "string" == typeof i4 || "number" == typeof i4 || "bigint" == typeof i4 || i4.constructor == String ? g(null, i4, null, null, null) : y(i4) ? g(b, { children: i4 }, null, null, null) : void 0 === i4.constructor && i4.__b > 0 ? g(i4.type, i4.props, i4.key, i4.ref ? i4.ref : null, i4.__v) : i4).__ = n3, i4.__b = n3.__b + 1, o4 = null, -1 !== (f4 = i4.__i = L(i4, u4, r4, s4)) && (s4--, (o4 = u4[f4]) && (o4.__u |= 131072)), null == o4 || null === o4.__v ? (-1 == f4 && a4--, "function" != typeof i4.type && (i4.__u |= 65536)) : f4 !== r4 && (f4 == r4 - 1 ? a4-- : f4 == r4 + 1 ? a4++ : (f4 > r4 ? a4-- : a4++, i4.__u |= 65536))) : i4 = n3.__k[t4] = null; if (s4) for (t4 = 0; t4 < c4; t4++) null != (o4 = u4[t4]) && 0 == (131072 & o4.__u) && (o4.__e == n3.__d && (n3.__d = x(o4)), V(o4, o4)); } function I(n3, l4, u4) { var t4, i4; if ("function" == typeof n3.type) { for (t4 = n3.__k, i4 = 0; t4 && i4 < t4.length; i4++) t4[i4] && (t4[i4].__ = n3, l4 = I(t4[i4], l4, u4)); return l4; } n3.__e != l4 && (l4 && n3.type && !u4.contains(l4) && (l4 = x(n3)), u4.insertBefore(n3.__e, l4 || null), l4 = n3.__e); do { l4 = l4 && l4.nextSibling; } while (null != l4 && 8 === l4.nodeType); return l4; } function H(n3, l4) { return l4 = l4 || [], null == n3 || "boolean" == typeof n3 || (y(n3) ? n3.some(function(n4) { H(n4, l4); }) : l4.push(n3)), l4; } function L(n3, l4, u4, t4) { var i4 = n3.key, o4 = n3.type, r4 = u4 - 1, f4 = u4 + 1, e4 = l4[u4]; if (null === e4 || e4 && i4 == e4.key && o4 === e4.type && 0 == (131072 & e4.__u)) return u4; if (t4 > (null != e4 && 0 == (131072 & e4.__u) ? 1 : 0)) for (; r4 >= 0 || f4 < l4.length; ) { if (r4 >= 0) { if ((e4 = l4[r4]) && 0 == (131072 & e4.__u) && i4 == e4.key && o4 === e4.type) return r4; r4--; } if (f4 < l4.length) { if ((e4 = l4[f4]) && 0 == (131072 & e4.__u) && i4 == e4.key && o4 === e4.type) return f4; f4++; } } return -1; } function T(n3, l4, u4) { "-" === l4[0] ? n3.setProperty(l4, null == u4 ? "" : u4) : n3[l4] = null == u4 ? "" : "number" != typeof u4 || p.test(l4) ? u4 : u4 + "px"; } function A(n3, l4, u4, t4, i4) { var o4; n: if ("style" === l4) if ("string" == typeof u4) n3.style.cssText = u4; else { if ("string" == typeof t4 && (n3.style.cssText = t4 = ""), t4) for (l4 in t4) u4 && l4 in u4 || T(n3.style, l4, ""); if (u4) for (l4 in u4) t4 && u4[l4] === t4[l4] || T(n3.style, l4, u4[l4]); } else if ("o" === l4[0] && "n" === l4[1]) o4 = l4 !== (l4 = l4.replace(/(PointerCapture)$|Capture$/i, "$1")), l4 = l4.toLowerCase() in n3 || "onFocusOut" === l4 || "onFocusIn" === l4 ? l4.toLowerCase().slice(2) : l4.slice(2), n3.l || (n3.l = {}), n3.l[l4 + o4] = u4, u4 ? t4 ? u4.u = t4.u : (u4.u = e, n3.addEventListener(l4, o4 ? s : c, o4)) : n3.removeEventListener(l4, o4 ? s : c, o4); else { if ("http://www.w3.org/2000/svg" == i4) l4 = l4.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" != l4 && "height" != l4 && "href" != l4 && "list" != l4 && "form" != l4 && "tabIndex" != l4 && "download" != l4 && "rowSpan" != l4 && "colSpan" != l4 && "role" != l4 && "popover" != l4 && l4 in n3) try { n3[l4] = null == u4 ? "" : u4; break n; } catch (n4) { } "function" == typeof u4 || (null == u4 || false === u4 && "-" !== l4[4] ? n3.removeAttribute(l4) : n3.setAttribute(l4, "popover" == l4 && 1 == u4 ? "" : u4)); } } function F(n3) { return function(u4) { if (this.l) { var t4 = this.l[u4.type + n3]; if (null == u4.t) u4.t = e++; else if (u4.t < t4.u) return; return t4(l.event ? l.event(u4) : u4); } }; } function O(n3, u4, t4, i4, o4, r4, f4, e4, c4, s4) { var a4, h4, v4, p4, w4, _3, g3, m4, x3, C4, S3, M3, $3, I3, H3, L3, T4 = u4.type; if (void 0 !== u4.constructor) return null; 128 & t4.__u && (c4 = !!(32 & t4.__u), r4 = [e4 = u4.__e = t4.__e]), (a4 = l.__b) && a4(u4); n: if ("function" == typeof T4) try { if (m4 = u4.props, x3 = "prototype" in T4 && T4.prototype.render, C4 = (a4 = T4.contextType) && i4[a4.__c], S3 = a4 ? C4 ? C4.props.value : a4.__ : i4, t4.__c ? g3 = (h4 = u4.__c = t4.__c).__ = h4.__E : (x3 ? u4.__c = h4 = new T4(m4, S3) : (u4.__c = h4 = new k(m4, S3), h4.constructor = T4, h4.render = q), C4 && C4.sub(h4), h4.props = m4, h4.state || (h4.state = {}), h4.context = S3, h4.__n = i4, v4 = h4.__d = true, h4.__h = [], h4._sb = []), x3 && null == h4.__s && (h4.__s = h4.state), x3 && null != T4.getDerivedStateFromProps && (h4.__s == h4.state && (h4.__s = d({}, h4.__s)), d(h4.__s, T4.getDerivedStateFromProps(m4, h4.__s))), p4 = h4.props, w4 = h4.state, h4.__v = u4, v4) x3 && null == T4.getDerivedStateFromProps && null != h4.componentWillMount && h4.componentWillMount(), x3 && null != h4.componentDidMount && h4.__h.push(h4.componentDidMount); else { if (x3 && null == T4.getDerivedStateFromProps && m4 !== p4 && null != h4.componentWillReceiveProps && h4.componentWillReceiveProps(m4, S3), !h4.__e && (null != h4.shouldComponentUpdate && false === h4.shouldComponentUpdate(m4, h4.__s, S3) || u4.__v === t4.__v)) { for (u4.__v !== t4.__v && (h4.props = m4, h4.state = h4.__s, h4.__d = false), u4.__e = t4.__e, u4.__k = t4.__k, u4.__k.some(function(n4) { n4 && (n4.__ = u4); }), M3 = 0; M3 < h4._sb.length; M3++) h4.__h.push(h4._sb[M3]); h4._sb = [], h4.__h.length && f4.push(h4); break n; } null != h4.componentWillUpdate && h4.componentWillUpdate(m4, h4.__s, S3), x3 && null != h4.componentDidUpdate && h4.__h.push(function() { h4.componentDidUpdate(p4, w4, _3); }); } if (h4.context = S3, h4.props = m4, h4.__P = n3, h4.__e = false, $3 = l.__r, I3 = 0, x3) { for (h4.state = h4.__s, h4.__d = false, $3 && $3(u4), a4 = h4.render(h4.props, h4.state, h4.context), H3 = 0; H3 < h4._sb.length; H3++) h4.__h.push(h4._sb[H3]); h4._sb = []; } else do { h4.__d = false, $3 && $3(u4), a4 = h4.render(h4.props, h4.state, h4.context), h4.state = h4.__s; } while (h4.__d && ++I3 < 25); h4.state = h4.__s, null != h4.getChildContext && (i4 = d(d({}, i4), h4.getChildContext())), x3 && !v4 && null != h4.getSnapshotBeforeUpdate && (_3 = h4.getSnapshotBeforeUpdate(p4, w4)), P(n3, y(L3 = null != a4 && a4.type === b && null == a4.key ? a4.props.children : a4) ? L3 : [L3], u4, t4, i4, o4, r4, f4, e4, c4, s4), h4.base = u4.__e, u4.__u &= -161, h4.__h.length && f4.push(h4), g3 && (h4.__E = h4.__ = null); } catch (n4) { if (u4.__v = null, c4 || null != r4) { for (u4.__u |= c4 ? 160 : 128; e4 && 8 === e4.nodeType && e4.nextSibling; ) e4 = e4.nextSibling; r4[r4.indexOf(e4)] = null, u4.__e = e4; } else u4.__e = t4.__e, u4.__k = t4.__k; l.__e(n4, u4, t4); } else null == r4 && u4.__v === t4.__v ? (u4.__k = t4.__k, u4.__e = t4.__e) : u4.__e = z(t4.__e, u4, t4, i4, o4, r4, f4, c4, s4); (a4 = l.diffed) && a4(u4); } function j(n3, u4, t4) { u4.__d = void 0; for (var i4 = 0; i4 < t4.length; i4++) N(t4[i4], t4[++i4], t4[++i4]); l.__c && l.__c(u4, n3), n3.some(function(u5) { try { n3 = u5.__h, u5.__h = [], n3.some(function(n4) { n4.call(u5); }); } catch (n4) { l.__e(n4, u5.__v); } }); } function z(u4, t4, i4, o4, r4, f4, e4, c4, s4) { var a4, v4, p4, d4, _3, g3, m4, b3 = i4.props, k4 = t4.props, C4 = t4.type; if ("svg" === C4 ? r4 = "http://www.w3.org/2000/svg" : "math" === C4 ? r4 = "http://www.w3.org/1998/Math/MathML" : r4 || (r4 = "http://www.w3.org/1999/xhtml"), null != f4) { for (a4 = 0; a4 < f4.length; a4++) if ((_3 = f4[a4]) && "setAttribute" in _3 == !!C4 && (C4 ? _3.localName === C4 : 3 === _3.nodeType)) { u4 = _3, f4[a4] = null; break; } } if (null == u4) { if (null === C4) return document.createTextNode(k4); u4 = document.createElementNS(r4, C4, k4.is && k4), c4 && (l.__m && l.__m(t4, f4), c4 = false), f4 = null; } if (null === C4) b3 === k4 || c4 && u4.data === k4 || (u4.data = k4); else { if (f4 = f4 && n.call(u4.childNodes), b3 = i4.props || h, !c4 && null != f4) for (b3 = {}, a4 = 0; a4 < u4.attributes.length; a4++) b3[(_3 = u4.attributes[a4]).name] = _3.value; for (a4 in b3) if (_3 = b3[a4], "children" == a4) ; else if ("dangerouslySetInnerHTML" == a4) p4 = _3; else if (!(a4 in k4)) { if ("value" == a4 && "defaultValue" in k4 || "checked" == a4 && "defaultChecked" in k4) continue; A(u4, a4, null, _3, r4); } for (a4 in k4) _3 = k4[a4], "children" == a4 ? d4 = _3 : "dangerouslySetInnerHTML" == a4 ? v4 = _3 : "value" == a4 ? g3 = _3 : "checked" == a4 ? m4 = _3 : c4 && "function" != typeof _3 || b3[a4] === _3 || A(u4, a4, _3, b3[a4], r4); if (v4) c4 || p4 && (v4.__html === p4.__html || v4.__html === u4.innerHTML) || (u4.innerHTML = v4.__html), t4.__k = []; else if (p4 && (u4.innerHTML = ""), P(u4, y(d4) ? d4 : [d4], t4, i4, o4, "foreignObject" === C4 ? "http://www.w3.org/1999/xhtml" : r4, f4, e4, f4 ? f4[0] : i4.__k && x(i4, 0), c4, s4), null != f4) for (a4 = f4.length; a4--; ) w(f4[a4]); c4 || (a4 = "value", "progress" === C4 && null == g3 ? u4.removeAttribute("value") : void 0 !== g3 && (g3 !== u4[a4] || "progress" === C4 && !g3 || "option" === C4 && g3 !== b3[a4]) && A(u4, a4, g3, b3[a4], r4), a4 = "checked", void 0 !== m4 && m4 !== u4[a4] && A(u4, a4, m4, b3[a4], r4)); } return u4; } function N(n3, u4, t4) { try { if ("function" == typeof n3) { var i4 = "function" == typeof n3.__u; i4 && n3.__u(), i4 && null == u4 || (n3.__u = n3(u4)); } else n3.current = u4; } catch (n4) { l.__e(n4, t4); } } function V(n3, u4, t4) { var i4, o4; if (l.unmount && l.unmount(n3), (i4 = n3.ref) && (i4.current && i4.current !== n3.__e || N(i4, null, u4)), null != (i4 = n3.__c)) { if (i4.componentWillUnmount) try { i4.componentWillUnmount(); } catch (n4) { l.__e(n4, u4); } i4.base = i4.__P = null; } if (i4 = n3.__k) for (o4 = 0; o4 < i4.length; o4++) i4[o4] && V(i4[o4], u4, t4 || "function" != typeof n3.type); t4 || w(n3.__e), n3.__c = n3.__ = n3.__e = n3.__d = void 0; } function q(n3, l4, u4) { return this.constructor(n3, u4); } function B(u4, t4, i4) { var o4, r4, f4, e4; l.__ && l.__(u4, t4), r4 = (o4 = "function" == typeof i4) ? null : i4 && i4.__k || t4.__k, f4 = [], e4 = [], O(t4, u4 = (!o4 && i4 || t4).__k = _(b, null, [u4]), r4 || h, h, t4.namespaceURI, !o4 && i4 ? [i4] : r4 ? null : t4.firstChild ? n.call(t4.childNodes) : null, f4, !o4 && i4 ? i4 : r4 ? r4.__e : t4.firstChild, o4, e4), j(f4, u4, e4); } function E(l4, u4, t4) { var i4, o4, r4, f4, e4 = d({}, l4.props); for (r4 in l4.type && l4.type.defaultProps && (f4 = l4.type.defaultProps), u4) "key" == r4 ? i4 = u4[r4] : "ref" == r4 ? o4 = u4[r4] : e4[r4] = void 0 === u4[r4] && void 0 !== f4 ? f4[r4] : u4[r4]; return arguments.length > 2 && (e4.children = arguments.length > 3 ? n.call(arguments, 2) : t4), g(l4.type, e4, i4 || l4.key, o4 || l4.ref, null); } n = v.slice, l = { __e: function(n3, l4, u4, t4) { for (var i4, o4, r4; l4 = l4.__; ) if ((i4 = l4.__c) && !i4.__) try { if ((o4 = i4.constructor) && null != o4.getDerivedStateFromError && (i4.setState(o4.getDerivedStateFromError(n3)), r4 = i4.__d), null != i4.componentDidCatch && (i4.componentDidCatch(n3, t4 || {}), r4 = i4.__d), r4) return i4.__E = i4; } catch (l5) { n3 = l5; } throw n3; } }, u = 0, t = function(n3) { return null != n3 && null == n3.constructor; }, k.prototype.setState = function(n3, l4) { var u4; u4 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = d({}, this.state), "function" == typeof n3 && (n3 = n3(d({}, u4), this.props)), n3 && d(u4, n3), null != n3 && this.__v && (l4 && this._sb.push(l4), S(this)); }, k.prototype.forceUpdate = function(n3) { this.__v && (this.__e = true, n3 && this.__h.push(n3), S(this)); }, k.prototype.render = b, i = [], r = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f = function(n3, l4) { return n3.__v.__b - l4.__v.__b; }, M.__r = 0, e = 0, c = F(false), s = F(true), a = 0; // node_modules/@uppy/utils/lib/isDOMElement.js function isDOMElement(obj) { if (typeof obj !== "object" || obj === null) return false; if (!("nodeType" in obj)) return false; return obj.nodeType === Node.ELEMENT_NODE; } // node_modules/@uppy/utils/lib/findDOMElement.js function findDOMElement(element, context) { if (context === void 0) { context = document; } if (typeof element === "string") { return context.querySelector(element); } if (isDOMElement(element)) { return element; } return null; } var findDOMElement_default = findDOMElement; // node_modules/@uppy/utils/lib/getTextDirection.js function getTextDirection(element) { var _element; while (element && !element.dir) { element = element.parentNode; } return (_element = element) == null ? void 0 : _element.dir; } var getTextDirection_default = getTextDirection; // node_modules/@uppy/core/lib/BasePlugin.js var BasePlugin = class { constructor(uppy, opts) { this.uppy = uppy; this.opts = opts != null ? opts : {}; } getPluginState() { const { plugins } = this.uppy.getState(); return (plugins == null ? void 0 : plugins[this.id]) || {}; } setPluginState(update) { const { plugins } = this.uppy.getState(); this.uppy.setState({ plugins: { ...plugins, [this.id]: { ...plugins[this.id], ...update } } }); } setOptions(newOpts) { this.opts = { ...this.opts, ...newOpts }; this.setPluginState(void 0); this.i18nInit(); } i18nInit() { const translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale]); this.i18n = translator.translate.bind(translator); this.i18nArray = translator.translateArray.bind(translator); this.setPluginState(void 0); } /** * Extendable methods * ================== * These methods are here to serve as an overview of the extendable methods as well as * making them not conditional in use, such as `if (this.afterUpdate)`. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars addTarget(plugin) { throw new Error("Extend the addTarget method to add your plugin to another plugin's target"); } install() { } uninstall() { } // eslint-disable-next-line @typescript-eslint/no-unused-vars update(state) { } // Called after every state update, after everything's mounted. Debounced. afterUpdate() { } }; // node_modules/@uppy/core/lib/UIPlugin.js function _classPrivateFieldLooseBase4(e4, t4) { if (!{}.hasOwnProperty.call(e4, t4)) throw new TypeError("attempted to use private field on non-instance"); return e4; } var id4 = 0; function _classPrivateFieldLooseKey4(e4) { return "__private_" + id4++ + "_" + e4; } function debounce3(fn2) { let calling = null; let latestArgs; return function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } latestArgs = args; if (!calling) { calling = Promise.resolve().then(() => { calling = null; return fn2(...latestArgs); }); } return calling; }; } var _updateUI = /* @__PURE__ */ _classPrivateFieldLooseKey4("updateUI"); var UIPlugin = class _UIPlugin extends BasePlugin { constructor() { super(...arguments); Object.defineProperty(this, _updateUI, { writable: true, value: void 0 }); } getTargetPlugin(target) { let targetPlugin; if (typeof (target == null ? void 0 : target.addTarget) === "function") { targetPlugin = target; if (!(targetPlugin instanceof _UIPlugin)) { console.warn(new Error("The provided plugin is not an instance of UIPlugin. This is an indication of a bug with the way Uppy is bundled.", { cause: { targetPlugin, UIPlugin: _UIPlugin } })); } } else if (typeof target === "function") { const Target = target; this.uppy.iteratePlugins((p4) => { if (p4 instanceof Target) { targetPlugin = p4; } }); } return targetPlugin; } /** * Check if supplied `target` is a DOM element or an `object`. * If it’s an object — target is a plugin, and we search `plugins` * for a plugin with same name and return its target. */ mount(target, plugin) { const callerPluginName = plugin.id; const targetElement = findDOMElement_default(target); if (targetElement) { this.isTargetDOMEl = true; const uppyRootElement = document.createElement("div"); uppyRootElement.classList.add("uppy-Root"); _classPrivateFieldLooseBase4(this, _updateUI)[_updateUI] = debounce3((state) => { if (!this.uppy.getPlugin(this.id)) return; B(this.render(state, uppyRootElement), uppyRootElement); this.afterUpdate(); }); this.uppy.log(`Installing ${callerPluginName} to a DOM element '${target}'`); if (this.opts.replaceTargetContent) { targetElement.innerHTML = ""; } B(this.render(this.uppy.getState(), uppyRootElement), uppyRootElement); this.el = uppyRootElement; targetElement.appendChild(uppyRootElement); uppyRootElement.dir = this.opts.direction || getTextDirection_default(uppyRootElement) || "ltr"; this.onMount(); return this.el; } const targetPlugin = this.getTargetPlugin(target); if (targetPlugin) { this.uppy.log(`Installing ${callerPluginName} to ${targetPlugin.id}`); this.parent = targetPlugin; this.el = targetPlugin.addTarget(plugin); this.onMount(); return this.el; } this.uppy.log(`Not installing ${callerPluginName}`); let message = `Invalid target option given to ${callerPluginName}.`; if (typeof target === "function") { message += " The given target is not a Plugin class. Please check that you're not specifying a React Component instead of a plugin. If you are using @uppy/* packages directly, make sure you have only 1 version of @uppy/core installed: run `npm ls @uppy/core` on the command line and verify that all the versions match and are deduped correctly."; } else { message += "If you meant to target an HTML element, please make sure that the element exists. Check that the