").css({
position: "absolute",
top: "0",
left: "0",
pointerEvents: "none",
visibility: "hidden",
width: "200px",
height: "150px",
overflow: "hidden"
}).append($inner).appendTo(document.body);
const widthContained = $inner[0].offsetWidth;
$outer.css("overflow", "scroll");
let widthScroll = $inner[0].offsetWidth;
if (widthContained === widthScroll) widthScroll = $outer[0].clientWidth;
$outer.remove();
scrollBarSizeCached = widthContained - widthScroll;
}
return scrollBarSizeCached;
};
var hasScrollbar = (target) => {
return target.scrollHeight > target.clientHeight;
};
var lockMap = new WeakMap();
var className = "mdui-lock-screen";
var lockScreen = (source, target) => {
const document = getDocument();
target ??= document.documentElement;
if (!lockMap.has(target)) lockMap.set(target, new Set());
lockMap.get(target).add(source);
const $target = $$1(target);
if (hasScrollbar(target)) $target.css("width", `calc(100% - ${getScrollBarSize()}px)`);
$target.addClass(className);
};
var unlockScreen = (source, target) => {
const document = getDocument();
target ??= document.documentElement;
const lock = lockMap.get(target);
if (!lock) return;
lock.delete(source);
if (lock.size === 0) {
lockMap.delete(target);
$$1(target).removeClass(className).width("");
}
};
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
var LOCALE_STATUS_EVENT = "lit-localize-status";
var isStrTagged = (val) => typeof val !== "string" && "strTag" in val;
var joinStringsAndValues = (strings, values, valueOrder) => {
let concat = strings[0];
for (let i = 1; i < strings.length; i++) {
concat += values[valueOrder ? valueOrder[i - 1] : i - 1];
concat += strings[i];
}
return concat;
};
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
var defaultMsg = ((template) => isStrTagged(template) ? joinStringsAndValues(template.strings, template.values) : template);
var msg = defaultMsg;
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
var Deferred = class {
constructor() {
this.settled = false;
this.promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
resolve(value) {
this.settled = true;
this._resolve(value);
}
reject(error) {
this.settled = true;
this._reject(error);
}
};
/**
* @license
* Copyright 2014 Travis Webb
* SPDX-License-Identifier: MIT
*/
var hl = [];
for (let i = 0; i < 256; i++) hl[i] = (i >> 4 & 15).toString(16) + (i & 15).toString(16);
new Deferred().resolve();
var listeningLitLocalizeStatus = false;
var localeReadyCallbacksMap = new Map();
var onLocaleReady = (target, callback) => {
if (!listeningLitLocalizeStatus) {
listeningLitLocalizeStatus = true;
getWindow$1().addEventListener(LOCALE_STATUS_EVENT, (event) => {
if (event.detail.status === "ready") localeReadyCallbacksMap.forEach((callbacks) => {
callbacks.forEach((cb) => cb());
});
});
}
const callbacks = localeReadyCallbacksMap.get(target) || [];
callbacks.push(callback);
localeReadyCallbacksMap.set(target, callbacks);
};
var offLocaleReady = (target) => {
localeReadyCallbacksMap.delete(target);
};
var style$11 = i$7`:host{--shape-corner:var(--mdui-shape-corner-extra-large);--z-index:2300;position:fixed;z-index:var(--z-index);display:none;align-items:center;justify-content:center;inset:0;padding:3rem}::slotted(mdui-top-app-bar[slot=header]){position:absolute;border-top-left-radius:var(--mdui-shape-corner-extra-large);border-top-right-radius:var(--mdui-shape-corner-extra-large);background-color:rgb(var(--mdui-color-surface-container-high))}:host([fullscreen]:not([fullscreen=false i])){--shape-corner:var(--mdui-shape-corner-none);padding:0}:host([fullscreen]:not([fullscreen=false i])) ::slotted(mdui-top-app-bar[slot=header]){border-top-left-radius:var(--mdui-shape-corner-none);border-top-right-radius:var(--mdui-shape-corner-none)}.overlay{position:fixed;inset:0;background-color:rgba(var(--mdui-color-scrim),.4)}.panel{--mdui-color-background:var(--mdui-color-surface-container-high);position:relative;display:flex;flex-direction:column;max-height:100%;border-radius:var(--shape-corner);outline:0;transform-origin:top;min-width:17.5rem;max-width:35rem;padding:1.5rem;background-color:rgb(var(--mdui-color-surface-container-high));box-shadow:var(--mdui-elevation-level3)}:host([fullscreen]:not([fullscreen=false i])) .panel{width:100%;max-width:100%;height:100%;max-height:100%;box-shadow:var(--mdui-elevation-level0)}.header{display:flex;flex-direction:column}.has-icon .header{align-items:center}.icon{display:flex;color:rgb(var(--mdui-color-secondary));font-size:1.5rem}.icon mdui-icon,::slotted([slot=icon]){font-size:inherit}.headline{display:flex;color:rgb(var(--mdui-color-on-surface));font-size:var(--mdui-typescale-headline-small-size);font-weight:var(--mdui-typescale-headline-small-weight);letter-spacing:var(--mdui-typescale-headline-small-tracking);line-height:var(--mdui-typescale-headline-small-line-height)}.icon+.headline{padding-top:1rem}.body{overflow:auto}.header+.body{margin-top:1rem}.description{display:flex;color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-body-medium-size);font-weight:var(--mdui-typescale-body-medium-weight);letter-spacing:var(--mdui-typescale-body-medium-tracking);line-height:var(--mdui-typescale-body-medium-line-height)}:host([fullscreen]:not([fullscreen=false i])) .description{color:rgb(var(--mdui-color-on-surface))}.has-description.has-default .description{margin-bottom:1rem}.action{display:flex;justify-content:flex-end;padding-top:1.5rem}.action::slotted(:not(:first-child)){margin-left:.5rem}:host([stacked-actions]:not([stacked-actions=false i])) .action{flex-direction:column;align-items:end}:host([stacked-actions]:not([stacked-actions=false i])) .action::slotted(:not(:first-child)){margin-left:0;margin-top:.5rem}`;
var Dialog = class Dialog extends MduiElement {
constructor() {
super(...arguments);
this.open = false;
this.fullscreen = false;
this.closeOnEsc = false;
this.closeOnOverlayClick = false;
this.stackedActions = false;
this.overlayRef = e$1();
this.panelRef = e$1();
this.bodyRef = e$1();
this.hasSlotController = new HasSlotController(this, "header", "icon", "headline", "description", "action", "[default]");
this.definedController = new DefinedController(this, { relatedElements: ["mdui-top-app-bar"] });
}
async onOpenChange() {
const hasUpdated = this.hasUpdated;
if (!this.open && !hasUpdated) return;
await this.definedController.whenDefined();
if (!hasUpdated) await this.updateComplete;
const children = Array.from(this.panelRef.value.querySelectorAll(".header, .body, .actions"));
const easingLinear = getEasing(this, "linear");
const easingEmphasizedDecelerate = getEasing(this, "emphasized-decelerate");
const easingEmphasizedAccelerate = getEasing(this, "emphasized-accelerate");
const stopAnimation = () => Promise.all([
stopAnimations(this.overlayRef.value),
stopAnimations(this.panelRef.value),
...children.map((child) => stopAnimations(child))
]);
if (this.open) {
if (hasUpdated) {
if (!this.emit("open", { cancelable: true })) return;
}
this.style.display = "flex";
const topAppBarElements = this.topAppBarElements ?? [];
if (topAppBarElements.length) {
const topAppBarElement = topAppBarElements[0];
if (!topAppBarElement.scrollTarget) topAppBarElement.scrollTarget = this.bodyRef.value;
this.bodyRef.value.style.marginTop = "0";
}
this.originalTrigger = document.activeElement;
this.modalHelper.activate();
lockScreen(this);
await stopAnimation();
requestAnimationFrame(() => {
const autoFocusTarget = this.querySelector("[autofocus]");
if (autoFocusTarget) autoFocusTarget.focus({ preventScroll: true });
else this.panelRef.value.focus({ preventScroll: true });
});
const duration = getDuration(this, "medium4");
await Promise.all([
animateTo(this.overlayRef.value, [
{ opacity: 0 },
{
opacity: 1,
offset: .3
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
}),
animateTo(this.panelRef.value, [{ transform: "translateY(-1.875rem) scaleY(0)" }, { transform: "translateY(0) scaleY(1)" }], {
duration: hasUpdated ? duration : 0,
easing: easingEmphasizedDecelerate
}),
animateTo(this.panelRef.value, [
{ opacity: 0 },
{
opacity: 1,
offset: .1
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
}),
...children.map((child) => animateTo(child, [
{ opacity: 0 },
{
opacity: 0,
offset: .2
},
{
opacity: 1,
offset: .8
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
}))
]);
if (hasUpdated) this.emit("opened");
} else {
if (!this.emit("close", { cancelable: true })) return;
this.modalHelper.deactivate();
await stopAnimation();
const duration = getDuration(this, "short4");
await Promise.all([
animateTo(this.overlayRef.value, [{ opacity: 1 }, { opacity: 0 }], {
duration,
easing: easingLinear
}),
animateTo(this.panelRef.value, [{ transform: "translateY(0) scaleY(1)" }, { transform: "translateY(-1.875rem) scaleY(0.6)" }], {
duration,
easing: easingEmphasizedAccelerate
}),
animateTo(this.panelRef.value, [
{ opacity: 1 },
{
opacity: 1,
offset: .75
},
{ opacity: 0 }
], {
duration,
easing: easingLinear
}),
...children.map((child) => animateTo(child, [
{ opacity: 1 },
{
opacity: 0,
offset: .75
},
{ opacity: 0 }
], {
duration,
easing: easingLinear
}))
]);
this.style.display = "none";
unlockScreen(this);
const trigger = this.originalTrigger;
if (typeof trigger?.focus === "function") setTimeout(() => trigger.focus());
this.emit("closed");
}
}
disconnectedCallback() {
super.disconnectedCallback();
unlockScreen(this);
offLocaleReady(this);
}
firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties);
this.modalHelper = new Modal(this);
this.addEventListener("keydown", (event) => {
if (this.open && this.closeOnEsc && event.key === "Escape") {
event.stopPropagation();
this.open = false;
}
});
}
render() {
const hasActionSlot = this.hasSlotController.test("action");
const hasDefaultSlot = this.hasSlotController.test("[default]");
const hasIcon = !!this.icon || this.hasSlotController.test("icon");
const hasHeadline = !!this.headline || this.hasSlotController.test("headline");
const hasDescription = !!this.description || this.hasSlotController.test("description");
const hasHeader = hasIcon || hasHeadline || this.hasSlotController.test("header");
const hasBody = hasDescription || hasDefaultSlot;
return b`
${n(hasHeader, () => b``)} ${n(hasBody, () => b`
${n(hasDescription, () => this.renderDescription())}
`)} ${n(hasActionSlot, () => b`
`)}
`;
}
onOverlayClick() {
this.emit("overlay-click");
if (!this.closeOnOverlayClick) return;
this.open = false;
}
renderIcon() {
return b`
${this.icon ? b`` : nothingTemplate}`;
}
renderHeadline() {
return b`
${this.headline}`;
}
renderDescription() {
return b`
${this.description}`;
}
};
Dialog.styles = [componentStyle, style$11];
__decorate([n$6({ reflect: true })], Dialog.prototype, "icon", void 0);
__decorate([n$6({ reflect: true })], Dialog.prototype, "headline", void 0);
__decorate([n$6({ reflect: true })], Dialog.prototype, "description", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Dialog.prototype, "open", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Dialog.prototype, "fullscreen", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "close-on-esc"
})], Dialog.prototype, "closeOnEsc", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "close-on-overlay-click"
})], Dialog.prototype, "closeOnOverlayClick", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "stacked-actions"
})], Dialog.prototype, "stackedActions", void 0);
__decorate([o$7({
slot: "header",
selector: "mdui-top-app-bar",
flatten: true
})], Dialog.prototype, "topAppBarElements", void 0);
__decorate([watch("open")], Dialog.prototype, "onOpenChange", null);
Dialog = __decorate([t$3("mdui-dialog")], Dialog);
var style$10 = i$7`:host{display:block;height:.0625rem;background-color:rgb(var(--mdui-color-surface-variant))}:host([inset]:not([inset=false i])){margin-left:1rem}:host([middle]:not([middle=false i])){margin-left:1rem;margin-right:1rem}:host([vertical]:not([vertical=false i])){height:100%;width:.0625rem}`;
var Divider = class Divider extends MduiElement {
constructor() {
super(...arguments);
this.vertical = false;
this.inset = false;
this.middle = false;
}
render() {
return b``;
}
};
Divider.styles = [componentStyle, style$10];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Divider.prototype, "vertical", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Divider.prototype, "inset", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Divider.prototype, "middle", void 0);
Divider = __decorate([t$3("mdui-divider")], Divider);
function hasWindow() {
return typeof window !== "undefined";
}
function getNodeName(node) {
if (isNode(node)) return (node.nodeName || "").toLowerCase();
return "#document";
}
function getWindow(node) {
var _node$ownerDocument;
return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
var _ref;
return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
if (!hasWindow()) return false;
return value instanceof Node || value instanceof getWindow(value).Node;
}
function isHTMLElement(value) {
if (!hasWindow()) return false;
return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
if (!hasWindow() || typeof ShadowRoot === "undefined") return false;
return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
var invalidOverflowDisplayValues = new Set(["inline", "contents"]);
function isOverflowElement(element) {
const { overflow, overflowX, overflowY, display } = getComputedStyle(element);
return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);
}
var lastTraversableNodeNames = new Set([
"html",
"body",
"#document"
]);
function isLastTraversableNode(node) {
return lastTraversableNodeNames.has(getNodeName(node));
}
function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}
function getParentNode(node) {
if (getNodeName(node) === "html") return node;
const result = node.assignedSlot || node.parentNode || isShadowRoot(node) && node.host || getDocumentElement(node);
return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
const parentNode = getParentNode(node);
if (isLastTraversableNode(parentNode)) return node.ownerDocument ? node.ownerDocument.body : node.body;
if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) return parentNode;
return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
var _node$ownerDocument2;
if (list === void 0) list = [];
if (traverseIframes === void 0) traverseIframes = true;
const scrollableAncestor = getNearestOverflowAncestor(node);
const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
const win = getWindow(scrollableAncestor);
if (isBody) {
const frameElement = getFrameElement(win);
return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
}
return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
function getFrameElement(win) {
return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}
var style$9 = i$7`:host{--z-index:2100;display:contents}.panel{display:block;position:fixed;z-index:var(--z-index)}`;
var Dropdown = class Dropdown extends MduiElement {
constructor() {
super();
this.open = false;
this.disabled = false;
this.trigger = "click";
this.placement = "auto";
this.stayOpenOnClick = false;
this.openDelay = 150;
this.closeDelay = 150;
this.openOnPointer = false;
this.panelRef = e$1();
this.definedController = new DefinedController(this, { relatedElements: [""] });
this.onDocumentClick = this.onDocumentClick.bind(this);
this.onDocumentKeydown = this.onDocumentKeydown.bind(this);
this.onWindowScroll = this.onWindowScroll.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onFocus = this.onFocus.bind(this);
this.onClick = this.onClick.bind(this);
this.onContextMenu = this.onContextMenu.bind(this);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onPanelClick = this.onPanelClick.bind(this);
}
get triggerElement() {
return this.triggerElements[0];
}
async onPositionChange() {
if (this.open) {
await this.definedController.whenDefined();
this.updatePositioner();
}
}
async onOpenChange() {
const hasUpdated = this.hasUpdated;
if (!this.open && !hasUpdated) return;
await this.definedController.whenDefined();
if (!hasUpdated) await this.updateComplete;
const easingLinear = getEasing(this, "linear");
const easingEmphasizedDecelerate = getEasing(this, "emphasized-decelerate");
const easingEmphasizedAccelerate = getEasing(this, "emphasized-accelerate");
if (this.open) {
if (hasUpdated) {
if (!this.emit("open", { cancelable: true })) return;
}
const focusablePanel = this.panelElements.find((panel) => isFunction(panel.focus));
setTimeout(() => {
focusablePanel?.focus();
});
const duration = getDuration(this, "medium4");
await stopAnimations(this.panelRef.value);
this.panelRef.value.hidden = false;
this.updatePositioner();
await Promise.all([animateTo(this.panelRef.value, [{ transform: `${this.getCssScaleName()}(0.45)` }, { transform: `${this.getCssScaleName()}(1)` }], {
duration: hasUpdated ? duration : 0,
easing: easingEmphasizedDecelerate
}), animateTo(this.panelRef.value, [
{ opacity: 0 },
{
opacity: 1,
offset: .125
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
})]);
if (hasUpdated) this.emit("opened");
} else {
if (!this.emit("close", { cancelable: true })) return;
if (!this.hasTrigger("focus") && isFunction(this.triggerElement?.focus) && (this.contains(document.activeElement) || this.contains(document.activeElement?.assignedSlot ?? null))) this.triggerElement.focus();
const duration = getDuration(this, "short4");
await stopAnimations(this.panelRef.value);
await Promise.all([animateTo(this.panelRef.value, [{ transform: `${this.getCssScaleName()}(1)` }, { transform: `${this.getCssScaleName()}(0.45)` }], {
duration,
easing: easingEmphasizedAccelerate
}), animateTo(this.panelRef.value, [
{ opacity: 1 },
{
opacity: 1,
offset: .875
},
{ opacity: 0 }
], {
duration,
easing: easingLinear
})]);
if (this.panelRef.value) this.panelRef.value.hidden = true;
this.emit("closed");
}
}
connectedCallback() {
super.connectedCallback();
this.definedController.whenDefined().then(() => {
document.addEventListener("pointerdown", this.onDocumentClick);
document.addEventListener("keydown", this.onDocumentKeydown);
this.overflowAncestors = getOverflowAncestors(this.triggerElement);
this.overflowAncestors.forEach((ancestor) => {
ancestor.addEventListener("scroll", this.onWindowScroll);
});
this.observeResize = observeResize(this.triggerElement, () => {
this.updatePositioner();
});
});
}
disconnectedCallback() {
if (!this.open && this.panelRef.value) this.panelRef.value.hidden = true;
super.disconnectedCallback();
document.removeEventListener("pointerdown", this.onDocumentClick);
document.removeEventListener("keydown", this.onDocumentKeydown);
this.overflowAncestors?.forEach((ancestor) => {
ancestor.removeEventListener("scroll", this.onWindowScroll);
});
this.observeResize?.unobserve();
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.addEventListener("mouseleave", this.onMouseLeave);
this.definedController.whenDefined().then(() => {
this.triggerElement.addEventListener("focus", this.onFocus);
this.triggerElement.addEventListener("click", this.onClick);
this.triggerElement.addEventListener("contextmenu", this.onContextMenu);
this.triggerElement.addEventListener("mouseenter", this.onMouseEnter);
});
}
render() {
return b`
`;
}
getCssScaleName() {
return this.animateDirection === "horizontal" ? "scaleX" : "scaleY";
}
onDocumentClick(e) {
if (this.disabled || !this.open) return;
const path = e.composedPath();
if (!path.includes(this)) this.open = false;
if (this.hasTrigger("contextmenu") && !this.hasTrigger("click") && path.includes(this.triggerElement)) this.open = false;
}
onDocumentKeydown(event) {
if (this.disabled || !this.open) return;
if (event.key === "Escape") {
this.open = false;
return;
}
if (event.key === "Tab") {
if (!this.hasTrigger("focus") && isFunction(this.triggerElement?.focus)) event.preventDefault();
this.open = false;
}
}
onWindowScroll() {
window.requestAnimationFrame(() => this.onPositionChange());
}
hasTrigger(trigger) {
return this.trigger.split(" ").includes(trigger);
}
onFocus() {
if (this.disabled || this.open || !this.hasTrigger("focus")) return;
this.open = true;
}
onClick(e) {
if (this.disabled || e.button || !this.hasTrigger("click")) return;
if (this.open && (this.hasTrigger("hover") || this.hasTrigger("focus"))) return;
this.pointerOffsetX = e.offsetX;
this.pointerOffsetY = e.offsetY;
this.open = !this.open;
}
onPanelClick(e) {
if (!this.disabled && !this.stayOpenOnClick && $$1(e.target).is("mdui-menu-item")) this.open = false;
}
onContextMenu(e) {
if (this.disabled || !this.hasTrigger("contextmenu")) return;
e.preventDefault();
this.pointerOffsetX = e.offsetX;
this.pointerOffsetY = e.offsetY;
this.open = true;
}
onMouseEnter() {
if (this.disabled || !this.hasTrigger("hover")) return;
window.clearTimeout(this.closeTimeout);
if (this.openDelay) this.openTimeout = window.setTimeout(() => {
this.open = true;
}, this.openDelay);
else this.open = true;
}
onMouseLeave() {
if (this.disabled || !this.hasTrigger("hover")) return;
window.clearTimeout(this.openTimeout);
this.closeTimeout = window.setTimeout(() => {
this.open = false;
}, this.closeDelay || 50);
}
updatePositioner() {
const $panel = $$1(this.panelRef.value);
const $window = $$1(window);
const panelElements = this.panelElements;
const panelRect = {
width: Math.max(...panelElements?.map((panel) => panel.offsetWidth) ?? []),
height: panelElements?.map((panel) => panel.offsetHeight).reduce((total, height) => total + height, 0)
};
const triggerClientRect = this.triggerElement.getBoundingClientRect();
const triggerRect = this.openOnPointer ? {
top: this.pointerOffsetY + triggerClientRect.top,
left: this.pointerOffsetX + triggerClientRect.left,
width: 0,
height: 0
} : triggerClientRect;
const screenMargin = 8;
let transformOriginX;
let transformOriginY;
let top;
let left;
let placement = this.placement;
if (placement === "auto") {
const windowWidth = $window.width();
const windowHeight = $window.height();
let position;
let alignment;
if (windowHeight - triggerRect.top - triggerRect.height > panelRect.height + screenMargin) position = "bottom";
else if (triggerRect.top > panelRect.height + screenMargin) position = "top";
else if (windowWidth - triggerRect.left - triggerRect.width > panelRect.width + screenMargin) position = "right";
else if (triggerRect.left > panelRect.width + screenMargin) position = "left";
else position = "bottom";
if (["top", "bottom"].includes(position)) if (windowWidth - triggerRect.left > panelRect.width + screenMargin) alignment = "start";
else if (triggerRect.left + triggerRect.width / 2 > panelRect.width / 2 + screenMargin && windowWidth - triggerRect.left - triggerRect.width / 2 > panelRect.width / 2 + screenMargin) alignment = void 0;
else if (triggerRect.left + triggerRect.width > panelRect.width + screenMargin) alignment = "end";
else alignment = "start";
else if (windowHeight - triggerRect.top > panelRect.height + screenMargin) alignment = "start";
else if (triggerRect.top + triggerRect.height / 2 > panelRect.height / 2 + screenMargin && windowHeight - triggerRect.top - triggerRect.height / 2 > panelRect.height / 2 + screenMargin) alignment = void 0;
else if (triggerRect.top + triggerRect.height > panelRect.height + screenMargin) alignment = "end";
else alignment = "start";
placement = alignment ? [position, alignment].join("-") : position;
}
const [position, alignment] = placement.split("-");
this.animateDirection = ["top", "bottom"].includes(position) ? "vertical" : "horizontal";
switch (position) {
case "top":
transformOriginY = "bottom";
top = triggerRect.top - panelRect.height;
break;
case "bottom":
transformOriginY = "top";
top = triggerRect.top + triggerRect.height;
break;
default:
transformOriginY = "center";
switch (alignment) {
case "start":
top = triggerRect.top;
break;
case "end":
top = triggerRect.top + triggerRect.height - panelRect.height;
break;
default:
top = triggerRect.top + triggerRect.height / 2 - panelRect.height / 2;
break;
}
break;
}
switch (position) {
case "left":
transformOriginX = "right";
left = triggerRect.left - panelRect.width;
break;
case "right":
transformOriginX = "left";
left = triggerRect.left + triggerRect.width;
break;
default:
transformOriginX = "center";
switch (alignment) {
case "start":
left = triggerRect.left;
break;
case "end":
left = triggerRect.left + triggerRect.width - panelRect.width;
break;
default:
left = triggerRect.left + triggerRect.width / 2 - panelRect.width / 2;
break;
}
break;
}
$panel.css({
top,
left,
transformOrigin: [transformOriginX, transformOriginY].join(" ")
});
}
};
Dropdown.styles = [componentStyle, style$9];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Dropdown.prototype, "open", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Dropdown.prototype, "disabled", void 0);
__decorate([n$6({ reflect: true })], Dropdown.prototype, "trigger", void 0);
__decorate([n$6({ reflect: true })], Dropdown.prototype, "placement", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "stay-open-on-click"
})], Dropdown.prototype, "stayOpenOnClick", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "open-delay"
})], Dropdown.prototype, "openDelay", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "close-delay"
})], Dropdown.prototype, "closeDelay", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "open-on-pointer"
})], Dropdown.prototype, "openOnPointer", void 0);
__decorate([o$7({
slot: "trigger",
flatten: true
})], Dropdown.prototype, "triggerElements", void 0);
__decorate([o$7({ flatten: true })], Dropdown.prototype, "panelElements", void 0);
__decorate([watch("placement", true), watch("openOnPointer", true)], Dropdown.prototype, "onPositionChange", null);
__decorate([watch("open")], Dropdown.prototype, "onOpenChange", null);
Dropdown = __decorate([t$3("mdui-dropdown")], Dropdown);
var delay = (duration = 0) => {
return new Promise((resolve) => setTimeout(resolve, duration));
};
var style$8 = i$7`:host{--shape-corner-small:var(--mdui-shape-corner-small);--shape-corner-normal:var(--mdui-shape-corner-large);--shape-corner-large:var(--mdui-shape-corner-extra-large);position:relative;display:inline-block;flex-shrink:0;overflow:hidden;text-align:center;border-radius:var(--shape-corner-normal);cursor:pointer;-webkit-tap-highlight-color:transparent;transition-property:box-shadow;transition-timing-function:var(--mdui-motion-easing-emphasized);transition-duration:var(--mdui-motion-duration-medium4);width:3.5rem;height:3.5rem;box-shadow:var(--mdui-elevation-level3);font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking);line-height:var(--mdui-typescale-label-large-line-height)}.button{padding:0 1rem}:host([size=small]) .button{padding:0 .5rem}:host([size=large]) .button{padding:0 1.875rem}:host([lowered]){box-shadow:var(--mdui-elevation-level1)}:host([focus-visible]){box-shadow:var(--mdui-elevation-level3)}:host([lowered][focus-visible]){box-shadow:var(--mdui-elevation-level1)}:host([pressed]){box-shadow:var(--mdui-elevation-level3)}:host([lowered][pressed]){box-shadow:var(--mdui-elevation-level1)}:host([hover]){box-shadow:var(--mdui-elevation-level4)}:host([lowered][hover]){box-shadow:var(--mdui-elevation-level2)}:host([variant=primary]){color:rgb(var(--mdui-color-on-primary-container));background-color:rgb(var(--mdui-color-primary-container));--mdui-comp-ripple-state-layer-color:var(
--mdui-color-on-primary-container
)}:host([variant=surface]){color:rgb(var(--mdui-color-primary));background-color:rgb(var(--mdui-color-surface-container-high));--mdui-comp-ripple-state-layer-color:var(--mdui-color-primary)}:host([variant=surface][lowered]){background-color:rgb(var(--mdui-color-surface-container-low))}:host([variant=secondary]){color:rgb(var(--mdui-color-on-secondary-container));background-color:rgb(var(--mdui-color-secondary-container));--mdui-comp-ripple-state-layer-color:var(
--mdui-color-on-secondary-container
)}:host([variant=tertiary]){color:rgb(var(--mdui-color-on-tertiary-container));background-color:rgb(var(--mdui-color-tertiary-container));--mdui-comp-ripple-state-layer-color:var(
--mdui-color-on-tertiary-container
)}:host([size=small]){border-radius:var(--shape-corner-small);width:2.5rem;height:2.5rem}:host([size=large]){border-radius:var(--shape-corner-large);width:6rem;height:6rem}:host([disabled]:not([disabled=false i])),:host([loading]:not([loading=false i])){cursor:default;pointer-events:none}:host([disabled]:not([disabled=false i])){color:rgba(var(--mdui-color-on-surface),38%);background-color:rgba(var(--mdui-color-on-surface),12%);box-shadow:var(--mdui-elevation-level0)}:host([extended]:not([extended=false i])){width:auto}.label{display:inline-flex;transition:opacity var(--mdui-motion-duration-short2) var(--mdui-motion-easing-linear) var(--mdui-motion-duration-short2);padding-left:.25rem;padding-right:.25rem}.has-icon .label{margin-left:.5rem}:host([size=small]) .has-icon .label{margin-left:.25rem}:host([size=large]) .has-icon .label{margin-left:1rem}:host(:not([extended])) .label,:host([extended=false i]) .label{opacity:0;transition-delay:0s;transition-duration:var(--mdui-motion-duration-short1)}:host([size=large]) .label{font-size:1.5em}.icon{display:inline-flex;font-size:1.71428571em}:host([size=large]) .icon{font-size:2.57142857em}.icon mdui-icon,::slotted([slot=icon]){font-size:inherit}mdui-circular-progress{display:inline-flex;width:1.5rem;height:1.5rem}:host([size=large]) mdui-circular-progress{width:2.25rem;height:2.25rem}:host([disabled]:not([disabled=false i])) mdui-circular-progress{stroke:rgba(var(--mdui-color-on-surface),38%)}`;
var Fab = class Fab extends ButtonBase {
constructor() {
super(...arguments);
this.variant = "primary";
this.size = "normal";
this.extended = false;
this.rippleRef = e$1();
this.hasSlotController = new HasSlotController(this, "icon");
this.definedController = new DefinedController(this, { relatedElements: [""] });
}
get rippleElement() {
return this.rippleRef.value;
}
async onExtendedChange() {
const hasUpdated = this.hasUpdated;
if (this.extended) this.style.width = `${this.scrollWidth}px`;
else this.style.width = "";
await this.definedController.whenDefined();
await this.updateComplete;
if (this.extended && !hasUpdated) this.style.width = `${this.scrollWidth}px`;
if (!hasUpdated) {
await delay();
this.style.transitionProperty = "box-shadow, width, bottom, transform";
}
}
render() {
const className = cc({
button: true,
"has-icon": this.icon || this.hasSlotController.test("icon")
});
return b`
${this.isButton() ? this.renderButton({
className,
part: "button",
content: this.renderInner()
}) : this.disabled || this.loading ? b`
${this.renderInner()}` : this.renderAnchor({
className,
part: "button",
content: this.renderInner()
})}`;
}
renderLabel() {
return b`
`;
}
renderIcon() {
if (this.loading) return this.renderLoading();
return b`
${this.icon ? b`` : nothingTemplate}`;
}
renderInner() {
return [this.renderIcon(), this.renderLabel()];
}
};
Fab.styles = [ButtonBase.styles, style$8];
__decorate([n$6({ reflect: true })], Fab.prototype, "variant", void 0);
__decorate([n$6({ reflect: true })], Fab.prototype, "size", void 0);
__decorate([n$6({ reflect: true })], Fab.prototype, "icon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Fab.prototype, "extended", void 0);
__decorate([watch("extended")], Fab.prototype, "onExtendedChange", null);
Fab = __decorate([t$3("mdui-fab")], Fab);
var layoutStyle = i$7`:host{position:relative;display:flex;flex:1 1 auto;overflow:hidden}:host([full-height]:not([full-height=false i])){height:100%}`;
var Layout = class Layout extends MduiElement {
constructor() {
super(...arguments);
this.fullHeight = false;
}
render() {
return b`
`;
}
};
Layout.styles = [componentStyle, layoutStyle];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "full-height"
})], Layout.prototype, "fullHeight", void 0);
Layout = __decorate([t$3("mdui-layout")], Layout);
var layoutItemStyle = i$7`:host{display:flex;z-index:1}`;
var LayoutItem = class LayoutItem extends LayoutItemBase {
constructor() {
super(...arguments);
this.placement = "top";
}
get layoutPlacement() {
return this.placement;
}
onPlacementChange() {
this.layoutManager?.updateLayout(this);
}
render() {
return b`
`;
}
};
LayoutItem.styles = [componentStyle, layoutItemStyle];
__decorate([n$6({ reflect: true })], LayoutItem.prototype, "placement", void 0);
__decorate([watch("placement", true)], LayoutItem.prototype, "onPlacementChange", null);
LayoutItem = __decorate([t$3("mdui-layout-item")], LayoutItem);
var layoutMainStyle = i$7`:host{flex:1 0 auto;max-width:100%;overflow:auto}`;
var LayoutMain = class LayoutMain extends MduiElement {
connectedCallback() {
super.connectedCallback();
const parentElement = this.parentElement;
if (isNodeName(parentElement, "mdui-layout")) {
this.layoutManager = getLayout(parentElement);
this.layoutManager.registerMain(this);
}
}
disconnectedCallback() {
super.disconnectedCallback();
if (this.layoutManager) this.layoutManager.unregisterMain();
}
render() {
return b`
`;
}
};
LayoutMain.styles = [componentStyle, layoutMainStyle];
LayoutMain = __decorate([t$3("mdui-layout-main")], LayoutMain);
var style$7 = i$7`:host{--shape-corner:var(--mdui-shape-corner-none);position:relative;display:inline-block;width:100%;overflow:hidden;border-radius:var(--shape-corner);background-color:rgb(var(--mdui-color-surface-container-highest));height:.25rem}.determinate,.indeterminate{background-color:rgb(var(--mdui-color-primary))}.determinate{height:100%;transition:width var(--mdui-motion-duration-long2) var(--mdui-motion-easing-standard)}.indeterminate::before{position:absolute;top:0;bottom:0;left:0;background-color:inherit;animation:mdui-comp-progress-indeterminate 2s var(--mdui-motion-easing-linear) infinite;content:' '}.indeterminate::after{position:absolute;top:0;bottom:0;left:0;background-color:inherit;animation:mdui-comp-progress-indeterminate-short 2s var(--mdui-motion-easing-linear) infinite;content:' '}@keyframes mdui-comp-progress-indeterminate{0%{left:0;width:0}50%{left:30%;width:70%}75%{left:100%;width:0}}@keyframes mdui-comp-progress-indeterminate-short{0%{left:0;width:0}50%{left:0;width:0}75%{left:0;width:25%}100%{left:100%;width:0}}`;
var LinearProgress = class LinearProgress extends MduiElement {
constructor() {
super(...arguments);
this.max = 1;
}
render() {
if (!isUndefined(this.value)) {
const value = this.value;
return b`
`;
}
return b`
`;
}
};
LinearProgress.styles = [componentStyle, style$7];
__decorate([n$6({
type: Number,
reflect: true
})], LinearProgress.prototype, "max", void 0);
__decorate([n$6({ type: Number })], LinearProgress.prototype, "value", void 0);
LinearProgress = __decorate([t$3("mdui-linear-progress")], LinearProgress);
var listItemStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-none);--shape-corner-rounded:var(--mdui-shape-corner-extra-large);position:relative;display:block;border-radius:var(--shape-corner);--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}:host([rounded]:not([rounded=false i])),:host([rounded]:not([rounded=false i])) mdui-ripple{border-radius:var(--shape-corner-rounded)}:host([active]:not([active=false i])){background-color:rgb(var(--mdui-color-secondary-container));--mdui-comp-ripple-state-layer-color:var(
--mdui-color-on-secondary-container
)}:host([disabled]:not([disabled=false i])){pointer-events:none}.container{cursor:pointer;-webkit-user-select:none;user-select:none;text-decoration:none;color:inherit;-webkit-tap-highlight-color:transparent}:host([disabled]:not([disabled=false i])) .container{cursor:default;opacity:.38}:host([nonclickable]:not([href],[nonclickable=false i])) .container{cursor:auto;-webkit-user-select:auto;user-select:auto}.preset{display:flex;align-items:center;padding:.5rem 1.5rem .5rem 1rem;min-height:3.5rem}:host([alignment=start]) .preset{align-items:flex-start}:host([alignment=end]) .preset{align-items:flex-end}.body{display:flex;flex:1 1 100%;flex-direction:column;justify-content:center;min-width:0}.headline{display:block;color:rgb(var(--mdui-color-on-surface));font-size:var(--mdui-typescale-body-large-size);font-weight:var(--mdui-typescale-body-large-weight);letter-spacing:var(--mdui-typescale-body-large-tracking);line-height:var(--mdui-typescale-body-large-line-height)}:host([active]:not([active=false i])) .headline{color:rgb(var(--mdui-color-on-secondary-container))}.description{display:none;color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-body-medium-size);font-weight:var(--mdui-typescale-body-medium-weight);letter-spacing:var(--mdui-typescale-body-medium-tracking);line-height:var(--mdui-typescale-body-medium-line-height)}:host([disabled]:not([disabled=false i])) .description,:host([focused]) .description,:host([hover]) .description,:host([pressed]) .description{color:rgb(var(--mdui-color-on-surface))}.has-description .description{display:block}:host([description-line='1']) .description,:host([headline-line='1']) .headline{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}:host([description-line='2']) .description,:host([description-line='3']) .description,:host([headline-line='2']) .headline,:host([headline-line='3']) .headline{display:-webkit-box;overflow:hidden;text-overflow:ellipsis;-webkit-box-orient:vertical}:host([description-line='2']) .description,:host([headline-line='2']) .headline{-webkit-line-clamp:2}:host([description-line='3']) .description,:host([headline-line='3']) .headline{-webkit-line-clamp:3}.end-icon,.icon{display:flex;flex:0 0 auto;font-size:var(--mdui-typescale-label-small-size);font-weight:var(--mdui-typescale-label-small-weight);letter-spacing:var(--mdui-typescale-label-small-tracking);line-height:var(--mdui-typescale-label-small-line-height);color:rgb(var(--mdui-color-on-surface-variant))}:host([disabled]:not([disabled=false i])) .end-icon,:host([disabled]:not([disabled=false i])) .icon,:host([focused]) .end-icon,:host([focused]) .icon,:host([hover]) .end-icon,:host([hover]) .icon,:host([pressed]) .end-icon,:host([pressed]) .icon{color:rgb(var(--mdui-color-on-surface))}:host([active]:not([active=false i])) .end-icon,:host([active]:not([active=false i])) .icon{color:rgb(var(--mdui-color-on-secondary-container))}.end-icon mdui-icon,.icon mdui-icon,.is-end-icon ::slotted([slot=end-icon]),.is-icon ::slotted([slot=icon]){font-size:1.5rem}.has-icon .icon{margin-right:1rem}.has-icon ::slotted(mdui-checkbox[slot=icon]),.has-icon ::slotted(mdui-radio[slot=icon]){margin-left:-.5rem}.has-end-icon .end-icon{margin-left:1rem}.has-end-icon ::slotted(mdui-checkbox[slot=end-icon]),.has-end-icon ::slotted(mdui-radio[slot=end-icon]){margin-right:-.5rem}`;
var ListItem = class ListItem extends AnchorMixin(RippleMixin(FocusableMixin(MduiElement))) {
constructor() {
super(...arguments);
this.disabled = false;
this.active = false;
this.nonclickable = false;
this.rounded = false;
this.alignment = "center";
this.rippleRef = e$1();
this.itemRef = e$1();
this.hasSlotController = new HasSlotController(this, "[default]", "description", "icon", "end-icon", "custom");
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.focusDisabled;
}
get focusElement() {
return this.href && !this.disabled ? this.itemRef.value : this;
}
get focusDisabled() {
return this.href ? this.disabled : this.disabled || this.nonclickable;
}
render() {
const preset = !this.hasSlotController.test("custom");
const hasIcon = this.icon || this.hasSlotController.test("icon");
const hasEndIcon = this.endIcon || this.hasSlotController.test("end-icon");
const hasDescription = this.description || this.hasSlotController.test("description");
const isIcon = (element) => isNodeName(element, "mdui-icon") || getNodeName$1(element).startsWith("mdui-icon-");
const className = cc({
container: true,
preset,
"has-icon": hasIcon,
"has-end-icon": hasEndIcon,
"has-description": hasDescription,
"is-icon": isIcon(this.iconElements[0]),
"is-end-icon": isIcon(this.endIconElements[0])
});
return b`
${this.href && !this.disabled ? this.renderAnchor({
className,
content: this.renderInner(),
part: "container",
refDirective: n$1(this.itemRef)
}) : b`
${this.renderInner()}
`}`;
}
renderInner() {
const hasDefaultSlot = this.hasSlotController.test("[default]");
return b`
${this.icon ? b`` : nothingTemplate}${hasDefaultSlot ? b`
` : b`
${this.headline}
`}
${this.description} ${this.endIcon ? b`` : nothingTemplate}`;
}
};
ListItem.styles = [componentStyle, listItemStyle];
__decorate([n$6({ reflect: true })], ListItem.prototype, "headline", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "headline-line"
})], ListItem.prototype, "headlineLine", void 0);
__decorate([n$6({ reflect: true })], ListItem.prototype, "description", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "description-line"
})], ListItem.prototype, "descriptionLine", void 0);
__decorate([n$6({ reflect: true })], ListItem.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-icon"
})], ListItem.prototype, "endIcon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], ListItem.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], ListItem.prototype, "active", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], ListItem.prototype, "nonclickable", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], ListItem.prototype, "rounded", void 0);
__decorate([n$6({ reflect: true })], ListItem.prototype, "alignment", void 0);
__decorate([o$7({
slot: "icon",
flatten: true
})], ListItem.prototype, "iconElements", void 0);
__decorate([o$7({
slot: "end-icon",
flatten: true
})], ListItem.prototype, "endIconElements", void 0);
ListItem = __decorate([t$3("mdui-list-item")], ListItem);
var listSubheaderStyle = i$7`:host{display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;cursor:default;color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-label-small-size);font-weight:var(--mdui-typescale-label-small-weight);letter-spacing:var(--mdui-typescale-label-small-tracking);line-height:var(--mdui-typescale-label-small-line-height);padding-left:1rem;padding-right:1.5rem;height:3.5rem;line-height:3.5rem}`;
var ListSubheader = class ListSubheader extends MduiElement {
render() {
return b`
`;
}
};
ListSubheader.styles = [componentStyle, listSubheaderStyle];
ListSubheader = __decorate([t$3("mdui-list-subheader")], ListSubheader);
var listStyle = i$7`:host{display:block;padding:.5rem 0}::slotted(mdui-divider[middle]){margin-left:1rem;margin-right:1.5rem}`;
var List = class List extends MduiElement {
render() {
return b`
`;
}
};
List.styles = [componentStyle, listStyle];
List = __decorate([t$3("mdui-list")], List);
var IconArrowRight = class IconArrowRight extends i$4 {
render() {
return svgTag("
");
}
};
IconArrowRight.styles = style$14;
IconArrowRight = __decorate([t$3("mdui-icon-arrow-right")], IconArrowRight);
var menuItemStyle = i$7`:host{position:relative;display:block}:host([selected]){background-color:rgba(var(--mdui-color-primary),12%)}:host([disabled]:not([disabled=false i])){pointer-events:none}.container{cursor:pointer;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}:host([disabled]:not([disabled=false i])) .container{cursor:default;opacity:.38}.preset{display:flex;align-items:center;text-decoration:none;height:3rem;padding:0 .75rem}.preset.dense{height:2rem}.label-container{flex:1 1 100%;min-width:0}.label{display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:rgb(var(--mdui-color-on-surface));font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking)}.end-icon,.end-text,.icon,.selected-icon{display:none;flex:0 0 auto;color:rgb(var(--mdui-color-on-surface-variant))}.has-end-icon .end-icon,.has-end-text .end-text,.has-icon .icon,.has-icon .selected-icon{display:flex}.end-icon,.icon,.selected-icon{font-size:1.5rem}.end-icon::slotted(mdui-avatar),.icon::slotted(mdui-avatar),.selected-icon::slotted(mdui-avatar){width:1.5rem;height:1.5rem}.dense .end-icon,.dense .icon,.dense .selected-icon{font-size:1.125rem}.dense .end-icon::slotted(mdui-avatar),.dense .icon::slotted(mdui-avatar),.dense .selected-icon::slotted(mdui-avatar){width:1.125rem;height:1.125rem}.end-icon .i,.icon .i,.selected-icon .i,::slotted([slot=end-icon]),::slotted([slot=icon]),::slotted([slot=selected-icon]){font-size:inherit}.end-text{font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking);line-height:var(--mdui-typescale-label-large-line-height)}.icon,.selected-icon{margin-right:.75rem}.end-icon,.end-text{margin-left:.75rem}.arrow-right{color:rgb(var(--mdui-color-on-surface))}.submenu{--shape-corner:var(--mdui-shape-corner-extra-small);display:block;position:absolute;z-index:1;border-radius:var(--shape-corner);background-color:rgb(var(--mdui-color-surface-container));box-shadow:var(--mdui-elevation-level2);min-width:7rem;max-width:17.5rem;padding-top:.5rem;padding-bottom:.5rem;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}.submenu::slotted(mdui-divider){margin-top:.5rem;margin-bottom:.5rem}`;
var MenuItem = class MenuItem extends AnchorMixin(RippleMixin(FocusableMixin(MduiElement))) {
constructor() {
super();
this.disabled = false;
this.submenuOpen = false;
this.selected = false;
this.dense = false;
this.focusable = false;
this.key = uniqueId();
this.rippleRef = e$1();
this.containerRef = e$1();
this.submenuRef = e$1();
this.hasSlotController = new HasSlotController(this, "[default]", "icon", "end-icon", "end-text", "submenu", "custom");
this.definedController = new DefinedController(this, { relatedElements: [""] });
this.onOuterClick = this.onOuterClick.bind(this);
this.onFocus = this.onFocus.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onClick = this.onClick.bind(this);
this.onKeydown = this.onKeydown.bind(this);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
}
get focusDisabled() {
return this.disabled || !this.focusable;
}
get focusElement() {
return this.href && !this.disabled ? this.containerRef.value : this;
}
get rippleDisabled() {
return this.disabled;
}
get rippleElement() {
return this.rippleRef.value;
}
get hasSubmenu() {
return this.hasSlotController.test("submenu");
}
async onOpenChange() {
const hasUpdated = this.hasUpdated;
if (!this.submenuOpen && !hasUpdated) return;
await this.definedController.whenDefined();
if (!hasUpdated) await this.updateComplete;
const easingLinear = getEasing(this, "linear");
const easingEmphasizedDecelerate = getEasing(this, "emphasized-decelerate");
const easingEmphasizedAccelerate = getEasing(this, "emphasized-accelerate");
if (this.submenuOpen) {
if (hasUpdated) {
if (!this.emit("submenu-open", { cancelable: true })) return;
}
const duration = getDuration(this, "medium4");
await stopAnimations(this.submenuRef.value);
this.submenuRef.value.hidden = false;
this.updateSubmenuPositioner();
await Promise.all([animateTo(this.submenuRef.value, [{ transform: "scaleY(0.45)" }, { transform: "scaleY(1)" }], {
duration: hasUpdated ? duration : 0,
easing: easingEmphasizedDecelerate
}), animateTo(this.submenuRef.value, [
{ opacity: 0 },
{
opacity: 1,
offset: .125
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
})]);
if (hasUpdated) this.emit("submenu-opened");
} else {
if (!this.emit("submenu-close", { cancelable: true })) return;
const duration = getDuration(this, "short4");
await stopAnimations(this.submenuRef.value);
await Promise.all([animateTo(this.submenuRef.value, [{ transform: "scaleY(1)" }, { transform: "scaleY(0.45)" }], {
duration,
easing: easingEmphasizedAccelerate
}), animateTo(this.submenuRef.value, [
{ opacity: 1 },
{
opacity: 1,
offset: .875
},
{ opacity: 0 }
], {
duration,
easing: easingLinear
})]);
if (this.submenuRef.value) this.submenuRef.value.hidden = true;
this.emit("submenu-closed");
}
}
connectedCallback() {
super.connectedCallback();
this.definedController.whenDefined().then(() => {
document.addEventListener("pointerdown", this.onOuterClick);
});
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("pointerdown", this.onOuterClick);
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.definedController.whenDefined().then(() => {
this.addEventListener("focus", this.onFocus);
this.addEventListener("blur", this.onBlur);
this.addEventListener("click", this.onClick);
this.addEventListener("keydown", this.onKeydown);
this.addEventListener("mouseenter", this.onMouseEnter);
this.addEventListener("mouseleave", this.onMouseLeave);
});
}
render() {
const hasSubmenu = this.hasSubmenu;
const hasCustomSlot = this.hasSlotController.test("custom");
const hasEndIconSlot = this.hasSlotController.test("end-icon");
const useDefaultEndIcon = !this.endIcon && hasSubmenu && !hasEndIconSlot;
const hasEndIcon = this.endIcon || hasSubmenu || hasEndIconSlot;
const hasIcon = !isUndefined(this.icon) || this.selects === "single" || this.selects === "multiple" || this.hasSlotController.test("icon");
const hasEndText = !!this.endText || this.hasSlotController.test("end-text");
const className = cc({
container: true,
dense: this.dense,
preset: !hasCustomSlot,
"has-icon": hasIcon,
"has-end-text": hasEndText,
"has-end-icon": hasEndIcon
});
return b`
${this.href && !this.disabled ? this.renderAnchor({
part: "container",
className,
content: this.renderInner(useDefaultEndIcon, hasIcon),
refDirective: n$1(this.containerRef),
tabIndex: this.focusable ? 0 : -1
}) : b`
${this.renderInner(useDefaultEndIcon, hasIcon)}
`} ${n(hasSubmenu, () => b``)}`;
}
onOuterClick(event) {
if (!this.disabled && this.submenuOpen && this !== event.target && !$$1.contains(this, event.target)) this.submenuOpen = false;
}
hasTrigger(trigger) {
return this.submenuTrigger ? this.submenuTrigger.split(" ").includes(trigger) : false;
}
onFocus() {
if (this.disabled || this.submenuOpen || !this.hasTrigger("focus") || !this.hasSubmenu) return;
this.submenuOpen = true;
}
onBlur() {
if (this.disabled || !this.submenuOpen || !this.hasTrigger("focus") || !this.hasSubmenu) return;
this.submenuOpen = false;
}
onClick(event) {
if (this.disabled || event.button) return;
if (!this.hasTrigger("click") || event.target !== this || !this.hasSubmenu) return;
if (this.submenuOpen && (this.hasTrigger("hover") || this.hasTrigger("focus"))) return;
this.submenuOpen = !this.submenuOpen;
}
onKeydown(event) {
if (this.disabled || !this.hasSubmenu) return;
if (!this.submenuOpen && event.key === "Enter") {
event.stopPropagation();
this.submenuOpen = true;
}
if (this.submenuOpen && event.key === "Escape") {
event.stopPropagation();
this.submenuOpen = false;
}
}
onMouseEnter() {
if (this.disabled || !this.hasTrigger("hover") || !this.hasSubmenu) return;
window.clearTimeout(this.submenuCloseTimeout);
if (this.submenuOpenDelay) this.submenuOpenTimeout = window.setTimeout(() => {
this.submenuOpen = true;
}, this.submenuOpenDelay);
else this.submenuOpen = true;
}
onMouseLeave() {
if (this.disabled || !this.hasTrigger("hover") || !this.hasSubmenu) return;
window.clearTimeout(this.submenuOpenTimeout);
this.submenuCloseTimeout = window.setTimeout(() => {
this.submenuOpen = false;
}, this.submenuCloseDelay || 50);
}
updateSubmenuPositioner() {
const $window = $$1(window);
const $submenu = $$1(this.submenuRef.value);
const itemRect = this.getBoundingClientRect();
const submenuWidth = $submenu.innerWidth();
const submenuHeight = $submenu.innerHeight();
const screenMargin = 8;
let placementX = "bottom";
let placementY = "right";
if ($window.height() - itemRect.top > submenuHeight + screenMargin) placementX = "bottom";
else if (itemRect.top + itemRect.height > submenuHeight + screenMargin) placementX = "top";
if ($window.width() - itemRect.left - itemRect.width > submenuWidth + screenMargin) placementY = "right";
else if (itemRect.left > submenuWidth + screenMargin) placementY = "left";
$$1(this.submenuRef.value).css({
top: placementX === "bottom" ? 0 : itemRect.height - submenuHeight,
left: placementY === "right" ? itemRect.width : -submenuWidth,
transformOrigin: [placementY === "right" ? 0 : "100%", placementX === "bottom" ? 0 : "100%"].join(" ")
});
}
renderInner(useDefaultEndIcon, hasIcon) {
return b`
${this.selected ? b`${this.selectedIcon ? b`` : b``}` : b`${hasIcon ? b`` : nothingTemplate}`}
${this.endText}${useDefaultEndIcon ? b`` : b`${this.endIcon ? b`` : nothingTemplate}`}`;
}
};
MenuItem.styles = [componentStyle, menuItemStyle];
__decorate([n$6({ reflect: true })], MenuItem.prototype, "value", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], MenuItem.prototype, "disabled", void 0);
__decorate([n$6({ reflect: true })], MenuItem.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-icon"
})], MenuItem.prototype, "endIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-text"
})], MenuItem.prototype, "endText", void 0);
__decorate([n$6({
reflect: true,
attribute: "selected-icon"
})], MenuItem.prototype, "selectedIcon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "submenu-open"
})], MenuItem.prototype, "submenuOpen", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], MenuItem.prototype, "selected", void 0);
__decorate([r$2()], MenuItem.prototype, "dense", void 0);
__decorate([r$2()], MenuItem.prototype, "selects", void 0);
__decorate([r$2()], MenuItem.prototype, "submenuTrigger", void 0);
__decorate([r$2()], MenuItem.prototype, "submenuOpenDelay", void 0);
__decorate([r$2()], MenuItem.prototype, "submenuCloseDelay", void 0);
__decorate([r$2()], MenuItem.prototype, "focusable", void 0);
__decorate([watch("submenuOpen")], MenuItem.prototype, "onOpenChange", null);
MenuItem = __decorate([t$3("mdui-menu-item")], MenuItem);
var menuStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-extra-small);position:relative;display:block;border-radius:var(--shape-corner);background-color:rgb(var(--mdui-color-surface-container));box-shadow:var(--mdui-elevation-level2);min-width:7rem;max-width:17.5rem;padding-top:.5rem;padding-bottom:.5rem;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}::slotted(mdui-divider){margin-top:.5rem;margin-bottom:.5rem}`;
var Menu = class Menu extends MduiElement {
constructor() {
super(...arguments);
this.dense = false;
this.submenuTrigger = "click hover";
this.submenuOpenDelay = 200;
this.submenuCloseDelay = 200;
this.selectedKeys = [];
this.isInitial = true;
this.lastActiveItems = [];
this.definedController = new DefinedController(this, { relatedElements: ["mdui-menu-item"] });
}
get items() {
return $$1(this.childrenItems).find("mdui-menu-item").add(this.childrenItems).get();
}
get itemsEnabled() {
return this.items.filter((item) => !item.disabled);
}
get isSingle() {
return this.selects === "single";
}
get isMultiple() {
return this.selects === "multiple";
}
get isSelectable() {
return this.isSingle || this.isMultiple;
}
get isSubmenu() {
return !$$1(this).parent().length;
}
get lastActiveItem() {
const index = this.lastActiveItems.length ? this.lastActiveItems.length - 1 : 0;
return this.lastActiveItems[index];
}
set lastActiveItem(item) {
const index = this.lastActiveItems.length ? this.lastActiveItems.length - 1 : 0;
this.lastActiveItems[index] = item;
}
async onSlotChange() {
await this.definedController.whenDefined();
this.items.forEach((item) => {
item.dense = this.dense;
item.selects = this.selects;
item.submenuTrigger = this.submenuTrigger;
item.submenuOpenDelay = this.submenuOpenDelay;
item.submenuCloseDelay = this.submenuCloseDelay;
});
}
async onSelectsChange() {
if (!this.isSelectable) this.setSelectedKeys([]);
else if (this.isSingle) this.setSelectedKeys(this.selectedKeys.slice(0, 1));
await this.onSelectedKeysChange();
}
async onSelectedKeysChange() {
await this.definedController.whenDefined();
const values = this.itemsEnabled.filter((item) => this.selectedKeys.includes(item.key)).map((item) => item.value);
const value = this.isMultiple ? values : values[0] || void 0;
this.setValue(value);
if (!this.isInitial) this.emit("change");
}
async onValueChange() {
this.isInitial = !this.hasUpdated;
await this.definedController.whenDefined();
if (!this.isSelectable) {
this.updateSelected();
return;
}
const values = (this.isSingle ? [this.value] : isString(this.value) ? [this.value] : this.value).filter((i) => i);
if (!values.length) this.setSelectedKeys([]);
else if (this.isSingle) {
const firstItem = this.itemsEnabled.find((item) => item.value === values[0]);
this.setSelectedKeys(firstItem ? [firstItem.key] : []);
} else if (this.isMultiple) this.setSelectedKeys(this.itemsEnabled.filter((item) => values.includes(item.value)).map((item) => item.key));
this.updateSelected();
this.updateFocusable();
}
focus(options) {
if (this.lastActiveItem) this.focusOne(this.lastActiveItem, options);
}
blur() {
if (this.lastActiveItem) this.lastActiveItem.blur();
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.definedController.whenDefined().then(() => {
this.updateFocusable();
this.lastActiveItem = this.items.find((item) => item.focusable);
});
this.addEventListener("submenu-open", (e) => {
const $parentItem = $$1(e.target);
const submenuItemsEnabled = $parentItem.children("mdui-menu-item:not([disabled])").get();
const submenuLevel = $parentItem.parents("mdui-menu-item").length + 1;
if (submenuItemsEnabled.length) {
this.lastActiveItems[submenuLevel] = submenuItemsEnabled[0];
this.updateFocusable();
this.focusOne(this.lastActiveItems[submenuLevel]);
}
});
this.addEventListener("submenu-close", (e) => {
const submenuLevel = $$1(e.target).parents("mdui-menu-item").length + 1;
if (this.lastActiveItems.length - 1 === submenuLevel) {
this.lastActiveItems.pop();
this.updateFocusable();
if (this.lastActiveItems[submenuLevel - 1]) this.focusOne(this.lastActiveItems[submenuLevel - 1]);
}
});
}
render() {
return b`
`;
}
setSelectedKeys(selectedKeys) {
if (!arraysEqualIgnoreOrder(this.selectedKeys, selectedKeys)) this.selectedKeys = selectedKeys;
}
setValue(value) {
if (this.isSingle || isUndefined(this.value) || isUndefined(value)) this.value = value;
else if (!arraysEqualIgnoreOrder(this.value, value)) this.value = value;
}
getSiblingsItems(item, onlyEnabled = false) {
return $$1(item).parent().children(`mdui-menu-item${onlyEnabled ? ":not([disabled])" : ""}`).get();
}
updateFocusable() {
if (this.lastActiveItem) {
this.items.forEach((item) => {
item.focusable = item.key === this.lastActiveItem.key;
});
return;
}
if (!this.selectedKeys.length) {
this.itemsEnabled.forEach((item, index) => {
item.focusable = !index;
});
return;
}
if (this.isSingle) {
this.items.forEach((item) => {
item.focusable = this.selectedKeys.includes(item.key);
});
return;
}
if (this.isMultiple) {
const focusableItem = this.items.find((item) => item.focusable);
if (!focusableItem?.key || !this.selectedKeys.includes(focusableItem.key)) this.itemsEnabled.filter((item) => this.selectedKeys.includes(item.key)).forEach((item, index) => item.focusable = !index);
}
}
updateSelected() {
this.items.forEach((item) => {
item.selected = this.selectedKeys.includes(item.key);
});
}
selectOne(item) {
if (this.isMultiple) {
const selectedKeys = [...this.selectedKeys];
if (selectedKeys.includes(item.key)) selectedKeys.splice(selectedKeys.indexOf(item.key), 1);
else selectedKeys.push(item.key);
this.setSelectedKeys(selectedKeys);
}
if (this.isSingle) if (this.selectedKeys.includes(item.key)) this.setSelectedKeys([]);
else this.setSelectedKeys([item.key]);
this.isInitial = false;
this.updateSelected();
}
async focusableOne(item) {
this.items.forEach((_item) => _item.focusable = _item.key === item.key);
await delay();
}
focusOne(item, options) {
item.focus(options);
}
async onClick(event) {
if (!this.definedController.isDefined()) return;
if (this.isSubmenu) return;
if (event.button) return;
const item = event.target.closest("mdui-menu-item");
if (!item || item.disabled) return;
this.lastActiveItem = item;
if (this.isSelectable && item.value) this.selectOne(item);
await this.focusableOne(item);
this.focusOne(item);
}
async onKeyDown(event) {
if (!this.definedController.isDefined()) return;
if (this.isSubmenu) return;
const item = event.target;
if (event.key === "Enter") {
event.preventDefault();
item.click();
}
if (event.key === " ") {
event.preventDefault();
if (this.isSelectable && item.value) {
this.selectOne(item);
await this.focusableOne(item);
this.focusOne(item);
}
}
if ([
"ArrowUp",
"ArrowDown",
"Home",
"End"
].includes(event.key)) {
const items = this.getSiblingsItems(item, true);
const activeItem = items.find((item) => item.focusable);
let index = activeItem ? items.indexOf(activeItem) : 0;
if (items.length > 0) {
event.preventDefault();
if (event.key === "ArrowDown") index++;
else if (event.key === "ArrowUp") index--;
else if (event.key === "Home") index = 0;
else if (event.key === "End") index = items.length - 1;
if (index < 0) index = items.length - 1;
if (index > items.length - 1) index = 0;
this.lastActiveItem = items[index];
await this.focusableOne(items[index]);
this.focusOne(items[index]);
return;
}
}
}
};
Menu.styles = [componentStyle, menuStyle];
__decorate([n$6({ reflect: true })], Menu.prototype, "selects", void 0);
__decorate([n$6()], Menu.prototype, "value", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Menu.prototype, "dense", void 0);
__decorate([n$6({
reflect: true,
attribute: "submenu-trigger"
})], Menu.prototype, "submenuTrigger", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "submenu-open-delay"
})], Menu.prototype, "submenuOpenDelay", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "submenu-close-delay"
})], Menu.prototype, "submenuCloseDelay", void 0);
__decorate([r$2()], Menu.prototype, "selectedKeys", void 0);
__decorate([o$7({
flatten: true,
selector: "mdui-menu-item"
})], Menu.prototype, "childrenItems", void 0);
__decorate([
watch("dense"),
watch("selects"),
watch("submenuTrigger"),
watch("submenuOpenDelay"),
watch("submenuCloseDelay")
], Menu.prototype, "onSlotChange", null);
__decorate([watch("selects", true)], Menu.prototype, "onSelectsChange", null);
__decorate([watch("selectedKeys", true)], Menu.prototype, "onSelectedKeysChange", null);
__decorate([watch("value")], Menu.prototype, "onValueChange", null);
Menu = __decorate([t$3("mdui-menu")], Menu);
var navigationBarItemStyle = i$7`:host{--shape-corner-indicator:var(--mdui-shape-corner-full);position:relative;z-index:0;flex:1;overflow:hidden;min-width:3rem;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface-variant)}.container{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;text-decoration:none;cursor:pointer;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;padding-top:.75rem;padding-bottom:.75rem}.container:not(.initial){transition:padding var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}mdui-ripple{z-index:1;left:50%;transform:translateX(-50%);width:4rem;height:2rem;margin-top:.75rem;border-radius:var(--mdui-shape-corner-full)}mdui-ripple:not(.initial){transition:margin-top var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}.indicator{position:relative;display:flex;align-items:center;justify-content:center;background-color:transparent;border-radius:var(--shape-corner-indicator);height:2rem;width:2rem}:not(.initial) .indicator{transition:background-color var(--mdui-motion-duration-short1) var(--mdui-motion-easing-standard),width var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}::slotted([slot=badge]){position:absolute;transform:translate(50%,-50%)}::slotted([slot=badge][variant=small]){transform:translate(.5625rem,-.5625rem)}.active-icon,.icon{color:rgb(var(--mdui-color-on-surface-variant));font-size:1.5rem}.active-icon mdui-icon,.icon mdui-icon,::slotted([slot=active]),::slotted([slot=icon]){font-size:inherit}.icon{display:flex}.active-icon{display:none}.label{display:flex;align-items:center;height:1rem;color:rgb(var(--mdui-color-on-surface-variant));margin-top:.25rem;margin-bottom:.25rem;font-size:var(--mdui-typescale-label-medium-size);font-weight:var(--mdui-typescale-label-medium-weight);letter-spacing:var(--mdui-typescale-label-medium-tracking);line-height:var(--mdui-typescale-label-medium-line-height)}:not(.initial) .label{transition:opacity var(--mdui-motion-duration-short4) var(--mdui-motion-easing-linear)}:host(:not([active])) mdui-ripple.label-visibility-selected,mdui-ripple.label-visibility-unlabeled{margin-top:1.5rem}.container.label-visibility-unlabeled,:host(:not([active])) .container.label-visibility-selected{padding-top:1.5rem;padding-bottom:0}.container.label-visibility-unlabeled .label,:host(:not([active])) .container.label-visibility-selected .label{opacity:0}:host([active]){--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}:host([active]) .indicator{width:4rem;background-color:rgb(var(--mdui-color-secondary-container))}:host([active]) .active-icon,:host([active]) .icon{color:rgb(var(--mdui-color-on-secondary-container))}:host([active]) .has-active-icon .active-icon{display:flex}:host([active]) .has-active-icon .icon{display:none}:host([active]) .label{color:rgb(var(--mdui-color-on-surface))}`;
var NavigationBarItem = class NavigationBarItem extends AnchorMixin(RippleMixin(FocusableMixin(MduiElement))) {
constructor() {
super(...arguments);
this.isInitial = true;
this.active = false;
this.disabled = false;
this.key = uniqueId();
this.rippleRef = e$1();
this.hasSlotController = new HasSlotController(this, "active-icon");
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.disabled;
}
get focusElement() {
return this.href ? this.renderRoot?.querySelector("._a") : this;
}
get focusDisabled() {
return this.disabled;
}
render() {
const labelVisibilityClassName = cc({
"label-visibility-selected": this.labelVisibility === "selected",
"label-visibility-labeled": this.labelVisibility === "labeled",
"label-visibility-unlabeled": this.labelVisibility === "unlabeled",
initial: this.isInitial
});
const className = cc([{
container: true,
"has-active-icon": this.activeIcon || this.hasSlotController.test("active-icon")
}, labelVisibilityClassName]);
return b`
${this.href ? this.renderAnchor({
part: "container",
className,
content: this.renderInner()
}) : b`
${this.renderInner()}
`}`;
}
renderInner() {
return b`
${this.activeIcon ? b`` : nothingTemplate}${this.icon ? b`` : nothingTemplate}
`;
}
};
NavigationBarItem.styles = [componentStyle, navigationBarItemStyle];
__decorate([n$6({ reflect: true })], NavigationBarItem.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "active-icon"
})], NavigationBarItem.prototype, "activeIcon", void 0);
__decorate([n$6({ reflect: true })], NavigationBarItem.prototype, "value", void 0);
__decorate([r$2()], NavigationBarItem.prototype, "labelVisibility", void 0);
__decorate([r$2()], NavigationBarItem.prototype, "isInitial", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationBarItem.prototype, "active", void 0);
__decorate([r$2()], NavigationBarItem.prototype, "disabled", void 0);
NavigationBarItem = __decorate([t$3("mdui-navigation-bar-item")], NavigationBarItem);
var navigationBarStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-none);--z-index:2000;position:fixed;right:0;bottom:0;left:0;display:flex;flex:0 0 auto;overflow:hidden;border-radius:var(--shape-corner) var(--shape-corner) 0 0;z-index:var(--z-index);transition-property:transform;transition-duration:var(--mdui-motion-duration-long2);transition-timing-function:var(--mdui-motion-easing-emphasized);height:5rem;background-color:rgb(var(--mdui-color-surface));box-shadow:var(--mdui-elevation-level2)}:host([scroll-target]:not([scroll-target=''])){position:absolute}:host([hide]:not([hide=false i])){transform:translateY(5.625rem);transition-duration:var(--mdui-motion-duration-short4)}`;
var NavigationBar = class NavigationBar extends ScrollBehaviorMixin(LayoutItemBase) {
constructor() {
super(...arguments);
this.hide = false;
this.labelVisibility = "auto";
this.activeKey = 0;
this.isInitial = true;
this.definedController = new DefinedController(this, { relatedElements: ["mdui-navigation-bar-item"] });
}
get scrollPaddingPosition() {
return "bottom";
}
get layoutPlacement() {
return "bottom";
}
async onActiveKeyChange() {
await this.definedController.whenDefined();
this.value = this.items.find((item) => item.key === this.activeKey)?.value;
if (!this.isInitial) this.emit("change");
}
async onValueChange() {
this.isInitial = !this.hasUpdated;
await this.definedController.whenDefined();
this.activeKey = this.items.find((item) => item.value === this.value)?.key ?? 0;
this.updateItems();
}
async onLabelVisibilityChange() {
await this.definedController.whenDefined();
this.updateItems();
}
firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties);
this.addEventListener("transitionend", (event) => {
if (event.target === this) this.emit(this.hide ? "hidden" : "shown");
});
}
render() {
return b`
`;
}
runScrollThreshold(isScrollingUp) {
if (!isScrollingUp && !this.hide) {
if (this.emit("hide", { cancelable: true })) this.hide = true;
}
if (isScrollingUp && this.hide) {
if (this.emit("show", { cancelable: true })) this.hide = false;
}
}
onClick(event) {
if (event.button) return;
const item = event.target.closest("mdui-navigation-bar-item");
if (!item) return;
this.activeKey = item.key;
this.isInitial = false;
this.updateItems();
}
updateItems() {
const items = this.items;
const labelVisibility = this.labelVisibility === "auto" ? items.length <= 3 ? "labeled" : "selected" : this.labelVisibility;
items.forEach((item) => {
item.active = this.activeKey === item.key;
item.labelVisibility = labelVisibility;
item.isInitial = this.isInitial;
});
}
async onSlotChange() {
await this.definedController.whenDefined();
this.updateItems();
}
};
NavigationBar.styles = [componentStyle, navigationBarStyle];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationBar.prototype, "hide", void 0);
__decorate([n$6({
reflect: true,
attribute: "label-visibility"
})], NavigationBar.prototype, "labelVisibility", void 0);
__decorate([n$6({ reflect: true })], NavigationBar.prototype, "value", void 0);
__decorate([n$6({
reflect: true,
attribute: "scroll-behavior"
})], NavigationBar.prototype, "scrollBehavior", void 0);
__decorate([r$2()], NavigationBar.prototype, "activeKey", void 0);
__decorate([o$7({
selector: "mdui-navigation-bar-item",
flatten: true
})], NavigationBar.prototype, "items", void 0);
__decorate([watch("activeKey", true)], NavigationBar.prototype, "onActiveKeyChange", null);
__decorate([watch("value")], NavigationBar.prototype, "onValueChange", null);
__decorate([watch("labelVisibility", true)], NavigationBar.prototype, "onLabelVisibilityChange", null);
NavigationBar = __decorate([t$3("mdui-navigation-bar")], NavigationBar);
var breakpoint = (width) => {
const window = getWindow$1();
const document = getDocument();
const computedStyle = window.getComputedStyle(document.documentElement);
const containerWidth = isElement(width) ? $$1(width).innerWidth() : isNumber(width) ? width : $$1(window).innerWidth();
const getBreakpointValue = (breakpoint) => {
const width = computedStyle.getPropertyValue(`--mdui-breakpoint-${breakpoint}`).toLowerCase();
return parseFloat(width);
};
const getNextBreakpoint = (breakpoint) => {
switch (breakpoint) {
case "xs": return "sm";
case "sm": return "md";
case "md": return "lg";
case "lg": return "xl";
case "xl": return "xxl";
}
};
return {
up(breakpoint) {
return containerWidth >= getBreakpointValue(breakpoint);
},
down(breakpoint) {
return containerWidth < getBreakpointValue(breakpoint);
},
only(breakpoint) {
if (breakpoint === "xxl") return this.up(breakpoint);
else return this.up(breakpoint) && this.down(getNextBreakpoint(breakpoint));
},
not(breakpoint) {
return !this.only(breakpoint);
},
between(startBreakpoint, endBreakpoint) {
return this.up(startBreakpoint) && this.down(endBreakpoint);
}
};
};
var style$6 = i$7`:host{--shape-corner:var(--mdui-shape-corner-large);--z-index:2200;display:none;position:fixed;top:0;bottom:0;left:0;z-index:1;width:22.5rem}:host([placement=right]){left:initial;right:0}:host([mobile]),:host([modal]:not([modal=false i])){top:0!important;right:0;bottom:0!important;width:initial;z-index:var(--z-index)}:host([placement=right][mobile]),:host([placement=right][modal]:not([modal=false i])){left:0}:host([contained]:not([contained=false i])){position:absolute}.overlay{position:absolute;inset:0;z-index:inherit;background-color:rgba(var(--mdui-color-scrim),.4)}.panel{display:block;position:absolute;top:0;bottom:0;left:0;width:100%;overflow:auto;z-index:inherit;background-color:rgb(var(--mdui-color-surface));box-shadow:var(--mdui-elevation-level0)}:host([placement=right]) .panel{left:initial;right:0}:host([mobile]) .panel,:host([modal]:not([modal=false i])) .panel{border-radius:0 var(--shape-corner) var(--shape-corner) 0;max-width:80%;width:22.5rem;background-color:rgb(var(--mdui-color-surface-container-low));box-shadow:var(--mdui-elevation-level1)}:host([placement=right][mobile]) .panel,:host([placement=right][modal]:not([modal=false i])) .panel{border-radius:var(--shape-corner) 0 0 var(--shape-corner)}`;
var NavigationDrawer = class NavigationDrawer extends LayoutItemBase {
constructor() {
super(...arguments);
this.open = false;
this.modal = false;
this.closeOnEsc = false;
this.closeOnOverlayClick = false;
this.placement = "left";
this.contained = false;
this.mobile = false;
this.overlayRef = e$1();
this.panelRef = e$1();
this.definedController = new DefinedController(this, { needDomReady: true });
}
get layoutPlacement() {
return this.placement;
}
get lockTarget() {
return this.contained || this.isParentLayout ? this.parentElement : document.documentElement;
}
get isModal() {
return this.mobile || this.modal;
}
async onContainedChange() {
await this.definedController.whenDefined();
this.observeResize?.unobserve();
this.setObserveResize();
}
onPlacementChange() {
if (this.isParentLayout) this.layoutManager.updateLayout(this);
}
async onMobileChange() {
if (!this.open || this.isParentLayout || this.contained) return;
await this.definedController.whenDefined();
if (this.isModal) {
lockScreen(this, this.lockTarget);
await this.getLockTargetAnimate(false, 0);
} else {
unlockScreen(this, this.lockTarget);
await this.getLockTargetAnimate(true, 0);
}
}
async onOpenChange() {
let panel = this.panelRef.value;
let overlay = this.overlayRef.value;
const isRight = this.placement === "right";
const easingLinear = getEasing(this, "linear");
const easingEmphasized = getEasing(this, "emphasized");
const setLayoutTransition = (duration, easing) => {
$$1(this.layoutManager.getItemsAndMain()).css("transition", isNull(duration) ? null : `all ${duration}ms ${easing}`);
};
const stopOldAnimations = async () => {
const elements = [];
if (this.isModal) elements.push(overlay, panel);
else if (!this.isParentLayout) elements.push(this.lockTarget);
if (this.isParentLayout) {
const layoutItems = this.layoutManager.getItemsAndMain();
const layoutIndex = layoutItems.indexOf(this);
elements.push(...layoutItems.slice(layoutIndex));
}
if (!this.isModal && !elements.includes(this)) elements.push(this);
await Promise.all(elements.map((element) => stopAnimations(element)));
};
if (this.open) {
const hasUpdated = this.hasUpdated;
if (!hasUpdated) {
await this.updateComplete;
panel = this.panelRef.value;
overlay = this.overlayRef.value;
}
if (hasUpdated) {
if (!this.emit("open", { cancelable: true })) return;
}
await this.definedController.whenDefined();
this.style.display = "block";
this.originalTrigger = document.activeElement;
if (this.isModal) {
this.modalHelper.activate();
if (!this.contained) lockScreen(this, this.lockTarget);
}
await stopOldAnimations();
requestAnimationFrame(() => {
const autoFocusTarget = this.querySelector("[autofocus]");
if (autoFocusTarget) autoFocusTarget.focus({ preventScroll: true });
else panel.focus({ preventScroll: true });
});
const duration = getDuration(this, "long2");
const animations = [];
if (this.isModal) animations.push(animateTo(overlay, [
{ opacity: 0 },
{
opacity: 1,
offset: .3
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
}));
else if (!this.isParentLayout) animations.push(this.getLockTargetAnimate(true, hasUpdated ? duration : 0));
if (this.isParentLayout && hasUpdated) {
setLayoutTransition(duration, easingEmphasized);
this.layoutManager.updateLayout(this);
}
animations.push(animateTo(this.isModal ? panel : this, [{ transform: `translateX(${isRight ? "" : "-"}100%)` }, { transform: "translateX(0)" }], {
duration: hasUpdated ? duration : 0,
easing: easingEmphasized
}));
await Promise.all(animations);
if (!this.open) return;
if (this.isParentLayout && hasUpdated) setLayoutTransition(null);
if (hasUpdated) this.emit("opened");
} else if (this.hasUpdated) {
if (!this.emit("close", { cancelable: true })) return;
await this.definedController.whenDefined();
if (this.isModal) this.modalHelper.deactivate();
await stopOldAnimations();
const duration = getDuration(this, "short4");
const animations = [];
if (this.isModal) animations.push(animateTo(overlay, [{ opacity: 1 }, { opacity: 0 }], {
duration,
easing: easingLinear
}));
else if (!this.isParentLayout) animations.push(this.getLockTargetAnimate(false, duration));
if (this.isParentLayout) {
setLayoutTransition(duration, easingEmphasized);
this.layoutManager.updateLayout(this, { width: 0 });
}
animations.push(animateTo(this.isModal ? panel : this, [{ transform: "translateX(0)" }, { transform: `translateX(${isRight ? "" : "-"}100%)` }], {
duration,
easing: easingEmphasized
}));
await Promise.all(animations);
if (this.open) return;
if (this.isParentLayout) setLayoutTransition(null);
this.style.display = "none";
if (this.isModal && !this.contained) unlockScreen(this, this.lockTarget);
const trigger = this.originalTrigger;
if (isFunction(trigger?.focus)) setTimeout(() => trigger.focus());
this.emit("closed");
}
}
connectedCallback() {
super.connectedCallback();
this.modalHelper = new Modal(this);
this.definedController.whenDefined().then(() => {
this.setObserveResize();
});
}
disconnectedCallback() {
super.disconnectedCallback();
unlockScreen(this, this.lockTarget);
this.observeResize?.unobserve();
}
firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties);
this.addEventListener("keydown", (event) => {
if (this.open && this.closeOnEsc && event.key === "Escape" && this.isModal) {
event.stopPropagation();
this.open = false;
}
});
}
render() {
return b`${n(this.isModal, () => b`
`)}
`;
}
setObserveResize() {
this.observeResize = observeResize(this.contained ? this.parentElement : document.documentElement, () => {
this.mobile = breakpoint(this.contained ? this.parentElement : void 0).down("md");
if (this.isParentLayout) this.layoutManager.updateLayout(this, { width: this.isModal ? 0 : void 0 });
});
}
onOverlayClick() {
this.emit("overlay-click");
if (this.closeOnOverlayClick) this.open = false;
}
getLockTargetAnimate(open, duration) {
const paddingName = this.placement === "right" ? "paddingRight" : "paddingLeft";
const panelWidth = $$1(this.panelRef.value).innerWidth() + "px";
return animateTo(this.lockTarget, [{ [paddingName]: open ? 0 : panelWidth }, { [paddingName]: open ? panelWidth : 0 }], {
duration,
easing: getEasing(this, "emphasized"),
fill: "forwards"
});
}
};
NavigationDrawer.styles = [componentStyle, style$6];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationDrawer.prototype, "open", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationDrawer.prototype, "modal", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "close-on-esc"
})], NavigationDrawer.prototype, "closeOnEsc", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "close-on-overlay-click"
})], NavigationDrawer.prototype, "closeOnOverlayClick", void 0);
__decorate([n$6({ reflect: true })], NavigationDrawer.prototype, "placement", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationDrawer.prototype, "contained", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationDrawer.prototype, "mobile", void 0);
__decorate([watch("contained", true)], NavigationDrawer.prototype, "onContainedChange", null);
__decorate([watch("placement", true)], NavigationDrawer.prototype, "onPlacementChange", null);
__decorate([watch("mobile", true), watch("modal", true)], NavigationDrawer.prototype, "onMobileChange", null);
__decorate([watch("open")], NavigationDrawer.prototype, "onOpenChange", null);
NavigationDrawer = __decorate([t$3("mdui-navigation-drawer")], NavigationDrawer);
var navigationRailStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-none);--z-index:2000;position:fixed;top:0;bottom:0;left:0;display:flex;flex-direction:column;align-items:center;border-radius:0 var(--shape-corner) var(--shape-corner) 0;z-index:var(--z-index);width:5rem;background-color:rgb(var(--mdui-color-surface));padding:.375rem .75rem}:host([contained]:not([contained=false i])){position:absolute}:host([divider]:not([divider=false i])){border-right:.0625rem solid rgb(var(--mdui-color-surface-variant));width:5.0625rem}:host([placement=right]){left:initial;right:0;border-radius:var(--shape-corner) 0 0 var(--shape-corner)}:host([placement=right][divider]:not([divider=false i])){border-right:none;border-left:.0625rem solid rgb(var(--mdui-color-surface-variant))}.bottom,.items,.top{display:flex;flex-direction:column;align-items:center;width:100%}.top{margin-bottom:1.75rem}.bottom{margin-top:1.75rem}::slotted([slot=bottom]),::slotted([slot=top]),::slotted(mdui-navigation-rail-item){margin-top:.375rem;margin-bottom:.375rem}:host([alignment=start]) .top-spacer{flex-grow:0}:host([alignment=start]) .bottom-spacer{flex-grow:1}:host([alignment=end]) .top-spacer{flex-grow:1}:host([alignment=end]) .bottom-spacer{flex-grow:0}:host([alignment=center]){justify-content:center}:host([alignment=center]) .bottom,:host([alignment=center]) .top{position:absolute}:host([alignment=center]) .top{top:.375rem}:host([alignment=center]) .bottom{bottom:.375rem}`;
var NavigationRail = class NavigationRail extends LayoutItemBase {
constructor() {
super(...arguments);
this.placement = "left";
this.alignment = "start";
this.contained = false;
this.divider = false;
this.activeKey = 0;
this.hasSlotController = new HasSlotController(this, "top", "bottom");
this.definedController = new DefinedController(this, { relatedElements: ["mdui-navigation-rail-item"] });
this.isInitial = true;
}
get layoutPlacement() {
return this.placement;
}
get parentTarget() {
return this.contained || this.isParentLayout ? this.parentElement : document.body;
}
get isRight() {
return this.placement === "right";
}
get paddingValue() {
return ["fixed", "absolute"].includes($$1(this).css("position")) ? this.offsetWidth : void 0;
}
async onActiveKeyChange() {
await this.definedController.whenDefined();
this.value = this.items.find((item) => item.key === this.activeKey)?.value;
if (!this.isInitial) this.emit("change");
}
async onValueChange() {
this.isInitial = !this.hasUpdated;
await this.definedController.whenDefined();
this.activeKey = this.items.find((item) => item.value === this.value)?.key ?? 0;
this.updateItems();
}
async onContainedChange() {
if (this.isParentLayout) return;
await this.definedController.whenDefined();
$$1(document.body).css({
paddingLeft: this.contained || this.isRight ? null : this.paddingValue,
paddingRight: this.contained || !this.isRight ? null : this.paddingValue
});
$$1(this.parentElement).css({
paddingLeft: this.contained && !this.isRight ? this.paddingValue : null,
paddingRight: this.contained && this.isRight ? this.paddingValue : null
});
}
async onPlacementChange() {
await this.definedController.whenDefined();
this.layoutManager?.updateLayout(this);
this.items.forEach((item) => {
item.placement = this.placement;
});
if (!this.isParentLayout) $$1(this.parentTarget).css({
paddingLeft: this.isRight ? null : this.paddingValue,
paddingRight: this.isRight ? this.paddingValue : null
});
}
connectedCallback() {
super.connectedCallback();
if (!this.isParentLayout) this.definedController.whenDefined().then(() => {
$$1(this.parentTarget).css({
paddingLeft: this.isRight ? null : this.paddingValue,
paddingRight: this.isRight ? this.paddingValue : null
});
});
}
disconnectedCallback() {
super.disconnectedCallback();
if (!this.isParentLayout && this.definedController.isDefined()) $$1(this.parentTarget).css({
paddingLeft: this.isRight ? void 0 : null,
paddingRight: this.isRight ? null : void 0
});
}
render() {
const hasTopSlot = this.hasSlotController.test("top");
const hasBottomSlot = this.hasSlotController.test("bottom");
return b`${n(hasTopSlot, () => b`
`)}
${n(hasBottomSlot, () => b`
`)}`;
}
onClick(event) {
if (event.button) return;
const item = event.target.closest("mdui-navigation-rail-item");
if (!item) return;
this.activeKey = item.key;
this.isInitial = false;
this.updateItems();
}
updateItems() {
this.items.forEach((item) => {
item.active = this.activeKey === item.key;
item.placement = this.placement;
item.isInitial = this.isInitial;
});
}
async onSlotChange() {
await this.definedController.whenDefined();
this.updateItems();
}
};
NavigationRail.styles = [componentStyle, navigationRailStyle];
__decorate([n$6({ reflect: true })], NavigationRail.prototype, "value", void 0);
__decorate([n$6({ reflect: true })], NavigationRail.prototype, "placement", void 0);
__decorate([n$6({ reflect: true })], NavigationRail.prototype, "alignment", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationRail.prototype, "contained", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationRail.prototype, "divider", void 0);
__decorate([r$2()], NavigationRail.prototype, "activeKey", void 0);
__decorate([o$7({
selector: "mdui-navigation-rail-item",
flatten: true
})], NavigationRail.prototype, "items", void 0);
__decorate([watch("activeKey", true)], NavigationRail.prototype, "onActiveKeyChange", null);
__decorate([watch("value")], NavigationRail.prototype, "onValueChange", null);
__decorate([watch("contained", true)], NavigationRail.prototype, "onContainedChange", null);
__decorate([watch("placement", true)], NavigationRail.prototype, "onPlacementChange", null);
NavigationRail = __decorate([t$3("mdui-navigation-rail")], NavigationRail);
var navigationRailItemStyle = i$7`:host{--shape-corner-indicator:var(--mdui-shape-corner-full);position:relative;z-index:0;width:100%;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface-variant)}.container{display:flex;flex-direction:column;align-items:center;justify-content:center;text-decoration:none;cursor:pointer;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;height:3.5rem}.container:not(.initial){transition:padding var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}mdui-ripple{z-index:1;width:3.5rem;height:2rem;border-radius:var(--mdui-shape-corner-full)}.container:not(.has-label)+mdui-ripple{height:3.5rem}.indicator{position:relative;display:flex;align-items:center;justify-content:center;background-color:transparent;border-radius:var(--shape-corner-indicator);height:2rem;width:2rem}:not(.initial) .indicator{transition:background-color var(--mdui-motion-duration-short1) var(--mdui-motion-easing-standard),width var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard),height var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}::slotted([slot=badge]){position:absolute;transform:translate(50%,-50%)}.placement-right::slotted([slot=badge]){transform:translate(-50%,-50%)}::slotted([slot=badge][variant=small]){transform:translate(.5625rem,-.5625rem)}.placement-right::slotted([slot=badge][variant=small]){transform:translate(-.5625rem,-.5625rem)}.active-icon,.icon{color:rgb(var(--mdui-color-on-surface-variant));font-size:1.5rem}.active-icon mdui-icon,.icon mdui-icon,::slotted([slot=active-icon]),::slotted([slot=icon]){font-size:inherit}.icon{display:flex}.active-icon{display:none}.label{display:flex;align-items:center;height:1rem;color:rgb(var(--mdui-color-on-surface-variant));margin-top:.25rem;margin-bottom:.25rem;font-size:var(--mdui-typescale-label-medium-size);font-weight:var(--mdui-typescale-label-medium-weight);letter-spacing:var(--mdui-typescale-label-medium-tracking);line-height:var(--mdui-typescale-label-medium-line-height)}:not(.initial) .label{transition:opacity var(--mdui-motion-duration-short4) var(--mdui-motion-easing-linear)}:host([active]){--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}:host([active]) .indicator{width:3.5rem;background-color:rgb(var(--mdui-color-secondary-container))}:host([active]) :not(.has-label) .indicator{height:3.5rem}:host([active]) .active-icon,:host([active]) .icon{color:rgb(var(--mdui-color-on-secondary-container))}:host([active]) .has-active-icon .active-icon{display:flex}:host([active]) .has-active-icon .icon{display:none}:host([active]) .label{color:rgb(var(--mdui-color-on-surface))}`;
var NavigationRailItem = class NavigationRailItem extends AnchorMixin(RippleMixin(FocusableMixin(MduiElement))) {
constructor() {
super(...arguments);
this.active = false;
this.isInitial = true;
this.placement = "left";
this.disabled = false;
this.key = uniqueId();
this.rippleRef = e$1();
this.hasSlotController = new HasSlotController(this, "[default]", "active-icon");
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.disabled;
}
get focusElement() {
return this.href ? this.renderRoot?.querySelector("._a") : this;
}
get focusDisabled() {
return this.disabled;
}
render() {
const hasDefaultSlot = this.hasSlotController.test("[default]");
const className = cc({
container: true,
"has-label": hasDefaultSlot,
"has-active-icon": this.activeIcon || this.hasSlotController.test("active-icon"),
initial: this.isInitial
});
return b`${this.href ? this.renderAnchor({
part: "container",
className,
content: this.renderInner(hasDefaultSlot)
}) : b`
${this.renderInner(hasDefaultSlot)}
`}
`;
}
renderInner(hasDefaultSlot) {
return b`
${this.activeIcon ? b`` : nothingTemplate}${this.icon ? b`` : nothingTemplate}
${hasDefaultSlot ? b`
` : A}`;
}
};
NavigationRailItem.styles = [componentStyle, navigationRailItemStyle];
__decorate([n$6({ reflect: true })], NavigationRailItem.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "active-icon"
})], NavigationRailItem.prototype, "activeIcon", void 0);
__decorate([n$6({ reflect: true })], NavigationRailItem.prototype, "value", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], NavigationRailItem.prototype, "active", void 0);
__decorate([r$2()], NavigationRailItem.prototype, "isInitial", void 0);
__decorate([r$2()], NavigationRailItem.prototype, "placement", void 0);
__decorate([r$2()], NavigationRailItem.prototype, "disabled", void 0);
NavigationRailItem = __decorate([t$3("mdui-navigation-rail-item")], NavigationRailItem);
var IconCircle = class IconCircle extends i$4 {
render() {
return svgTag("
");
}
};
IconCircle.styles = style$14;
IconCircle = __decorate([t$3("mdui-icon-circle")], IconCircle);
var IconRadioButtonUnchecked = class IconRadioButtonUnchecked extends i$4 {
render() {
return svgTag("
");
}
};
IconRadioButtonUnchecked.styles = style$14;
IconRadioButtonUnchecked = __decorate([t$3("mdui-icon-radio-button-unchecked")], IconRadioButtonUnchecked);
var radioStyle = i$7`:host{position:relative;display:inline-flex;align-items:center;cursor:pointer;-webkit-tap-highlight-color:transparent;-webkit-user-select:none;user-select:none;touch-action:manipulation;zoom:1;-webkit-user-drag:none;border-radius:.125rem;font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking);line-height:var(--mdui-typescale-label-large-line-height)}.icon{display:flex;position:absolute;font-size:1.5rem}:not(.initial) .icon{transition-duration:var(--mdui-motion-duration-short4);transition-timing-function:var(--mdui-motion-easing-standard)}.unchecked-icon{transition-property:color;color:rgb(var(--mdui-color-on-surface-variant))}:host([focused]) .unchecked-icon,:host([hover]) .unchecked-icon,:host([pressed]) .unchecked-icon{color:rgb(var(--mdui-color-on-surface))}.checked-icon{opacity:0;transform:scale(.2);transition-property:color,opacity,transform;color:rgb(var(--mdui-color-primary))}.icon .i,::slotted([slot=checked-icon]),::slotted([slot=unchecked-icon]){color:inherit;font-size:inherit}i{position:relative;display:flex;align-items:center;justify-content:center;flex-shrink:0;overflow:hidden;border-radius:50%;width:2.5rem;height:2.5rem;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}.label{display:flex;width:100%;padding-top:.625rem;padding-bottom:.625rem;color:rgb(var(--mdui-color-on-surface))}.label:not(.initial){transition:color var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}:host([checked]:not([checked=false i])) i{--mdui-comp-ripple-state-layer-color:var(--mdui-color-primary)}:host([checked]:not([checked=false i])) .icon{color:rgb(var(--mdui-color-primary))}:host([checked]:not([checked=false i])) .checked-icon{opacity:1;transform:scale(.5)}i.invalid{--mdui-comp-ripple-state-layer-color:var(--mdui-color-error)}i.invalid .icon{color:rgb(var(--mdui-color-error))}.label.invalid{color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])),:host([group-disabled]){cursor:default;pointer-events:none}:host([disabled]:not([disabled=false i])) .icon,:host([group-disabled]) .icon{color:rgba(var(--mdui-color-on-surface),38%)}:host([disabled]:not([disabled=false i])) .label,:host([group-disabled]) .label{color:rgba(var(--mdui-color-on-surface),38%)}`;
var Radio = class Radio extends RippleMixin(FocusableMixin(MduiElement)) {
constructor() {
super(...arguments);
this.value = "";
this.disabled = false;
this.checked = false;
this.invalid = false;
this.groupDisabled = false;
this.focusable = true;
this.isInitial = true;
this.rippleRef = e$1();
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.isDisabled();
}
get focusElement() {
return this;
}
get focusDisabled() {
return this.isDisabled() || !this.focusable;
}
onCheckedChange() {
this.emit("change");
}
firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties);
this.addEventListener("click", () => {
if (!this.isDisabled()) this.checked = true;
});
}
render() {
const className = e({
invalid: this.invalid,
initial: this.isInitial
});
return b`
${this.uncheckedIcon ? b`` : b``}${this.checkedIcon ? b`` : b``}`;
}
isDisabled() {
return this.disabled || this.groupDisabled;
}
};
Radio.styles = [componentStyle, radioStyle];
__decorate([n$6({ reflect: true })], Radio.prototype, "value", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Radio.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Radio.prototype, "checked", void 0);
__decorate([n$6({
reflect: true,
attribute: "unchecked-icon"
})], Radio.prototype, "uncheckedIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "checked-icon"
})], Radio.prototype, "checkedIcon", void 0);
__decorate([r$2()], Radio.prototype, "invalid", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "group-disabled"
})], Radio.prototype, "groupDisabled", void 0);
__decorate([r$2()], Radio.prototype, "focusable", void 0);
__decorate([r$2()], Radio.prototype, "isInitial", void 0);
__decorate([watch("checked", true)], Radio.prototype, "onCheckedChange", null);
Radio = __decorate([t$3("mdui-radio")], Radio);
var radioGroupStyle = i$7`:host{display:inline-block}fieldset{border:none;padding:0;margin:0;min-width:0}input{position:absolute;padding:0;opacity:0;pointer-events:none;width:1.25rem;height:1.25rem;margin:0 0 0 .625rem}`;
var RadioGroup = class RadioGroup extends MduiElement {
constructor() {
super(...arguments);
this.disabled = false;
this.name = "";
this.value = "";
this.defaultValue = "";
this.required = false;
this.invalid = false;
this.isInitial = true;
this.inputRef = e$1();
this.formController = new FormController(this);
this.definedController = new DefinedController(this, { relatedElements: ["mdui-radio"] });
}
get validity() {
return this.inputRef.value.validity;
}
get validationMessage() {
return this.inputRef.value.validationMessage;
}
get items() {
return $$1(this).find("mdui-radio").get();
}
get itemsEnabled() {
return $$1(this).find("mdui-radio:not([disabled])").get();
}
async onValueChange() {
this.isInitial = false;
await this.definedController.whenDefined();
this.emit("input");
this.emit("change");
this.updateItems();
this.updateRadioFocusable();
await this.updateComplete;
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.inputRef.value.checkValidity();
}
async onInvalidChange() {
await this.definedController.whenDefined();
this.updateItems();
}
checkValidity() {
const valid = this.inputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.inputRef.value.reportValidity();
if (this.invalid) {
if (!this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
})) {
this.inputRef.value.blur();
this.inputRef.value.focus();
}
}
return !this.invalid;
}
setCustomValidity(message) {
this.inputRef.value.setCustomValidity(message);
this.invalid = !this.inputRef.value.checkValidity();
}
render() {
return b`
`;
}
updateRadioFocusable() {
const items = this.items;
const itemChecked = items.find((item) => item.checked);
if (itemChecked) items.forEach((item) => {
item.focusable = item === itemChecked;
});
else this.itemsEnabled.forEach((item, index) => {
item.focusable = !index;
});
}
async onClick(event) {
await this.definedController.whenDefined();
const item = event.target.closest("mdui-radio");
if (!item || item.disabled) return;
this.value = item.value;
await this.updateComplete;
item.focus();
}
async onKeyDown(event) {
if (![
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
" "
].includes(event.key)) return;
event.preventDefault();
await this.definedController.whenDefined();
const items = this.itemsEnabled;
const itemChecked = items.find((item) => item.checked) ?? items[0];
const incr = event.key === " " ? 0 : ["ArrowUp", "ArrowLeft"].includes(event.key) ? -1 : 1;
let index = items.indexOf(itemChecked) + incr;
if (index < 0) index = items.length - 1;
if (index > items.length - 1) index = 0;
this.value = items[index].value;
await this.updateComplete;
items[index].focus();
}
async onSlotChange() {
await this.definedController.whenDefined();
this.updateItems();
this.updateRadioFocusable();
}
onCheckedChange(event) {
event.stopPropagation();
}
updateItems() {
this.items.forEach((item) => {
item.checked = item.value === this.value;
item.invalid = this.invalid;
item.groupDisabled = this.disabled;
item.isInitial = this.isInitial;
});
}
};
RadioGroup.styles = [componentStyle, radioGroupStyle];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], RadioGroup.prototype, "disabled", void 0);
__decorate([n$6({ reflect: true })], RadioGroup.prototype, "form", void 0);
__decorate([n$6({ reflect: true })], RadioGroup.prototype, "name", void 0);
__decorate([n$6({ reflect: true })], RadioGroup.prototype, "value", void 0);
__decorate([defaultValue()], RadioGroup.prototype, "defaultValue", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], RadioGroup.prototype, "required", void 0);
__decorate([r$2()], RadioGroup.prototype, "invalid", void 0);
__decorate([watch("value", true)], RadioGroup.prototype, "onValueChange", null);
__decorate([watch("invalid", true), watch("disabled")], RadioGroup.prototype, "onInvalidChange", null);
RadioGroup = __decorate([t$3("mdui-radio-group")], RadioGroup);
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
function* o(o, f) {
if (void 0 !== o) {
let i = 0;
for (const t of o) yield f(t, i++);
}
}
var sliderBaseStyle = i$7`:host{position:relative;display:block;width:100%;-webkit-tap-highlight-color:transparent;height:2.5rem;padding:0 1.25rem}label{position:relative;display:block;width:100%;height:100%}input[type=range]{position:absolute;inset:0;z-index:4;height:100%;cursor:pointer;opacity:0;appearance:none;width:calc(100% + 20rem * 2 / 16);margin:0 -1.25rem;padding:0 .75rem}:host([disabled]:not([disabled=false i])) input[type=range]{cursor:not-allowed}.track-active,.track-inactive{position:absolute;top:50%;height:.25rem;margin-top:-.125rem}.track-inactive{left:-.125rem;right:-.125rem;border-radius:var(--mdui-shape-corner-full);background-color:rgb(var(--mdui-color-surface-container-highest))}.invalid .track-inactive{background-color:rgba(var(--mdui-color-error),.12)}:host([disabled]:not([disabled=false i])) .track-inactive{background-color:rgba(var(--mdui-color-on-surface),.12)}.track-active{background-color:rgb(var(--mdui-color-primary))}.invalid .track-active{background-color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])) .track-active{background-color:rgba(var(--mdui-color-on-surface),.38)}.handle{position:absolute;top:50%;transform:translate(-50%);cursor:pointer;z-index:2;width:2.5rem;height:2.5rem;margin-top:-1.25rem;--mdui-comp-ripple-state-layer-color:var(--mdui-color-primary)}.invalid .handle{--mdui-comp-ripple-state-layer-color:var(--mdui-color-error)}.handle .elevation,.handle::before{position:absolute;display:block;content:' ';left:.625rem;top:.625rem;width:1.25rem;height:1.25rem;border-radius:var(--mdui-shape-corner-full)}.handle .elevation{background-color:rgb(var(--mdui-color-primary));box-shadow:var(--mdui-elevation-level1)}.invalid .handle .elevation{background-color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])) .handle .elevation{background-color:rgba(var(--mdui-color-on-surface),.38);box-shadow:var(--mdui-elevation-level0)}.handle::before{background-color:rgb(var(--mdui-color-background))}.handle mdui-ripple{border-radius:var(--mdui-shape-corner-full)}.label{position:absolute;left:50%;transform:translateX(-50%) scale(0);transform-origin:center bottom;display:flex;align-items:center;justify-content:center;cursor:default;white-space:nowrap;-webkit-user-select:none;user-select:none;pointer-events:none;transition:transform var(--mdui-motion-duration-short2) var(--mdui-motion-easing-standard);bottom:2.5rem;min-width:1.75rem;height:1.75rem;padding:.375rem .5rem;border-radius:var(--mdui-shape-corner-full);color:rgb(var(--mdui-color-on-primary));font-size:var(--mdui-typescale-label-medium-size);font-weight:var(--mdui-typescale-label-medium-weight);letter-spacing:var(--mdui-typescale-label-medium-tracking);line-height:var(--mdui-typescale-label-medium-line-height);background-color:rgb(var(--mdui-color-primary))}.invalid .label{color:rgb(var(--mdui-color-on-error));background-color:rgb(var(--mdui-color-error))}.label::after{content:' ';position:absolute;z-index:-1;transform:rotate(45deg);width:.875rem;height:.875rem;bottom:-.125rem;background-color:rgb(var(--mdui-color-primary))}.invalid .label::after{background-color:rgb(var(--mdui-color-error))}.label-visible{transform:translateX(-50%) scale(1);transition:transform var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}.tickmark{position:absolute;top:50%;transform:translate(-50%);width:.125rem;height:.125rem;margin-top:-.0625rem;border-radius:var(--mdui-shape-corner-full);background-color:rgba(var(--mdui-color-on-surface-variant),.38)}.invalid .tickmark{background-color:rgba(var(--mdui-color-error),.38)}.tickmark.active{background-color:rgba(var(--mdui-color-on-primary),.38)}.invalid .tickmark.active{background-color:rgba(var(--mdui-color-on-error),.38)}:host([disabled]:not([disabled=false i])) .tickmark{background-color:rgba(var(--mdui-color-on-surface),.38)}`;
var SliderBase = class extends RippleMixin(FocusableMixin(MduiElement)) {
constructor() {
super(...arguments);
this.min = 0;
this.max = 100;
this.step = 1;
this.tickmarks = false;
this.nolabel = false;
this.disabled = false;
this.name = "";
this.invalid = false;
this.labelVisible = false;
this.inputRef = e$1();
this.trackActiveRef = e$1();
this.labelFormatter = (value) => value.toString();
}
get validity() {
return this.inputRef.value.validity;
}
get validationMessage() {
return this.inputRef.value.validationMessage;
}
get rippleDisabled() {
return this.disabled;
}
get focusElement() {
return this.inputRef.value;
}
get focusDisabled() {
return this.disabled;
}
onDisabledChange() {
this.invalid = !this.inputRef.value.checkValidity();
}
checkValidity() {
const valid = this.inputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.inputRef.value.reportValidity();
if (this.invalid) {
if (!this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
})) {
this.blur();
this.focus();
}
}
return !this.invalid;
}
setCustomValidity(message) {
this.inputRef.value.setCustomValidity(message);
this.invalid = !this.inputRef.value.checkValidity();
}
fixValue(value) {
const { min, max, step } = this;
value = Math.min(Math.max(value, min), max);
let fixedValue = min + Math.round((value - min) / step) * step;
if (fixedValue > max) fixedValue -= step;
return fixedValue;
}
getCandidateValues() {
return Array.from({ length: this.max - this.min + 1 }, (_, index) => index + this.min).filter((value) => !((value - this.min) % this.step));
}
renderLabel(value) {
return n(!this.nolabel, () => b`
${this.labelFormatter(value)}
`);
}
onChange() {
this.emit("change");
}
};
SliderBase.styles = [componentStyle, sliderBaseStyle];
__decorate([n$6({
type: Number,
reflect: true
})], SliderBase.prototype, "min", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], SliderBase.prototype, "max", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], SliderBase.prototype, "step", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SliderBase.prototype, "tickmarks", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SliderBase.prototype, "nolabel", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SliderBase.prototype, "disabled", void 0);
__decorate([n$6({ reflect: true })], SliderBase.prototype, "form", void 0);
__decorate([n$6({ reflect: true })], SliderBase.prototype, "name", void 0);
__decorate([r$2()], SliderBase.prototype, "invalid", void 0);
__decorate([r$2()], SliderBase.prototype, "labelVisible", void 0);
__decorate([n$6({ attribute: false })], SliderBase.prototype, "labelFormatter", void 0);
__decorate([watch("disabled", true)], SliderBase.prototype, "onDisabledChange", null);
var RangeSlider = class RangeSlider extends SliderBase {
constructor() {
super(...arguments);
this.defaultValue = [];
this.currentHandle = "start";
this.rippleStartRef = e$1();
this.rippleEndRef = e$1();
this.handleStartRef = e$1();
this.handleEndRef = e$1();
this.formController = new FormController(this);
this._value = [];
this.getRippleIndex = () => {
if (this.hoverHandle) return this.hoverHandle === "start" ? 0 : 1;
return this.currentHandle === "start" ? 0 : 1;
};
}
get value() {
return this._value;
}
set value(_value) {
const oldValue = [...this._value];
this._value = [this.fixValue(_value[0]), this.fixValue(_value[1])];
this.requestUpdate("value", oldValue);
this.updateComplete.then(() => {
this.updateStyle();
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.inputRef.value.checkValidity();
});
}
get rippleElement() {
return [this.rippleStartRef.value, this.rippleEndRef.value];
}
connectedCallback() {
super.connectedCallback();
if (!this.value.length) this.value = [this.min, this.max];
this.value[0] = this.fixValue(this.value[0]);
this.value[1] = this.fixValue(this.value[1]);
if (!this.defaultValue.length) this.defaultValue = [...this.value];
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
const getCurrentHandle = (event) => {
const $this = $$1(this);
const paddingLeft = parseFloat($this.css("padding-left"));
const paddingRight = parseFloat($this.css("padding-right"));
const percent = (event.offsetX - paddingLeft) / (this.clientWidth - paddingLeft - paddingRight);
return (this.max - this.min) * percent + this.min > (this.value[1] - this.value[0]) / 2 + this.value[0] ? "end" : "start";
};
const onTouchStart = () => {
if (!this.disabled) this.labelVisible = true;
};
const onTouchEnd = () => {
if (!this.disabled) this.labelVisible = false;
};
this.addEventListener("touchstart", onTouchStart);
this.addEventListener("mousedown", onTouchStart);
this.addEventListener("touchend", onTouchEnd);
this.addEventListener("mouseup", onTouchEnd);
this.addEventListener("pointerdown", (event) => {
this.currentHandle = getCurrentHandle(event);
});
this.addEventListener("pointermove", (event) => {
const currentHandle = getCurrentHandle(event);
if (this.hoverHandle !== currentHandle) {
this.endHover(event);
this.hoverHandle = currentHandle;
this.startHover(event);
}
});
this.updateStyle();
}
render() {
return b`
`;
}
updateStyle() {
const getPercent = (value) => (value - this.min) / (this.max - this.min) * 100;
const startPercent = getPercent(this.value[0]);
const endPercent = getPercent(this.value[1]);
this.trackActiveRef.value.style.width = `${endPercent - startPercent}%`;
this.trackActiveRef.value.style.left = `${startPercent}%`;
this.handleStartRef.value.style.left = `${startPercent}%`;
this.handleEndRef.value.style.left = `${endPercent}%`;
}
onInput() {
const isStart = this.currentHandle === "start";
const value = parseFloat(this.inputRef.value.value);
const startValue = this.value[0];
const endValue = this.value[1];
const doInput = () => {
this.updateStyle();
};
if (isStart) {
if (value <= endValue) {
this.value = [value, endValue];
doInput();
} else if (startValue !== endValue) {
this.value = [endValue, endValue];
doInput();
}
} else if (value >= startValue) {
this.value = [startValue, value];
doInput();
} else if (startValue !== endValue) {
this.value = [startValue, startValue];
doInput();
}
}
};
RangeSlider.styles = [SliderBase.styles];
__decorate([defaultValue()], RangeSlider.prototype, "defaultValue", void 0);
__decorate([r$2()], RangeSlider.prototype, "currentHandle", void 0);
__decorate([n$6({
type: Array,
attribute: false
})], RangeSlider.prototype, "value", null);
RangeSlider = __decorate([t$3("mdui-range-slider")], RangeSlider);
var segmentedButtonStyle = i$7`:host{position:relative;display:inline-flex;flex-grow:1;flex-shrink:0;float:left;height:100%;overflow:hidden;cursor:pointer;-webkit-tap-highlight-color:transparent;border:.0625rem solid rgb(var(--mdui-color-outline))}.button{width:100%;padding:0 .75rem}:host([invalid]){color:rgb(var(--mdui-color-error));border-color:rgb(var(--mdui-color-error))}:host([invalid]) .button{background-color:rgb(var(--mdui-color-error-container))}:host([selected]){color:rgb(var(--mdui-color-on-secondary-container));background-color:rgb(var(--mdui-color-secondary-container));--mdui-comp-ripple-state-layer-color:var(
--mdui-color-on-secondary-container
)}:host([disabled]:not([disabled=false i])),:host([group-disabled]){cursor:default;pointer-events:none;color:rgba(var(--mdui-color-on-surface),38%);border-color:rgba(var(--mdui-color-on-surface),12%)}:host([loading]:not([loading=false i])){cursor:default;pointer-events:none}:host(:not(.mdui-segmented-button-first)){margin-left:-.0625rem}:host(.mdui-segmented-button-first){border-radius:var(--shape-corner) 0 0 var(--shape-corner)}:host(.mdui-segmented-button-last){border-radius:0 var(--shape-corner) var(--shape-corner) 0}.end-icon,.icon,.selected-icon{display:inline-flex;font-size:1.28571429em}.end-icon .i,.icon .i,.selected-icon .i,::slotted([slot=end-icon]),::slotted([slot=icon]),::slotted([slot=selected-icon]){font-size:inherit}mdui-circular-progress{width:1.125rem;height:1.125rem}:host([disabled]:not([disabled=false i])) mdui-circular-progress{opacity:.38}.label{display:inline-flex}.has-icon .label{padding-left:.5rem}.has-end-icon .label{padding-right:.5rem}`;
var SegmentedButton = class SegmentedButton extends ButtonBase {
constructor() {
super(...arguments);
this.selected = false;
this.invalid = false;
this.groupDisabled = false;
this.key = uniqueId();
this.rippleRef = e$1();
this.hasSlotController = new HasSlotController(this, "[default]", "icon", "end-icon");
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.isDisabled() || this.loading;
}
get focusDisabled() {
return this.isDisabled() || this.loading;
}
render() {
const className = cc({
button: true,
"has-icon": this.icon || this.selected || this.loading || this.hasSlotController.test("icon"),
"has-end-icon": this.endIcon || this.hasSlotController.test("end-icon")
});
return b`
${this.isButton() ? this.renderButton({
className,
part: "button",
content: this.renderInner()
}) : this.isDisabled() || this.loading ? b`
${this.renderInner()}` : this.renderAnchor({
className,
part: "button",
content: this.renderInner()
})}`;
}
isDisabled() {
return this.disabled || this.groupDisabled;
}
renderIcon() {
if (this.loading) return this.renderLoading();
if (this.selected) return b`
${this.selectedIcon ? b`` : b``}`;
return b`
${this.icon ? b`` : nothingTemplate}`;
}
renderLabel() {
if (!this.hasSlotController.test("[default]")) return nothingTemplate;
return b`
`;
}
renderEndIcon() {
return b`
${this.endIcon ? b`` : nothingTemplate}`;
}
renderInner() {
return [
this.renderIcon(),
this.renderLabel(),
this.renderEndIcon()
];
}
};
SegmentedButton.styles = [ButtonBase.styles, segmentedButtonStyle];
__decorate([n$6({ reflect: true })], SegmentedButton.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-icon"
})], SegmentedButton.prototype, "endIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "selected-icon"
})], SegmentedButton.prototype, "selectedIcon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SegmentedButton.prototype, "selected", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SegmentedButton.prototype, "invalid", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "group-disabled"
})], SegmentedButton.prototype, "groupDisabled", void 0);
SegmentedButton = __decorate([t$3("mdui-segmented-button")], SegmentedButton);
var segmentedButtonGroupStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-full);position:relative;display:inline-flex;vertical-align:middle;height:2.5rem;font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking);line-height:var(--mdui-typescale-label-large-line-height);color:rgb(var(--mdui-color-on-surface));--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}:host([full-width]:not([full-width=false i])){display:flex;flex-wrap:nowrap}input,select{position:absolute;width:100%;height:100%;padding:0;opacity:0;pointer-events:none}`;
var SegmentedButtonGroup = class SegmentedButtonGroup extends MduiElement {
constructor() {
super(...arguments);
this.fullWidth = false;
this.disabled = false;
this.required = false;
this.name = "";
this.value = "";
this.defaultValue = "";
this.selectedKeys = [];
this.invalid = false;
this.isInitial = true;
this.inputRef = e$1();
this.formController = new FormController(this);
this.definedController = new DefinedController(this, { relatedElements: ["mdui-segmented-button"] });
}
get validity() {
return this.inputRef.value.validity;
}
get validationMessage() {
return this.inputRef.value.validationMessage;
}
get items() {
return $$1(this).find("mdui-segmented-button").get();
}
get itemsEnabled() {
return $$1(this).find("mdui-segmented-button:not([disabled])").get();
}
get isSingle() {
return this.selects === "single";
}
get isMultiple() {
return this.selects === "multiple";
}
get isSelectable() {
return this.isSingle || this.isMultiple;
}
async onSelectsChange() {
if (!this.isSelectable) this.setSelectedKeys([]);
else if (this.isSingle) this.setSelectedKeys(this.selectedKeys.slice(0, 1));
await this.onSelectedKeysChange();
}
async onSelectedKeysChange() {
await this.definedController.whenDefined();
const values = this.itemsEnabled.filter((item) => this.selectedKeys.includes(item.key)).map((item) => item.value);
const value = this.isMultiple ? values : values[0] || "";
this.setValue(value);
if (!this.isInitial) this.emit("change");
}
async onValueChange() {
this.isInitial = !this.hasUpdated;
await this.definedController.whenDefined();
if (!this.isSelectable) {
this.updateItems();
return;
}
const values = (this.isSingle ? [this.value] : isString(this.value) ? [this.value] : this.value).filter((i) => i);
if (!values.length) this.setSelectedKeys([]);
else if (this.isSingle) {
const firstItem = this.itemsEnabled.find((item) => item.value === values[0]);
this.setSelectedKeys(firstItem ? [firstItem.key] : []);
} else if (this.isMultiple) this.setSelectedKeys(this.itemsEnabled.filter((item) => values.includes(item.value)).map((item) => item.key));
this.updateItems();
if (!this.isInitial) {
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.inputRef.value.checkValidity();
}
}
async onInvalidChange() {
await this.definedController.whenDefined();
this.updateItems();
}
connectedCallback() {
super.connectedCallback();
this.value = this.isMultiple && isString(this.value) ? this.value ? [this.value] : [] : this.value;
this.defaultValue = this.selects === "multiple" ? [] : "";
}
checkValidity() {
const valid = this.inputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.inputRef.value.reportValidity();
if (this.invalid) {
if (!this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
})) {
this.inputRef.value.blur();
this.inputRef.value.focus();
}
}
return !this.invalid;
}
setCustomValidity(message) {
this.inputRef.value.setCustomValidity(message);
this.invalid = !this.inputRef.value.checkValidity();
}
render() {
return b`${n(this.isSelectable && this.isSingle, () => b`
`)}${n(this.isSelectable && this.isMultiple, () => b`
`)}
`;
}
selectOne(item) {
if (this.isMultiple) {
const selectedKeys = [...this.selectedKeys];
if (selectedKeys.includes(item.key)) selectedKeys.splice(selectedKeys.indexOf(item.key), 1);
else selectedKeys.push(item.key);
this.setSelectedKeys(selectedKeys);
}
if (this.isSingle) if (this.selectedKeys.includes(item.key)) this.setSelectedKeys([]);
else this.setSelectedKeys([item.key]);
this.isInitial = false;
this.updateItems();
}
async onClick(event) {
if (event.button) return;
await this.definedController.whenDefined();
const item = event.target.closest("mdui-segmented-button");
if (!item || item.disabled) return;
if (this.isSelectable && item.value) this.selectOne(item);
}
async onInputKeyDown(event) {
if (!["Enter", " "].includes(event.key)) return;
event.preventDefault();
await this.definedController.whenDefined();
if (this.isSingle) {
const input = event.target;
input.checked = !input.checked;
this.selectOne(this.itemsEnabled[0]);
this.itemsEnabled[0].focus();
}
if (this.isMultiple) {
this.selectOne(this.itemsEnabled[0]);
this.itemsEnabled[0].focus();
}
}
async onSlotChange() {
await this.definedController.whenDefined();
this.updateItems(true);
}
setSelectedKeys(selectedKeys) {
if (!arraysEqualIgnoreOrder(this.selectedKeys, selectedKeys)) this.selectedKeys = selectedKeys;
}
setValue(value) {
if (this.isSingle) this.value = value;
else if (!arraysEqualIgnoreOrder(this.value, value)) this.value = value;
}
updateItems(slotChange = false) {
const items = this.items;
items.forEach((item, index) => {
item.invalid = this.invalid;
item.groupDisabled = this.disabled;
item.selected = this.selectedKeys.includes(item.key);
if (slotChange) {
item.classList.toggle("mdui-segmented-button-first", index === 0);
item.classList.toggle("mdui-segmented-button-last", index === items.length - 1);
}
});
}
};
SegmentedButtonGroup.styles = [componentStyle, segmentedButtonGroupStyle];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "full-width"
})], SegmentedButtonGroup.prototype, "fullWidth", void 0);
__decorate([n$6({ reflect: true })], SegmentedButtonGroup.prototype, "selects", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SegmentedButtonGroup.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], SegmentedButtonGroup.prototype, "required", void 0);
__decorate([n$6({ reflect: true })], SegmentedButtonGroup.prototype, "form", void 0);
__decorate([n$6({ reflect: true })], SegmentedButtonGroup.prototype, "name", void 0);
__decorate([n$6()], SegmentedButtonGroup.prototype, "value", void 0);
__decorate([defaultValue()], SegmentedButtonGroup.prototype, "defaultValue", void 0);
__decorate([r$2()], SegmentedButtonGroup.prototype, "selectedKeys", void 0);
__decorate([r$2()], SegmentedButtonGroup.prototype, "invalid", void 0);
__decorate([watch("selects", true)], SegmentedButtonGroup.prototype, "onSelectsChange", null);
__decorate([watch("selectedKeys", true)], SegmentedButtonGroup.prototype, "onSelectedKeysChange", null);
__decorate([watch("value")], SegmentedButtonGroup.prototype, "onValueChange", null);
__decorate([watch("invalid", true), watch("disabled")], SegmentedButtonGroup.prototype, "onInvalidChange", null);
SegmentedButtonGroup = __decorate([t$3("mdui-segmented-button-group")], SegmentedButtonGroup);
var IconCancel_Outlined = class IconCancel_Outlined extends i$4 {
render() {
return svgTag("
");
}
};
IconCancel_Outlined.styles = style$14;
IconCancel_Outlined = __decorate([t$3("mdui-icon-cancel--outlined")], IconCancel_Outlined);
var IconError = class IconError extends i$4 {
render() {
return svgTag("
");
}
};
IconError.styles = style$14;
IconError = __decorate([t$3("mdui-icon-error")], IconError);
var IconVisibilityOff = class IconVisibilityOff extends i$4 {
render() {
return svgTag("
");
}
};
IconVisibilityOff.styles = style$14;
IconVisibilityOff = __decorate([t$3("mdui-icon-visibility-off")], IconVisibilityOff);
var IconVisibility = class IconVisibility extends i$4 {
render() {
return svgTag("
");
}
};
IconVisibility.styles = style$14;
IconVisibility = __decorate([t$3("mdui-icon-visibility")], IconVisibility);
var style$5 = i$7`:host{display:inline-block;width:100%}:host([disabled]:not([disabled=false i])){pointer-events:none}:host([type=hidden]){display:none}.container{position:relative;display:flex;align-items:center;height:100%;padding:.125rem .125rem .125rem 1rem;transition:box-shadow var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard)}.container.has-icon{padding-left:.75rem}.container.has-action,.container.has-right-icon,.container.has-suffix{padding-right:.75rem}:host([variant=filled]) .container{box-shadow:inset 0 -.0625rem 0 0 rgb(var(--mdui-color-on-surface-variant));background-color:rgb(var(--mdui-color-surface-container-highest));border-radius:var(--mdui-shape-corner-extra-small) var(--mdui-shape-corner-extra-small) 0 0}:host([variant=outlined]) .container{box-shadow:inset 0 0 0 .0625rem rgb(var(--mdui-color-outline));border-radius:var(--mdui-shape-corner-extra-small)}:host([variant=filled]) .container.invalid,:host([variant=filled]) .container.invalid-style{box-shadow:inset 0 -.0625rem 0 0 rgb(var(--mdui-color-error))}:host([variant=outlined]) .container.invalid,:host([variant=outlined]) .container.invalid-style{box-shadow:inset 0 0 0 .0625rem rgb(var(--mdui-color-error))}:host([variant=filled]:hover) .container{box-shadow:inset 0 -.0625rem 0 0 rgb(var(--mdui-color-on-surface))}:host([variant=outlined]:hover) .container{box-shadow:inset 0 0 0 .0625rem rgb(var(--mdui-color-on-surface))}:host([variant=filled]:hover) .container.invalid,:host([variant=filled]:hover) .container.invalid-style{box-shadow:inset 0 -.0625rem 0 0 rgb(var(--mdui-color-on-error-container))}:host([variant=outlined]:hover) .container.invalid,:host([variant=outlined]:hover) .container.invalid-style{box-shadow:inset 0 0 0 .0625rem rgb(var(--mdui-color-on-error-container))}:host([variant=filled][focused-style]) .container,:host([variant=filled][focused]) .container{box-shadow:inset 0 -.125rem 0 0 rgb(var(--mdui-color-primary))}:host([variant=outlined][focused-style]) .container,:host([variant=outlined][focused]) .container{box-shadow:inset 0 0 0 .125rem rgb(var(--mdui-color-primary))}:host([variant=filled][focused-style]) .container.invalid,:host([variant=filled][focused-style]) .container.invalid-style,:host([variant=filled][focused]) .container.invalid,:host([variant=filled][focused]) .container.invalid-style{box-shadow:inset 0 -.125rem 0 0 rgb(var(--mdui-color-error))}:host([variant=outlined][focused-style]) .container.invalid,:host([variant=outlined][focused-style]) .container.invalid-style,:host([variant=outlined][focused]) .container.invalid,:host([variant=outlined][focused]) .container.invalid-style{box-shadow:inset 0 0 0 .125rem rgb(var(--mdui-color-error))}:host([variant=filled][disabled]:not([disabled=false i])) .container{box-shadow:inset 0 -.0625rem 0 0 rgba(var(--mdui-color-on-surface),38%);background-color:rgba(var(--mdui-color-on-surface),4%)}:host([variant=outlined][disabled]:not([disabled=false i])) .container{box-shadow:inset 0 0 0 .125rem rgba(var(--mdui-color-on-surface),12%)}.action,.icon,.prefix,.right-icon,.suffix{display:flex;-webkit-user-select:none;user-select:none;color:rgb(var(--mdui-color-on-surface-variant))}:host([disabled]:not([disabled=false i])) .action,:host([disabled]:not([disabled=false i])) .icon,:host([disabled]:not([disabled=false i])) .prefix,:host([disabled]:not([disabled=false i])) .right-icon,:host([disabled]:not([disabled=false i])) .suffix{color:rgba(var(--mdui-color-on-surface),38%)}.invalid .right-icon,.invalid-style .right-icon{color:rgb(var(--mdui-color-error))}:host(:hover) .invalid .right-icon,:host(:hover) .invalid-style .right-icon{color:rgb(var(--mdui-color-on-error-container))}:host([focused-style]) .invalid .right-icon,:host([focused-style]) .invalid-style .right-icon,:host([focused]) .invalid .right-icon,:host([focused]) .invalid-style .right-icon{color:rgb(var(--mdui-color-error))}.action,.icon,.right-icon{font-size:1.5rem}.action mdui-button-icon,.icon mdui-button-icon,.right-icon mdui-button-icon,::slotted(mdui-button-icon[slot]){margin-left:-.5rem;margin-right:-.5rem}.action .i,.icon .i,.right-icon .i,::slotted([slot$=icon]){font-size:inherit}.has-icon .icon{margin-right:1rem}.has-prefix .prefix{padding-right:.125rem}.has-action .action{margin-left:.75rem}.has-suffix .suffix{padding-right:.25rem;padding-left:.125rem}.has-right-icon .right-icon{margin-left:.75rem}.prefix,.suffix{display:none;font-size:var(--mdui-typescale-body-large-size);font-weight:var(--mdui-typescale-body-large-weight);letter-spacing:var(--mdui-typescale-body-large-tracking);line-height:var(--mdui-typescale-body-large-line-height)}:host([variant=filled][label]) .prefix,:host([variant=filled][label]) .suffix{padding-top:1rem}.has-value .prefix,.has-value .suffix,:host([focused-style]) .prefix,:host([focused-style]) .suffix,:host([focused]) .prefix,:host([focused]) .suffix{display:flex}.input-container{display:flex;width:100%;height:100%}.label{position:absolute;pointer-events:none;max-width:calc(100% - 1rem);display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1;transition:all var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard);top:1rem;color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-body-large-size);font-weight:var(--mdui-typescale-body-large-weight);letter-spacing:var(--mdui-typescale-body-large-tracking);line-height:var(--mdui-typescale-body-large-line-height)}.invalid .label,.invalid-style .label{color:rgb(var(--mdui-color-error))}:host([variant=outlined]) .label{padding:0 .25rem;margin:0 -.25rem}:host([variant=outlined]:hover) .label{color:rgb(var(--mdui-color-on-surface))}:host([variant=filled]:hover) .invalid .label,:host([variant=filled]:hover) .invalid-style .label,:host([variant=outlined]:hover) .invalid .label,:host([variant=outlined]:hover) .invalid-style .label{color:rgb(var(--mdui-color-on-error-container))}:host([variant=filled][focused-style]) .label,:host([variant=filled][focused]) .label,:host([variant=outlined][focused-style]) .label,:host([variant=outlined][focused]) .label{color:rgb(var(--mdui-color-primary))}:host([variant=filled]) .has-value .label,:host([variant=filled][focused-style]) .label,:host([variant=filled][focused]) .label,:host([variant=filled][type=date]) .label,:host([variant=filled][type=datetime-local]) .label,:host([variant=filled][type=month]) .label,:host([variant=filled][type=time]) .label,:host([variant=filled][type=week]) .label{font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height);top:.25rem}:host([variant=outlined]) .has-value .label,:host([variant=outlined][focused-style]) .label,:host([variant=outlined][focused]) .label,:host([variant=outlined][type=date]) .label,:host([variant=outlined][type=datetime-local]) .label,:host([variant=outlined][type=month]) .label,:host([variant=outlined][type=time]) .label,:host([variant=outlined][type=week]) .label{font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height);top:-.5rem;left:.75rem;background-color:rgb(var(--mdui-color-background))}:host([variant=filled][focused-style]) .invalid .label,:host([variant=filled][focused-style]) .invalid-style .label,:host([variant=filled][focused]) .invalid .label,:host([variant=filled][focused]) .invalid-style .label,:host([variant=outlined][focused-style]) .invalid .label,:host([variant=outlined][focused-style]) .invalid-style .label,:host([variant=outlined][focused]) .invalid .label,:host([variant=outlined][focused]) .invalid-style .label{color:rgb(var(--mdui-color-error))}:host([variant=filled][disabled]:not([disabled=false i])) .label,:host([variant=outlined][disabled]:not([disabled=false i])) .label{color:rgba(var(--mdui-color-on-surface),38%)}.input{display:block;width:100%;border:none;outline:0;background:0 0;appearance:none;resize:none;cursor:inherit;font-family:inherit;padding:.875rem .875rem .875rem 0;font-size:var(--mdui-typescale-body-large-size);font-weight:var(--mdui-typescale-body-large-weight);letter-spacing:var(--mdui-typescale-body-large-tracking);line-height:var(--mdui-typescale-body-large-line-height);color:rgb(var(--mdui-color-on-surface));caret-color:rgb(var(--mdui-color-primary))}.has-action .input,.has-right-icon .input{padding-right:.25rem}.has-suffix .input{padding-right:0}.input.hide-input{opacity:0;height:0;min-height:0;width:0;padding:0!important;overflow:hidden}.input::placeholder{color:rgb(var(--mdui-color-on-surface-variant))}.invalid .input,.invalid-style .input{caret-color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])) .input{color:rgba(var(--mdui-color-on-surface),38%)}:host([end-aligned]:not([end-aligned=false i])) .input{text-align:right}textarea.input{padding-top:0;margin-top:.875rem}:host([variant=filled]) .label+.input{padding-top:1.375rem;padding-bottom:.375rem}:host([variant=filled]) .label+textarea.input{padding-top:0;margin-top:1.375rem}.supporting{display:flex;justify-content:space-between;padding:.25rem 1rem;color:rgb(var(--mdui-color-on-surface-variant))}.supporting.invalid,.supporting.invalid-style{color:rgb(var(--mdui-color-error))}.helper{display:block;opacity:1;transition:opacity var(--mdui-motion-duration-short4) var(--mdui-motion-easing-linear);font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height)}:host([disabled]:not([disabled=false i])) .helper{color:rgba(var(--mdui-color-on-surface),38%)}:host([helper-on-focus]:not([helper-on-focus=false i])) .helper{opacity:0}:host([helper-on-focus][focused-style]:not([helper-on-focus=false i])) .helper,:host([helper-on-focus][focused]:not([helper-on-focus=false i])) .helper{opacity:1}.error{font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height)}.counter{flex-wrap:nowrap;padding-left:1rem;font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height)}::-ms-reveal{display:none}.input[type=number]::-webkit-inner-spin-button,.input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;display:none}.input[type=number]{-moz-appearance:textfield}.input[type=search]::-webkit-search-cancel-button{-webkit-appearance:none}`;
var TextField = class TextField extends FocusableMixin(MduiElement) {
constructor() {
super(...arguments);
this.variant = "filled";
this.type = "text";
this.name = "";
this.value = "";
this.defaultValue = "";
this.helperOnFocus = false;
this.clearable = false;
this.endAligned = false;
this.readonly = false;
this.disabled = false;
this.required = false;
this.autosize = false;
this.counter = false;
this.togglePassword = false;
this.spellcheck = false;
this.invalid = false;
this.invalidStyle = false;
this.focusedStyle = false;
this.isPasswordVisible = false;
this.hasValue = false;
this.error = "";
this.inputRef = e$1();
this.formController = new FormController(this);
this.hasSlotController = new HasSlotController(this, "icon", "end-icon", "helper", "input");
this.readonlyButClearable = false;
}
get validity() {
return this.inputRef.value.validity;
}
get validationMessage() {
return this.inputRef.value.validationMessage;
}
get valueAsNumber() {
return this.inputRef.value?.valueAsNumber ?? parseFloat(this.value);
}
set valueAsNumber(newValue) {
const input = document.createElement("input");
input.type = "number";
input.valueAsNumber = newValue;
this.value = input.value;
}
get focusElement() {
return this.inputRef.value;
}
get focusDisabled() {
return this.disabled;
}
get isFocusedStyle() {
return this.focused || this.focusedStyle;
}
get isTextarea() {
return this.rows && this.rows > 1 || this.autosize;
}
onDisabledChange() {
this.inputRef.value.disabled = this.disabled;
this.invalid = !this.inputRef.value.checkValidity();
}
async onValueChange() {
this.hasValue = !["", null].includes(this.value);
if (this.hasUpdated) {
await this.updateComplete;
this.setTextareaHeight();
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.inputRef.value.checkValidity();
}
}
onRowsChange() {
this.setTextareaHeight();
}
async onMaxRowsChange() {
if (!this.autosize) return;
if (!this.hasUpdated) await this.updateComplete;
const $input = $$1(this.inputRef.value);
$input.css("max-height", parseFloat($input.css("line-height")) * (this.maxRows ?? 1) + parseFloat($input.css("padding-top")) + parseFloat($input.css("padding-bottom")));
}
async onMinRowsChange() {
if (!this.autosize) return;
if (!this.hasUpdated) await this.updateComplete;
const $input = $$1(this.inputRef.value);
$input.css("min-height", parseFloat($input.css("line-height")) * (this.minRows ?? 1) + parseFloat($input.css("padding-top")) + parseFloat($input.css("padding-bottom")));
}
connectedCallback() {
super.connectedCallback();
this.updateComplete.then(() => {
this.setTextareaHeight();
this.observeResize = observeResize(this.inputRef.value, () => this.setTextareaHeight());
});
}
disconnectedCallback() {
super.disconnectedCallback();
this.observeResize?.unobserve();
offLocaleReady(this);
}
select() {
this.inputRef.value.select();
}
setSelectionRange(start, end, direction = "none") {
this.inputRef.value.setSelectionRange(start, end, direction);
}
setRangeText(replacement, start, end, selectMode = "preserve") {
this.inputRef.value.setRangeText(replacement, start, end, selectMode);
if (this.value !== this.inputRef.value.value) {
this.value = this.inputRef.value.value;
this.setTextareaHeight();
this.emit("input");
this.emit("change");
}
}
checkValidity() {
const valid = this.inputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.inputRef.value.reportValidity();
if (this.invalid) {
this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
this.focus();
}
return !this.invalid;
}
setCustomValidity(message) {
this.setCustomValidityInternal(message);
offLocaleReady(this);
}
render() {
const hasIcon = !!this.icon || this.hasSlotController.test("icon");
const hasEndIcon = !!this.endIcon || this.hasSlotController.test("end-icon");
const hasErrorIcon = this.invalid || this.invalidStyle;
const hasTogglePasswordButton = this.type === "password" && this.togglePassword && !this.disabled;
const hasClearButton = this.clearable && !this.disabled && (!this.readonly || this.readonlyButClearable) && (typeof this.value === "number" || this.value.length > 0);
const hasPrefix = !!this.prefix || this.hasSlotController.test("prefix");
const hasSuffix = !!this.suffix || this.hasSlotController.test("suffix");
const hasHelper = !!this.helper || this.hasSlotController.test("helper");
const hasError = hasErrorIcon && !!(this.error || this.inputRef.value.validationMessage);
const hasCounter = this.counter && !!this.maxlength;
const hasInputSlot = this.hasSlotController.test("input");
const invalidClassNameObj = {
invalid: this.invalid,
"invalid-style": this.invalidStyle
};
return b`
${this.renderPrefix()}
${this.renderLabel()} ${this.isTextarea ? this.renderTextArea(hasInputSlot) : this.renderInput(hasInputSlot)} ${n(hasInputSlot, () => b``)}
${this.renderSuffix()}${this.renderClearButton(hasClearButton)} ${this.renderTogglePasswordButton(hasTogglePasswordButton)} ${this.renderRightIcon(hasErrorIcon)}
${n(hasError || hasHelper || hasCounter, () => b`
${this.renderHelper(hasError, hasHelper)} ${this.renderCounter(hasCounter)}
`)}`;
}
setCustomValidityInternal(message) {
this.inputRef.value.setCustomValidity(message);
this.invalid = !this.inputRef.value.checkValidity();
this.requestUpdate();
}
onChange() {
this.value = this.inputRef.value.value;
if (this.isTextarea) this.setTextareaHeight();
this.emit("change");
}
onClear(event) {
this.value = "";
this.emit("clear");
this.emit("input");
this.emit("change");
this.focus();
event.stopPropagation();
}
onInput(event) {
event.stopPropagation();
this.value = this.inputRef.value.value;
if (this.isTextarea) this.setTextareaHeight();
this.emit("input");
}
onInvalid(event) {
event.preventDefault();
}
onKeyDown(event) {
const hasModifier = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
if (event.key === "Enter" && !hasModifier) setTimeout(() => {
if (!event.defaultPrevented) this.formController.submit();
});
}
onTextAreaKeyUp() {
if (this.pattern) {
const patternRegex = new RegExp(this.pattern);
if (this.value && !this.value.match(patternRegex)) {
this.setCustomValidityInternal(this.getPatternErrorMsg());
onLocaleReady(this, () => {
this.setCustomValidityInternal(this.getPatternErrorMsg());
});
} else {
this.setCustomValidityInternal("");
offLocaleReady(this);
}
}
}
onTogglePassword() {
this.isPasswordVisible = !this.isPasswordVisible;
}
getPatternErrorMsg() {
return msg("Please match the requested format.", { id: "components.textField.patternError" });
}
setTextareaHeight() {
if (this.autosize) {
this.inputRef.value.style.height = "auto";
this.inputRef.value.style.height = `${this.inputRef.value.scrollHeight}px`;
} else this.inputRef.value.style.height = void 0;
}
renderLabel() {
return this.label ? b`
` : nothingTemplate;
}
renderPrefix() {
return b`
${this.icon ? b`` : nothingTemplate}${this.prefix}`;
}
renderSuffix() {
return b`
${this.suffix}`;
}
renderRightIcon(hasErrorIcon) {
return hasErrorIcon ? b`
${this.errorIcon ? b`` : b``}` : b`
${this.endIcon ? b`` : nothingTemplate}`;
}
renderClearButton(hasClearButton) {
return n(hasClearButton, () => b`
${this.clearIcon ? b`` : b``}`);
}
renderTogglePasswordButton(hasTogglePasswordButton) {
return n(hasTogglePasswordButton, () => b`
${this.isPasswordVisible ? b`${this.showPasswordIcon ? b`` : b``}` : b`${this.hidePasswordIcon ? b`` : b``}`}`);
}
renderInput(hasInputSlot) {
return b`
`;
}
renderTextArea(hasInputSlot) {
return b`
`;
}
renderHelper(hasError, hasHelper) {
return hasError ? b`
${this.error || this.inputRef.value.validationMessage}
` : hasHelper ? b`
${this.helper}` : b`
`;
}
renderCounter(hasCounter) {
return hasCounter ? b`
${this.value.length}/${this.maxlength}
` : nothingTemplate;
}
};
TextField.styles = [componentStyle, style$5];
__decorate([n$6({ reflect: true })], TextField.prototype, "variant", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "type", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "name", void 0);
__decorate([n$6()], TextField.prototype, "value", void 0);
__decorate([defaultValue()], TextField.prototype, "defaultValue", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "label", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "placeholder", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "helper", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "helper-on-focus"
})], TextField.prototype, "helperOnFocus", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "clearable", void 0);
__decorate([n$6({
reflect: true,
attribute: "clear-icon"
})], TextField.prototype, "clearIcon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "end-aligned"
})], TextField.prototype, "endAligned", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "prefix", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "suffix", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-icon"
})], TextField.prototype, "endIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "error-icon"
})], TextField.prototype, "errorIcon", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "form", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "readonly", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "required", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "rows", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "autosize", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "min-rows"
})], TextField.prototype, "minRows", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "max-rows"
})], TextField.prototype, "maxRows", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "minlength", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "maxlength", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "counter", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "min", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "max", void 0);
__decorate([n$6({
type: Number,
reflect: true
})], TextField.prototype, "step", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "pattern", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "toggle-password"
})], TextField.prototype, "togglePassword", void 0);
__decorate([n$6({
reflect: true,
attribute: "show-password-icon"
})], TextField.prototype, "showPasswordIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "hide-password-icon"
})], TextField.prototype, "hidePasswordIcon", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "autocapitalize", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "autocorrect", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "autocomplete", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "enterkeyhint", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TextField.prototype, "spellcheck", void 0);
__decorate([n$6({ reflect: true })], TextField.prototype, "inputmode", void 0);
__decorate([r$2()], TextField.prototype, "invalid", void 0);
__decorate([r$2()], TextField.prototype, "invalidStyle", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "focused-style"
})], TextField.prototype, "focusedStyle", void 0);
__decorate([r$2()], TextField.prototype, "isPasswordVisible", void 0);
__decorate([r$2()], TextField.prototype, "hasValue", void 0);
__decorate([r$2()], TextField.prototype, "error", void 0);
__decorate([watch("disabled", true)], TextField.prototype, "onDisabledChange", null);
__decorate([watch("value")], TextField.prototype, "onValueChange", null);
__decorate([watch("rows", true)], TextField.prototype, "onRowsChange", null);
__decorate([watch("maxRows")], TextField.prototype, "onMaxRowsChange", null);
__decorate([watch("minRows")], TextField.prototype, "onMinRowsChange", null);
TextField = __decorate([t$3("mdui-text-field")], TextField);
var style$4 = i$7`:host{display:inline-block;width:100%}.hidden-input{display:none}.text-field{cursor:pointer}.chips{display:flex;flex-wrap:wrap;margin:-.5rem -.25rem;min-height:2.5rem}:host([variant=filled][label]) .chips{margin:0 -.25rem -1rem -.25rem}.chip{margin:.25rem}mdui-menu{max-width:none}`;
var Select = class Select extends FocusableMixin(MduiElement) {
constructor() {
super(...arguments);
this.variant = "filled";
this.multiple = false;
this.name = "";
this.value = "";
this.defaultValue = "";
this.clearable = false;
this.placement = "auto";
this.endAligned = false;
this.readonly = false;
this.disabled = false;
this.required = false;
this.invalid = false;
this.menuRef = e$1();
this.textFieldRef = e$1();
this.hiddenInputRef = e$1();
this.formController = new FormController(this);
this.hasSlotController = new HasSlotController(this, "icon", "end-icon", "error-icon", "prefix", "suffix", "clear-button", "clear-icon", "helper");
this.definedController = new DefinedController(this, { relatedElements: ["mdui-menu-item"] });
}
get validity() {
return this.hiddenInputRef.value.validity;
}
get validationMessage() {
return this.hiddenInputRef.value.validationMessage;
}
get focusElement() {
return this.textFieldRef.value;
}
get focusDisabled() {
return this.disabled;
}
connectedCallback() {
super.connectedCallback();
this.value = this.multiple && isString(this.value) ? this.value ? [this.value] : [] : this.value;
this.defaultValue = this.multiple ? [] : "";
this.definedController.whenDefined().then(() => {
this.requestUpdate();
});
this.updateComplete.then(() => {
this.observeResize = observeResize(this.textFieldRef.value, () => this.resizeMenu());
});
}
disconnectedCallback() {
super.disconnectedCallback();
this.observeResize?.unobserve();
}
checkValidity() {
const valid = this.hiddenInputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.hiddenInputRef.value.reportValidity();
if (this.invalid) {
this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
this.focus();
}
return !this.invalid;
}
setCustomValidity(message) {
this.hiddenInputRef.value.setCustomValidity(message);
this.invalid = !this.hiddenInputRef.value.checkValidity();
}
render() {
const hasSelection = this.multiple ? !!this.value.length : !!this.value;
return b`${this.multiple ? b`
` : b`
`}
`${v}:text-field__${v}`).join(",")}" readonly="readonly" .readonlyButClearable="${true}" .variant="${this.variant}" .name="${this.name}" .value="${this.multiple ? this.value.length ? " " : "" : this.getMenuItemLabelByValue(this.value)}" .label="${this.label}" .placeholder="${this.placeholder}" .helper="${this.helper}" .error="${this.hiddenInputRef.value?.validationMessage}" .clearable="${this.clearable}" .clearIcon="${this.clearIcon}" .endAligned="${this.endAligned}" .prefix="${this.prefix}" .suffix="${this.suffix}" .icon="${this.icon}" .endIcon="${this.endIcon}" .errorIcon="${this.errorIcon}" .form="${this.form}" .disabled="${this.disabled}" .required="${this.required}" .invalidStyle="${this.invalid}" @clear="${this.onClear}" @change="${(e) => e.stopPropagation()}" @keydown="${this.onTextFieldKeyDown}">${o([
"icon",
"end-icon",
"error-icon",
"prefix",
"suffix",
"clear-button",
"clear-icon",
"helper"
], (slotName) => this.hasSlotController.test(slotName) ? b`` : A)} ${n(this.multiple && this.value.length, () => b`${o(this.value, (valueItem) => b` `${v}:chip__${v}`).join(",")}" variant="input" deletable tabindex="-1" @delete="${() => this.onDeleteOneValue(valueItem)}">${this.getMenuItemLabelByValue(valueItem)}`)}
`)}`;
}
getMenuItemLabelByValue(valueItem) {
if (!this.menuItems.length) return valueItem;
return this.menuItems.find((item) => item.value === valueItem)?.textContent?.trim() || valueItem;
}
resizeMenu() {
this.menuRef.value.style.width = `${this.textFieldRef.value.clientWidth}px`;
}
async onDropdownOpen() {
this.textFieldRef.value.focusedStyle = true;
}
onDropdownClose() {
this.textFieldRef.value.focusedStyle = false;
if (this.contains(document.activeElement) || this.contains(document.activeElement?.assignedSlot ?? null)) setTimeout(() => {
this.focus();
});
}
async onValueChange(e) {
const menu = e.target;
this.value = this.multiple ? menu.value.map((v) => v ?? "") : menu.value ?? "";
await this.updateComplete;
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.hiddenInputRef.value.checkValidity();
}
onDeleteOneValue(valueItem) {
const value = [...this.value];
if (value.includes(valueItem)) value.splice(value.indexOf(valueItem), 1);
this.value = value;
}
onClear() {
this.value = this.multiple ? [] : "";
}
onTextFieldKeyDown(event) {
if (event.key === "Enter") {
event.preventDefault();
this.textFieldRef.value.click();
}
}
};
Select.styles = [componentStyle, style$4];
__decorate([n$6({ reflect: true })], Select.prototype, "variant", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Select.prototype, "multiple", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "name", void 0);
__decorate([n$6()], Select.prototype, "value", void 0);
__decorate([defaultValue()], Select.prototype, "defaultValue", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "label", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "placeholder", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "helper", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Select.prototype, "clearable", void 0);
__decorate([n$6({
reflect: true,
attribute: "clear-icon"
})], Select.prototype, "clearIcon", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "placement", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "end-aligned"
})], Select.prototype, "endAligned", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "prefix", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "suffix", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "icon", void 0);
__decorate([n$6({
reflect: true,
attribute: "end-icon"
})], Select.prototype, "endIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "error-icon"
})], Select.prototype, "errorIcon", void 0);
__decorate([n$6({ reflect: true })], Select.prototype, "form", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Select.prototype, "readonly", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Select.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Select.prototype, "required", void 0);
__decorate([r$2()], Select.prototype, "invalid", void 0);
__decorate([o$7({
flatten: true,
selector: "mdui-menu-item"
})], Select.prototype, "menuItems", void 0);
Select = __decorate([t$3("mdui-select")], Select);
var style$3 = i$7`.track-active{left:-.125rem;border-radius:var(--mdui-shape-corner-full) 0 0 var(--mdui-shape-corner-full)}`;
var Slider = class Slider extends SliderBase {
constructor() {
super(...arguments);
this.value = 0;
this.defaultValue = 0;
this.rippleRef = e$1();
this.handleRef = e$1();
this.formController = new FormController(this);
}
get rippleElement() {
return this.rippleRef.value;
}
async onValueChange() {
this.value = this.fixValue(this.value);
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else {
await this.updateComplete;
this.invalid = !this.inputRef.value.checkValidity();
}
this.updateStyle();
}
connectedCallback() {
super.connectedCallback();
this.value = this.fixValue(this.value);
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
const onTouchStart = () => {
if (!this.disabled) this.labelVisible = true;
};
const onTouchEnd = () => {
if (!this.disabled) this.labelVisible = false;
};
this.addEventListener("touchstart", onTouchStart);
this.addEventListener("mousedown", onTouchStart);
this.addEventListener("touchend", onTouchEnd);
this.addEventListener("mouseup", onTouchEnd);
this.updateStyle();
}
render() {
return b`
`;
}
updateStyle() {
const percent = (this.value - this.min) / (this.max - this.min) * 100;
this.trackActiveRef.value.style.width = `${percent}%`;
this.handleRef.value.style.left = `${percent}%`;
}
onInput() {
this.value = parseFloat(this.inputRef.value.value);
this.updateStyle();
}
};
Slider.styles = [SliderBase.styles, style$3];
__decorate([n$6({ type: Number })], Slider.prototype, "value", void 0);
__decorate([defaultValue()], Slider.prototype, "defaultValue", void 0);
__decorate([watch("value", true)], Slider.prototype, "onValueChange", null);
Slider = __decorate([t$3("mdui-slider")], Slider);
var style$2 = i$7`:host{--shape-corner:var(--mdui-shape-corner-extra-small);--z-index:2400;position:fixed;z-index:var(--z-index);display:none;align-items:center;flex-wrap:wrap;border-radius:var(--shape-corner);transform:scaleY(0);transition:transform 0s var(--mdui-motion-easing-linear) var(--mdui-motion-duration-short4);min-width:20rem;max-width:36rem;padding:.25rem 0;box-shadow:var(--mdui-elevation-level3);background-color:rgb(var(--mdui-color-inverse-surface));color:rgb(var(--mdui-color-inverse-on-surface));font-size:var(--mdui-typescale-body-medium-size);font-weight:var(--mdui-typescale-body-medium-weight);letter-spacing:var(--mdui-typescale-body-medium-tracking);line-height:var(--mdui-typescale-body-medium-line-height)}:host([placement^=top]){transform-origin:top}:host([placement^=bottom]){transform-origin:bottom}:host([placement=bottom-start]:not([mobile])),:host([placement=top-start]:not([mobile])){left:1rem}:host([placement=bottom-end]:not([mobile])),:host([placement=top-end]:not([mobile])){right:1rem}:host([placement=bottom]:not([mobile])),:host([placement=top]:not([mobile])){left:50%;transform:scaleY(0) translateX(-50%)}:host([mobile]){min-width:0;left:1rem;right:1rem}:host([open]){transform:scaleY(1);transition:top var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard),bottom var(--mdui-motion-duration-short4) var(--mdui-motion-easing-standard),transform var(--mdui-motion-duration-medium4) var(--mdui-motion-easing-emphasized-decelerate)}:host([placement=bottom][open]:not([mobile])),:host([placement=top][open]:not([mobile])){transform:scaleY(1) translateX(-50%)}.message{display:block;margin:.625rem 1rem}:host([message-line='1']) .message{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}:host([message-line='2']) .message{display:-webkit-box;overflow:hidden;text-overflow:ellipsis;-webkit-box-orient:vertical;-webkit-line-clamp:2}.action-group{display:flex;align-items:center;margin-left:auto;padding-right:.5rem}.action,.close-button{display:inline-flex;align-items:center;justify-content:center}.action{color:rgb(var(--mdui-color-inverse-primary));font-size:var(--mdui-typescale-label-large-size);font-weight:var(--mdui-typescale-label-large-weight);letter-spacing:var(--mdui-typescale-label-large-tracking)}.action mdui-button,::slotted(mdui-button[slot=action][variant=outlined]),::slotted(mdui-button[slot=action][variant=text]){color:inherit;font-size:inherit;font-weight:inherit;letter-spacing:inherit;--mdui-comp-ripple-state-layer-color:var(--mdui-color-inverse-primary)}.action mdui-button::part(button){padding:0 .5rem}.close-button{margin:0 -.25rem 0 .25rem;font-size:1.5rem;color:rgb(var(--mdui-color-inverse-on-surface))}.close-button mdui-button-icon,::slotted(mdui-button-icon[slot=close-button][variant=outlined]),::slotted(mdui-button-icon[slot=close-button][variant=standard]){font-size:inherit;color:inherit;--mdui-comp-ripple-state-layer-color:var(--mdui-color-inverse-on-surface)}.close-button .i,::slotted([slot=close-icon]){font-size:inherit}`;
var stacks = [];
var reordering = false;
var Snackbar = class Snackbar extends MduiElement {
constructor() {
super();
this.open = false;
this.placement = "bottom";
this.actionLoading = false;
this.closeable = false;
this.autoCloseDelay = 5e3;
this.closeOnOutsideClick = false;
this.mobile = false;
this.onDocumentClick = this.onDocumentClick.bind(this);
}
async onOpenChange() {
const easingLinear = getEasing(this, "linear");
const children = Array.from(this.renderRoot.querySelectorAll(".message, .action-group"));
if (this.open) {
const hasUpdated = this.hasUpdated;
if (!hasUpdated) await this.updateComplete;
if (hasUpdated) {
if (!this.emit("open", { cancelable: true })) return;
}
window.clearTimeout(this.closeTimeout);
if (this.autoCloseDelay) this.closeTimeout = window.setTimeout(() => {
this.open = false;
}, this.autoCloseDelay);
this.style.display = "flex";
await Promise.all([stopAnimations(this), ...children.map((child) => stopAnimations(child))]);
stacks.push({
height: this.clientHeight,
snackbar: this
});
await this.reorderStack(this);
const duration = getDuration(this, "medium4");
await Promise.all([animateTo(this, [
{ opacity: 0 },
{
opacity: 1,
offset: .5
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear,
fill: "forwards"
}), ...children.map((child) => animateTo(child, [
{ opacity: 0 },
{
opacity: 0,
offset: .2
},
{
opacity: 1,
offset: .8
},
{ opacity: 1 }
], {
duration: hasUpdated ? duration : 0,
easing: easingLinear
}))]);
if (hasUpdated) this.emit("opened");
return;
}
if (!this.open && this.hasUpdated) {
if (!this.emit("close", { cancelable: true })) return;
window.clearTimeout(this.closeTimeout);
await Promise.all([stopAnimations(this), ...children.map((child) => stopAnimations(child))]);
const duration = getDuration(this, "short4");
await Promise.all([animateTo(this, [{ opacity: 1 }, { opacity: 0 }], {
duration,
easing: easingLinear,
fill: "forwards"
}), ...children.map((child) => animateTo(child, [
{ opacity: 1 },
{
opacity: 0,
offset: .75
},
{ opacity: 0 }
], {
duration,
easing: easingLinear
}))]);
this.style.display = "none";
this.emit("closed");
const stackIndex = stacks.findIndex((stack) => stack.snackbar === this);
stacks.splice(stackIndex, 1);
if (stacks[stackIndex]) await this.reorderStack(stacks[stackIndex].snackbar);
return;
}
}
async onStackChange() {
await this.reorderStack(this);
}
connectedCallback() {
super.connectedCallback();
document.addEventListener("pointerdown", this.onDocumentClick);
this.mobile = breakpoint().down("sm");
this.observeResize = observeResize(document.documentElement, async () => {
const mobile = breakpoint().down("sm");
if (this.mobile !== mobile) {
this.mobile = mobile;
if (!reordering) {
reordering = true;
await this.reorderStack();
reordering = false;
}
}
});
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("pointerdown", this.onDocumentClick);
window.clearTimeout(this.closeTimeout);
if (this.open) this.open = false;
this.observeResize?.unobserve();
}
render() {
return b`
${this.action ? b`${this.action}` : nothingTemplate}${n(this.closeable, () => b`${this.closeIcon ? b`` : b``}`)}
`;
}
async reorderStack(startSnackbar) {
const stackIndex = startSnackbar ? stacks.findIndex((stack) => stack.snackbar === startSnackbar) : 0;
for (let i = stackIndex; i < stacks.length; i++) {
const snackbar = stacks[i].snackbar;
if (this.mobile) ["top", "bottom"].forEach((placement) => {
if (snackbar.placement.startsWith(placement)) {
const prevStacks = stacks.filter((stack, index) => {
return index < i && stack.snackbar.placement.startsWith(placement);
});
const prevHeight = prevStacks.reduce((prev, current) => prev + current.height, 0);
snackbar.style[placement] = `calc(${prevHeight}px + ${prevStacks.length + 1}rem)`;
snackbar.style[placement === "top" ? "bottom" : "top"] = "auto";
}
});
else [
"top",
"top-start",
"top-end",
"bottom",
"bottom-start",
"bottom-end"
].forEach((placement) => {
if (snackbar.placement === placement) {
const prevStacks = stacks.filter((stack, index) => {
return index < i && stack.snackbar.placement === placement;
});
const prevHeight = prevStacks.reduce((prev, current) => prev + current.height, 0);
snackbar.style[placement.startsWith("top") ? "top" : "bottom"] = `calc(${prevHeight}px + ${prevStacks.length + 1}rem)`;
snackbar.style[placement.startsWith("top") ? "bottom" : "top"] = "auto";
}
});
}
}
onDocumentClick(e) {
if (!this.open || !this.closeOnOutsideClick) return;
const target = e.target;
if (!this.contains(target) && this !== target) this.open = false;
}
onActionClick(event) {
event.stopPropagation();
this.emit("action-click");
}
onCloseClick() {
this.open = false;
}
};
Snackbar.styles = [componentStyle, style$2];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Snackbar.prototype, "open", void 0);
__decorate([n$6({ reflect: true })], Snackbar.prototype, "placement", void 0);
__decorate([n$6({
reflect: true,
attribute: "action"
})], Snackbar.prototype, "action", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "action-loading"
})], Snackbar.prototype, "actionLoading", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Snackbar.prototype, "closeable", void 0);
__decorate([n$6({
reflect: true,
attribute: "close-icon"
})], Snackbar.prototype, "closeIcon", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "message-line"
})], Snackbar.prototype, "messageLine", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "auto-close-delay"
})], Snackbar.prototype, "autoCloseDelay", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
attribute: "close-on-outside-click",
converter: booleanConverter
})], Snackbar.prototype, "closeOnOutsideClick", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Snackbar.prototype, "mobile", void 0);
__decorate([watch("open")], Snackbar.prototype, "onOpenChange", null);
__decorate([watch("placement", true), watch("messageLine", true)], Snackbar.prototype, "onStackChange", null);
Snackbar = __decorate([t$3("mdui-snackbar")], Snackbar);
var style$1 = i$7`:host{--shape-corner:var(--mdui-shape-corner-full);--shape-corner-thumb:var(--mdui-shape-corner-full);position:relative;display:inline-block;cursor:pointer;-webkit-tap-highlight-color:transparent;height:2.5rem}:host([disabled]:not([disabled=false i])){cursor:default;pointer-events:none}label{display:inline-flex;align-items:center;width:100%;height:100%;white-space:nowrap;cursor:inherit;-webkit-user-select:none;user-select:none;touch-action:manipulation;zoom:1;-webkit-user-drag:none}.track{position:relative;display:flex;align-items:center;border-radius:var(--shape-corner);transition-property:background-color,border-width;transition-duration:var(--mdui-motion-duration-short4);transition-timing-function:var(--mdui-motion-easing-standard);height:2rem;width:3.25rem;border:.125rem solid rgb(var(--mdui-color-outline));background-color:rgb(var(--mdui-color-surface-container-highest))}:host([checked]:not([checked=false i])) .track{background-color:rgb(var(--mdui-color-primary));border-width:0}.invalid .track{background-color:rgb(var(--mdui-color-error-container));border-color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])) .track{background-color:rgba(var(--mdui-color-surface-container-highest),.12);border-color:rgba(var(--mdui-color-on-surface),.12)}:host([disabled][checked]:not([disabled=false i],[checked=false i])) .track{background-color:rgba(var(--mdui-color-on-surface),.12)}input{position:absolute;padding:0;opacity:0;pointer-events:none;width:1.25rem;height:1.25rem;margin:0 0 0 .625rem}mdui-ripple{border-radius:50%;transition-property:left,top;transition-duration:var(--mdui-motion-duration-short4);transition-timing-function:var(--mdui-motion-easing-standard);width:2.5rem;height:2.5rem}.thumb{position:absolute;display:flex;align-items:center;justify-content:center;border-radius:var(--shape-corner-thumb);transition-property:width,height,left,background-color;transition-duration:var(--mdui-motion-duration-short4);transition-timing-function:var(--mdui-motion-easing-standard);height:1rem;width:1rem;left:.375rem;background-color:rgb(var(--mdui-color-outline));--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}.thumb mdui-ripple{left:-.75rem;top:-.75rem}.has-unchecked-icon .thumb{height:1.5rem;width:1.5rem;left:.125rem}.has-unchecked-icon .thumb mdui-ripple{left:-.5rem;top:-.5rem}:host([focus-visible]) .thumb,:host([hover]) .thumb,:host([pressed]) .thumb{background-color:rgb(var(--mdui-color-on-surface-variant))}:host([checked]:not([checked=false i])) .thumb{height:1.5rem;width:1.5rem;left:1.5rem;background-color:rgb(var(--mdui-color-on-primary));--mdui-comp-ripple-state-layer-color:var(--mdui-color-primary)}:host([checked]:not([checked=false i])) .thumb mdui-ripple{left:-.5rem;top:-.5rem}:host([pressed]) .thumb{height:1.75rem;width:1.75rem;left:0}:host([pressed]) .thumb mdui-ripple{left:-.375rem;top:-.375rem}:host([pressed][checked]:not([checked=false i])) .thumb{left:1.375rem}:host([focus-visible][checked]:not([checked=false i])) .thumb,:host([hover][checked]:not([checked=false i])) .thumb,:host([pressed][checked]:not([checked=false i])) .thumb{background-color:rgb(var(--mdui-color-primary-container))}.invalid .thumb{background-color:rgb(var(--mdui-color-error));--mdui-comp-ripple-state-layer-color:var(--mdui-color-error)}:host([focus-visible]) .invalid .thumb,:host([hover]) .invalid .thumb,:host([pressed]) .invalid .thumb{background-color:rgb(var(--mdui-color-error))}:host([disabled]:not([disabled=false i])) .thumb{background-color:rgba(var(--mdui-color-on-surface),.38)}:host([disabled][checked]:not([disabled=false i],[checked=false i])) .thumb{background-color:rgb(var(--mdui-color-surface))}.checked-icon,.unchecked-icon{display:flex;position:absolute;transition-property:opacity,transform;font-size:1rem}.unchecked-icon{opacity:1;transform:scale(1);transition-delay:var(--mdui-motion-duration-short1);transition-duration:var(--mdui-motion-duration-short3);transition-timing-function:var(--mdui-motion-easing-linear);color:rgb(var(--mdui-color-surface-container-highest))}:host([checked]:not([checked=false i])) .unchecked-icon{opacity:0;transform:scale(.92);transition-delay:0s;transition-duration:var(--mdui-motion-duration-short1)}:host([disabled]:not([disabled=false i])) .unchecked-icon{color:rgba(var(--mdui-color-surface-container-highest),.38)}.checked-icon{opacity:0;transform:scale(.92);transition-delay:0s;transition-duration:var(--mdui-motion-duration-short1);transition-timing-function:var(--mdui-motion-easing-linear);color:rgb(var(--mdui-color-on-primary-container))}:host([checked]:not([checked=false i])) .checked-icon{opacity:1;transform:scale(1);transition-delay:var(--mdui-motion-duration-short1);transition-duration:var(--mdui-motion-duration-short3)}.invalid .checked-icon{color:rgb(var(--mdui-color-error-container))}:host([disabled]:not([disabled=false i])) .checked-icon{color:rgba(var(--mdui-color-on-surface),.38)}.checked-icon .i,.unchecked-icon .i,::slotted([slot=checked-icon]),::slotted([slot=unchecked-icon]){font-size:inherit;color:inherit}`;
var Switch = class Switch extends RippleMixin(FocusableMixin(MduiElement)) {
constructor() {
super(...arguments);
this.disabled = false;
this.checked = false;
this.defaultChecked = false;
this.required = false;
this.name = "";
this.value = "on";
this.invalid = false;
this.rippleRef = e$1();
this.inputRef = e$1();
this.formController = new FormController(this, {
value: (control) => control.checked ? control.value : void 0,
defaultValue: (control) => control.defaultChecked,
setValue: (control, checked) => control.checked = checked
});
this.hasSlotController = new HasSlotController(this, "unchecked-icon");
}
get validity() {
return this.inputRef.value.validity;
}
get validationMessage() {
return this.inputRef.value.validationMessage;
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return this.disabled;
}
get focusElement() {
return this.inputRef.value;
}
get focusDisabled() {
return this.disabled;
}
async onDisabledChange() {
await this.updateComplete;
this.invalid = !this.inputRef.value.checkValidity();
}
async onCheckedChange() {
await this.updateComplete;
const form = this.formController.getForm();
if (form && formResets.get(form)?.has(this)) {
this.invalid = false;
formResets.get(form).delete(this);
} else this.invalid = !this.inputRef.value.checkValidity();
}
checkValidity() {
const valid = this.inputRef.value.checkValidity();
if (!valid) this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
});
return valid;
}
reportValidity() {
this.invalid = !this.inputRef.value.reportValidity();
if (this.invalid) {
if (!this.emit("invalid", {
bubbles: false,
cancelable: true,
composed: false
})) {
this.blur();
this.focus();
}
}
return !this.invalid;
}
setCustomValidity(message) {
this.inputRef.value.setCustomValidity(message);
this.invalid = !this.inputRef.value.checkValidity();
}
render() {
return b`
`;
}
onChange() {
this.checked = this.inputRef.value.checked;
this.emit("change");
}
};
Switch.styles = [componentStyle, style$1];
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Switch.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Switch.prototype, "checked", void 0);
__decorate([defaultValue("checked")], Switch.prototype, "defaultChecked", void 0);
__decorate([n$6({
reflect: true,
attribute: "unchecked-icon"
})], Switch.prototype, "uncheckedIcon", void 0);
__decorate([n$6({
reflect: true,
attribute: "checked-icon"
})], Switch.prototype, "checkedIcon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Switch.prototype, "required", void 0);
__decorate([n$6({ reflect: true })], Switch.prototype, "form", void 0);
__decorate([n$6({ reflect: true })], Switch.prototype, "name", void 0);
__decorate([n$6({ reflect: true })], Switch.prototype, "value", void 0);
__decorate([r$2()], Switch.prototype, "invalid", void 0);
__decorate([watch("disabled", true), watch("required", true)], Switch.prototype, "onDisabledChange", null);
__decorate([watch("checked", true)], Switch.prototype, "onCheckedChange", null);
Switch = __decorate([t$3("mdui-switch")], Switch);
var tabStyle = i$7`:host{position:relative;--mdui-comp-ripple-state-layer-color:var(--mdui-color-on-surface)}:host([active]){--mdui-comp-ripple-state-layer-color:var(--mdui-color-primary)}.container{display:flex;justify-content:center;align-items:center;cursor:pointer;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;height:100%}.preset{flex-direction:column;min-height:3rem;padding:.625rem 1rem}:host([inline]:not([inline=false i])) .preset{flex-direction:row}.icon-container,.label-container{position:relative;display:flex;align-items:center;justify-content:center}.icon-container ::slotted([slot=badge]){position:absolute;transform:translate(50%,-50%)}.icon-container ::slotted([slot=badge][variant=small]){transform:translate(.5625rem,-.5625rem)}.label-container ::slotted([slot=badge]){position:absolute;left:100%;bottom:100%;transform:translate(-.75rem,.625rem)}.label-container ::slotted([slot=badge][variant=small]){transform:translate(-.375rem,.375rem)}.icon,.label{display:flex;color:rgb(var(--mdui-color-on-surface-variant))}:host([focused]) .icon,:host([focused]) .label,:host([hover]) .icon,:host([hover]) .label,:host([pressed]) .icon,:host([pressed]) .label{color:rgb(var(--mdui-color-on-surface))}:host([active]) .icon,:host([active]) .label{color:rgb(var(--mdui-color-primary))}:host([active]) .variant-secondary .icon,:host([active]) .variant-secondary .label{color:rgb(var(--mdui-color-on-surface))}.icon{font-size:1.5rem}.label{font-size:var(--mdui-typescale-title-small-size);font-weight:var(--mdui-typescale-title-small-weight);letter-spacing:var(--mdui-typescale-title-small-tracking);line-height:var(--mdui-typescale-title-small-line-height)}.icon mdui-icon,::slotted([slot=icon]){font-size:inherit;color:inherit}`;
var Tab = class Tab extends RippleMixin(FocusableMixin(MduiElement)) {
constructor() {
super(...arguments);
this.inline = false;
this.active = false;
this.variant = "primary";
this.key = uniqueId();
this.rippleRef = e$1();
this.hasSlotController = new HasSlotController(this, "icon", "custom");
}
get rippleElement() {
return this.rippleRef.value;
}
get rippleDisabled() {
return false;
}
get focusElement() {
return this;
}
get focusDisabled() {
return false;
}
render() {
const hasIcon = this.icon || this.hasSlotController.test("icon");
const hasCustomSlot = this.hasSlotController.test("custom");
const renderBadge = () => b`
`;
return b`
${n(hasIcon || this.icon, renderBadge)}${this.icon ? b`` : nothingTemplate}
${n(!hasIcon, renderBadge)}
`;
}
};
Tab.styles = [componentStyle, tabStyle];
__decorate([n$6({ reflect: true })], Tab.prototype, "value", void 0);
__decorate([n$6({ reflect: true })], Tab.prototype, "icon", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Tab.prototype, "inline", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Tab.prototype, "active", void 0);
__decorate([r$2()], Tab.prototype, "variant", void 0);
Tab = __decorate([t$3("mdui-tab")], Tab);
var tabPanelStyle = i$7`:host{display:block;overflow-y:auto;flex:1 1 auto}:host(:not([active])){display:none}`;
var TabPanel = class TabPanel extends MduiElement {
constructor() {
super(...arguments);
this.active = false;
}
render() {
return b`
`;
}
};
TabPanel.styles = [componentStyle, tabPanelStyle];
__decorate([n$6({ reflect: true })], TabPanel.prototype, "value", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TabPanel.prototype, "active", void 0);
TabPanel = __decorate([t$3("mdui-tab-panel")], TabPanel);
var tabsStyle = i$7`:host{position:relative;display:flex}:host([placement^=top]){flex-direction:column}:host([placement^=bottom]){flex-direction:column-reverse}:host([placement^=left]){flex-direction:row}:host([placement^=right]){flex-direction:row-reverse}.container{position:relative;display:flex;flex:0 0 auto;overflow-x:auto;background-color:rgb(var(--mdui-color-surface))}:host([placement^=bottom]) .container,:host([placement^=top]) .container{flex-direction:row}:host([placement^=left]) .container,:host([placement^=right]) .container{flex-direction:column}:host([placement$='-start']) .container{justify-content:flex-start}:host([placement=bottom]) .container,:host([placement=left]) .container,:host([placement=right]) .container,:host([placement=top]) .container{justify-content:center}:host([placement$='-end']) .container{justify-content:flex-end}.container::after{content:' ';position:absolute;background-color:rgb(var(--mdui-color-surface-variant))}:host([placement^=bottom]) .container::after,:host([placement^=top]) .container::after{left:0;width:100%;height:.0625rem}:host([placement^=top]) .container::after{bottom:0}:host([placement^=bottom]) .container::after{top:0}:host([placement^=left]) .container::after,:host([placement^=right]) .container::after{top:0;height:100%;width:.0625rem}:host([placement^=left]) .container::after{right:0}:host([placement^=right]) .container::after{left:0}.indicator{position:absolute;z-index:1;background-color:rgb(var(--mdui-color-primary))}.container:not(.initial) .indicator{transition-duration:var(--mdui-motion-duration-medium2);transition-timing-function:var(--mdui-motion-easing-standard-decelerate)}:host([placement^=bottom]) .indicator,:host([placement^=top]) .indicator{transition-property:transform,left,width}:host([placement^=left]) .indicator,:host([placement^=right]) .indicator{transition-property:transform,top,height}:host([placement^=top]) .indicator{bottom:0}:host([placement^=bottom]) .indicator{top:0}:host([placement^=left]) .indicator{right:0}:host([placement^=right]) .indicator{left:0}:host([placement^=bottom][variant=primary]) .indicator,:host([placement^=top][variant=primary]) .indicator{height:.1875rem}:host([placement^=bottom][variant=secondary]) .indicator,:host([placement^=top][variant=secondary]) .indicator{height:.125rem}:host([placement^=left][variant=primary]) .indicator,:host([placement^=right][variant=primary]) .indicator{width:.1875rem}:host([placement^=left][variant=secondary]) .indicator,:host([placement^=right][variant=secondary]) .indicator{width:.125rem}:host([placement^=top][variant=primary]) .indicator{border-top-left-radius:.1875rem;border-top-right-radius:.1875rem}:host([placement^=bottom][variant=primary]) .indicator{border-bottom-right-radius:.1875rem;border-bottom-left-radius:.1875rem}:host([placement^=left][variant=primary]) .indicator{border-top-left-radius:.1875rem;border-bottom-left-radius:.1875rem}:host([placement^=right][variant=primary]) .indicator{border-top-right-radius:.1875rem;border-bottom-right-radius:.1875rem}:host([full-width]:not([full-width=false i])) ::slotted(mdui-tab){flex:1}`;
var Tabs = class Tabs extends MduiElement {
constructor() {
super(...arguments);
this.variant = "primary";
this.placement = "top-start";
this.fullWidth = false;
this.activeKey = 0;
this.isInitial = true;
this.containerRef = e$1();
this.indicatorRef = e$1();
this.definedController = new DefinedController(this, { relatedElements: ["mdui-tab", "mdui-tab-panel"] });
}
async onActiveKeyChange() {
await this.definedController.whenDefined();
this.value = this.tabs.find((tab) => tab.key === this.activeKey)?.value;
this.updateActive();
if (!this.isInitial) this.emit("change");
}
async onValueChange() {
this.isInitial = !this.hasUpdated;
await this.definedController.whenDefined();
this.activeKey = this.tabs.find((tab) => tab.value === this.value)?.key ?? 0;
}
async onIndicatorChange() {
await this.updateComplete;
this.updateIndicator();
}
connectedCallback() {
super.connectedCallback();
this.updateComplete.then(() => {
this.observeResize = observeResize(this.containerRef.value, () => this.updateIndicator());
});
}
disconnectedCallback() {
super.disconnectedCallback();
this.observeResize?.unobserve();
}
render() {
return b`
`;
}
async onSlotChange() {
await this.definedController.whenDefined();
this.updateActive();
}
async onClick(event) {
if (event.button) return;
await this.definedController.whenDefined();
const tab = event.target.closest("mdui-tab");
if (!tab) return;
this.activeKey = tab.key;
this.isInitial = false;
this.updateActive();
}
updateActive() {
this.activeTab = this.tabs.map((tab) => {
tab.active = this.activeKey === tab.key;
return tab;
}).find((tab) => tab.active);
this.panels.forEach((panel) => panel.active = panel.value === this.activeTab?.value);
this.updateIndicator();
}
updateIndicator() {
const activeTab = this.activeTab;
const $indicator = $$1(this.indicatorRef.value);
const isVertical = this.placement.startsWith("left") || this.placement.startsWith("right");
if (!activeTab) {
$indicator.css({ transform: isVertical ? "scaleY(0)" : "scaleX(0)" });
return;
}
const $activeTab = $$1(activeTab);
const offsetTop = activeTab.offsetTop;
const offsetLeft = activeTab.offsetLeft;
const commonStyle = isVertical ? {
transform: "scaleY(1)",
width: "",
left: ""
} : {
transform: "scaleX(1)",
height: "",
top: ""
};
let shownStyle = {};
if (this.variant === "primary") {
const $customSlots = $activeTab.find(":scope > [slot=\"custom\"]");
const children = $customSlots.length ? $customSlots.get() : $$1(activeTab.renderRoot).find("slot[name=\"custom\"]").children().get();
if (isVertical) {
const top = Math.min(...children.map((child) => child.offsetTop)) + offsetTop;
shownStyle = {
top,
height: Math.max(...children.map((child) => child.offsetTop + child.offsetHeight)) + offsetTop - top
};
} else {
const left = Math.min(...children.map((child) => child.offsetLeft)) + offsetLeft;
shownStyle = {
left,
width: Math.max(...children.map((child) => child.offsetLeft + child.offsetWidth)) + offsetLeft - left
};
}
}
if (this.variant === "secondary") shownStyle = isVertical ? {
top: offsetTop,
height: activeTab.offsetHeight
} : {
left: offsetLeft,
width: activeTab.offsetWidth
};
$indicator.css({
...commonStyle,
...shownStyle
});
}
};
Tabs.styles = [componentStyle, tabsStyle];
__decorate([n$6({ reflect: true })], Tabs.prototype, "variant", void 0);
__decorate([n$6({ reflect: true })], Tabs.prototype, "value", void 0);
__decorate([n$6({ reflect: true })], Tabs.prototype, "placement", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter,
attribute: "full-width"
})], Tabs.prototype, "fullWidth", void 0);
__decorate([r$2()], Tabs.prototype, "activeKey", void 0);
__decorate([r$2()], Tabs.prototype, "isInitial", void 0);
__decorate([o$7({
selector: "mdui-tab",
flatten: true
})], Tabs.prototype, "tabs", void 0);
__decorate([o$7({
selector: "mdui-tab-panel",
slot: "panel",
flatten: true
})], Tabs.prototype, "panels", void 0);
__decorate([watch("activeKey", true)], Tabs.prototype, "onActiveKeyChange", null);
__decorate([watch("value")], Tabs.prototype, "onValueChange", null);
__decorate([
watch("variant", true),
watch("placement", true),
watch("fullWidth", true)
], Tabs.prototype, "onIndicatorChange", null);
Tabs = __decorate([t$3("mdui-tabs")], Tabs);
var HoverController = class {
constructor(host, elementRef) {
this.isHover = false;
this.uniqueID = uniqueId();
this.enterEventName = `mouseenter.${this.uniqueID}.hoverController`;
this.leaveEventName = `mouseleave.${this.uniqueID}.hoverController`;
this.mouseEnterItems = [];
this.mouseLeaveItems = [];
(this.host = host).addController(this);
this.elementRef = elementRef;
}
hostConnected() {
this.host.updateComplete.then(() => {
$$1(this.elementRef.value).on(this.enterEventName, () => {
this.isHover = true;
for (let i = this.mouseEnterItems.length - 1; i >= 0; i--) {
const item = this.mouseEnterItems[i];
item.callback();
if (item.one) this.mouseEnterItems.splice(i, 1);
}
}).on(this.leaveEventName, () => {
this.isHover = false;
for (let i = this.mouseLeaveItems.length - 1; i >= 0; i--) {
const item = this.mouseLeaveItems[i];
item.callback();
if (item.one) this.mouseLeaveItems.splice(i, 1);
}
});
});
}
hostDisconnected() {
$$1(this.elementRef.value).off(this.enterEventName).off(this.leaveEventName);
}
onMouseEnter(callback, one = false) {
this.mouseEnterItems.push({
callback,
one
});
}
onMouseLeave(callback, one = false) {
this.mouseLeaveItems.push({
callback,
one
});
}
};
var style = i$7`:host{--shape-corner-plain:var(--mdui-shape-corner-extra-small);--shape-corner-rich:var(--mdui-shape-corner-medium);--z-index:2500;display:contents}.popup{position:fixed;display:flex;flex-direction:column;z-index:var(--z-index);border-radius:var(--shape-corner-plain);background-color:rgb(var(--mdui-color-inverse-surface));padding:0 .5rem;min-width:1.75rem;max-width:20rem}:host([variant=rich]) .popup{border-radius:var(--shape-corner-rich);background-color:rgb(var(--mdui-color-surface-container));box-shadow:var(--mdui-elevation-level2);padding:.75rem 1rem .5rem 1rem}.headline{display:flex;color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-title-small-size);font-weight:var(--mdui-typescale-title-small-weight);letter-spacing:var(--mdui-typescale-title-small-tracking);line-height:var(--mdui-typescale-title-small-line-height)}.content{display:flex;padding:.25rem 0;color:rgb(var(--mdui-color-inverse-on-surface));font-size:var(--mdui-typescale-body-small-size);font-weight:var(--mdui-typescale-body-small-weight);letter-spacing:var(--mdui-typescale-body-small-tracking);line-height:var(--mdui-typescale-body-small-line-height)}:host([variant=rich]) .content{color:rgb(var(--mdui-color-on-surface-variant));font-size:var(--mdui-typescale-body-medium-size);font-weight:var(--mdui-typescale-body-medium-weight);letter-spacing:var(--mdui-typescale-body-medium-tracking);line-height:var(--mdui-typescale-body-medium-line-height)}.action{display:flex;justify-content:flex-start;padding-top:.5rem}.action ::slotted(:not(:last-child)){margin-right:.5rem}`;
var Tooltip = class Tooltip extends MduiElement {
constructor() {
super();
this.variant = "plain";
this.placement = "auto";
this.openDelay = 150;
this.closeDelay = 150;
this.trigger = "hover focus";
this.disabled = false;
this.open = false;
this.popupRef = e$1();
this.hasSlotController = new HasSlotController(this, "headline", "action");
this.hoverController = new HoverController(this, this.popupRef);
this.definedController = new DefinedController(this, { needDomReady: true });
this.onDocumentClick = this.onDocumentClick.bind(this);
this.onWindowScroll = this.onWindowScroll.bind(this);
this.onFocus = this.onFocus.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onClick = this.onClick.bind(this);
this.onKeydown = this.onKeydown.bind(this);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
}
get target() {
return [...this.children].find((el) => el.tagName.toLowerCase() !== "style" && el.getAttribute("slot") !== "content");
}
async onPositionChange() {
if (this.open) {
await this.definedController.whenDefined();
this.updatePositioner();
}
}
async onOpenChange() {
const hasUpdated = this.hasUpdated;
const duration = getDuration(this, "short4");
const easing = getEasing(this, "standard");
if (this.open) {
await this.definedController.whenDefined();
$$1(`mdui-tooltip[variant="${this.variant}"]`).filter((_, element) => element !== this).prop("open", false);
if (!hasUpdated) await this.updateComplete;
if (hasUpdated) {
if (!this.emit("open", { cancelable: true })) return;
}
await stopAnimations(this.popupRef.value);
this.popupRef.value.hidden = false;
this.updatePositioner();
await animateTo(this.popupRef.value, [{ transform: "scale(0)" }, { transform: "scale(1)" }], {
duration: hasUpdated ? duration : 0,
easing
});
if (hasUpdated) this.emit("opened");
return;
}
if (!this.open && hasUpdated) {
if (!this.emit("close", { cancelable: true })) return;
await stopAnimations(this.popupRef.value);
await animateTo(this.popupRef.value, [{ transform: "scale(1)" }, { transform: "scale(0)" }], {
duration,
easing
});
this.popupRef.value.hidden = true;
this.emit("closed");
}
}
connectedCallback() {
super.connectedCallback();
document.addEventListener("pointerdown", this.onDocumentClick);
this.definedController.whenDefined().then(() => {
this.overflowAncestors = getOverflowAncestors(this.target);
this.overflowAncestors.forEach((ancestor) => {
ancestor.addEventListener("scroll", this.onWindowScroll);
});
this.observeResize = observeResize(this.target, () => {
this.updatePositioner();
});
});
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("pointerdown", this.onDocumentClick);
this.overflowAncestors?.forEach((ancestor) => {
ancestor.removeEventListener("scroll", this.onWindowScroll);
});
this.observeResize?.unobserve();
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.definedController.whenDefined().then(() => {
const target = this.target;
target.addEventListener("focus", this.onFocus);
target.addEventListener("blur", this.onBlur);
target.addEventListener("pointerdown", this.onClick);
target.addEventListener("keydown", this.onKeydown);
target.addEventListener("mouseenter", this.onMouseEnter);
target.addEventListener("mouseleave", this.onMouseLeave);
});
}
render() {
const hasHeadline = this.isRich() && (this.headline || this.hasSlotController.test("headline"));
const hasAction = this.isRich() && this.hasSlotController.test("action");
return b`
`;
}
isRich() {
return this.variant === "rich";
}
requestClose() {
if (!this.hoverController.isHover) {
this.open = false;
return;
}
this.hoverController.onMouseLeave(() => {
if (this.hasTrigger("hover")) this.hoverTimeout = window.setTimeout(() => {
this.open = false;
}, this.closeDelay || 50);
else this.open = false;
}, true);
}
hasTrigger(trigger) {
return this.trigger.split(" ").includes(trigger);
}
onFocus() {
if (this.disabled || this.open || !this.hasTrigger("focus")) return;
this.open = true;
}
onBlur() {
if (this.disabled || !this.open || !this.hasTrigger("focus")) return;
this.requestClose();
}
onClick(e) {
if (this.disabled || e.button || !this.hasTrigger("click")) return;
if (this.open && (this.hasTrigger("hover") || this.hasTrigger("focus"))) return;
this.open = !this.open;
}
onKeydown(e) {
if (this.disabled || !this.open || e.key !== "Escape") return;
e.stopPropagation();
this.requestClose();
}
onMouseEnter() {
if (this.disabled || this.open || !this.hasTrigger("hover")) return;
if (this.openDelay) {
window.clearTimeout(this.hoverTimeout);
this.hoverTimeout = window.setTimeout(() => {
this.open = true;
}, this.openDelay);
} else this.open = true;
}
onMouseLeave() {
window.clearTimeout(this.hoverTimeout);
if (this.disabled || !this.open || !this.hasTrigger("hover")) return;
this.hoverTimeout = window.setTimeout(() => {
this.requestClose();
}, this.closeDelay || 50);
}
onDocumentClick(e) {
if (this.disabled || !this.open) return;
if (!e.composedPath().includes(this)) this.requestClose();
}
onWindowScroll() {
window.requestAnimationFrame(() => this.updatePositioner());
}
updatePositioner() {
const $popup = $$1(this.popupRef.value);
const targetMargin = this.isRich() ? 0 : 4;
const popupMargin = 4;
const targetRect = this.target.getBoundingClientRect();
const targetTop = targetRect.top;
const targetLeft = targetRect.left;
const targetHeight = targetRect.height;
const targetWidth = targetRect.width;
const popupHeight = this.popupRef.value.offsetHeight;
const popupWidth = this.popupRef.value.offsetWidth;
const popupXSpace = popupWidth + targetMargin + popupMargin;
const popupYSpace = popupHeight + targetMargin + popupMargin;
let transformOriginX;
let transformOriginY;
let top;
let left;
let placement = this.placement;
if (placement === "auto") {
const $window = $$1(window);
const hasTopSpace = targetTop > popupYSpace;
const hasBottomSpace = $window.height() - targetTop - targetHeight > popupYSpace;
const hasLeftSpace = targetLeft > popupXSpace;
const hasRightSpace = $window.width() - targetLeft - targetWidth > popupXSpace;
if (this.isRich()) {
placement = "bottom-right";
if (hasBottomSpace && hasRightSpace) placement = "bottom-right";
else if (hasBottomSpace && hasLeftSpace) placement = "bottom-left";
else if (hasTopSpace && hasRightSpace) placement = "top-right";
else if (hasTopSpace && hasLeftSpace) placement = "top-left";
else if (hasBottomSpace) placement = "bottom";
else if (hasTopSpace) placement = "top";
else if (hasRightSpace) placement = "right";
else if (hasLeftSpace) placement = "left";
} else {
placement = "top";
if (hasTopSpace) placement = "top";
else if (hasBottomSpace) placement = "bottom";
else if (hasLeftSpace) placement = "left";
else if (hasRightSpace) placement = "right";
}
}
const [position, alignment] = placement.split("-");
switch (position) {
case "top":
transformOriginY = "bottom";
top = targetTop - popupHeight - targetMargin;
break;
case "bottom":
transformOriginY = "top";
top = targetTop + targetHeight + targetMargin;
break;
default:
transformOriginY = "center";
switch (alignment) {
case "start":
top = targetTop;
break;
case "end":
top = targetTop + targetHeight - popupHeight;
break;
default:
top = targetTop + targetHeight / 2 - popupHeight / 2;
break;
}
break;
}
switch (position) {
case "left":
transformOriginX = "right";
left = targetLeft - popupWidth - targetMargin;
break;
case "right":
transformOriginX = "left";
left = targetLeft + targetWidth + targetMargin;
break;
default:
transformOriginX = "center";
switch (alignment) {
case "start":
left = targetLeft;
break;
case "end":
left = targetLeft + targetWidth - popupWidth;
break;
case "left":
transformOriginX = "right";
left = targetLeft - popupWidth - targetMargin;
break;
case "right":
transformOriginX = "left";
left = targetLeft + targetWidth + targetMargin;
break;
default:
left = targetLeft + targetWidth / 2 - popupWidth / 2;
break;
}
break;
}
$popup.css({
top,
left,
transformOrigin: [transformOriginX, transformOriginY].join(" ")
});
}
};
Tooltip.styles = [componentStyle, style];
__decorate([n$6({ reflect: true })], Tooltip.prototype, "variant", void 0);
__decorate([n$6({ reflect: true })], Tooltip.prototype, "placement", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "open-delay"
})], Tooltip.prototype, "openDelay", void 0);
__decorate([n$6({
type: Number,
reflect: true,
attribute: "close-delay"
})], Tooltip.prototype, "closeDelay", void 0);
__decorate([n$6({ reflect: true })], Tooltip.prototype, "headline", void 0);
__decorate([n$6({ reflect: true })], Tooltip.prototype, "content", void 0);
__decorate([n$6({ reflect: true })], Tooltip.prototype, "trigger", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Tooltip.prototype, "disabled", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], Tooltip.prototype, "open", void 0);
__decorate([watch("placement", true), watch("content", true)], Tooltip.prototype, "onPositionChange", null);
__decorate([watch("open")], Tooltip.prototype, "onOpenChange", null);
Tooltip = __decorate([t$3("mdui-tooltip")], Tooltip);
var getInnerHtmlFromSlot = (slot) => {
const nodes = slot.assignedNodes({ flatten: true });
let html = "";
[...nodes].forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) html += node.outerHTML;
if (node.nodeType === Node.TEXT_NODE) html += node.textContent;
});
return html;
};
var topAppBarTitleStyle = i$7`:host{display:block;width:100%;flex-shrink:initial!important;overflow:hidden;color:rgb(var(--mdui-color-on-surface));font-size:var(--mdui-typescale-title-large-size);font-weight:var(--mdui-typescale-title-large-weight);letter-spacing:var(--mdui-typescale-title-large-tracking);line-height:var(--mdui-typescale-title-large-line-height);line-height:2.5rem}.label{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;opacity:1;transition:opacity var(--mdui-motion-duration-short2) var(--mdui-motion-easing-linear)}.label.variant-center-aligned{text-align:center}.label.variant-large:not(.shrink),.label.variant-medium:not(.shrink){opacity:0}.label.variant-large.shrink,.label.variant-medium.shrink{transition-delay:var(--mdui-motion-duration-short2)}.label-large{display:none;position:absolute;width:100%;left:0;margin-right:0;padding:0 1rem;transition:opacity var(--mdui-motion-duration-short2) var(--mdui-motion-easing-linear)}.label-large.variant-large,.label-large.variant-medium{display:block}.label-large.variant-medium{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;bottom:.75rem;font-size:var(--mdui-typescale-headline-small-size);font-weight:var(--mdui-typescale-headline-small-weight);letter-spacing:var(--mdui-typescale-headline-small-tracking);line-height:var(--mdui-typescale-headline-small-line-height)}.label-large.variant-large{display:-webkit-box;overflow:hidden;white-space:normal;-webkit-box-orient:vertical;-webkit-line-clamp:2;bottom:1.25rem;font-size:var(--mdui-typescale-headline-medium-size);font-weight:var(--mdui-typescale-headline-medium-weight);letter-spacing:var(--mdui-typescale-headline-medium-tracking);line-height:var(--mdui-typescale-headline-medium-line-height)}.label-large.variant-large:not(.shrink),.label-large.variant-medium:not(.shrink){opacity:1;transition-delay:var(--mdui-motion-duration-short2)}.label-large.variant-large.shrink,.label-large.variant-medium.shrink{opacity:0;z-index:-1}`;
var TopAppBarTitle = class TopAppBarTitle extends MduiElement {
constructor() {
super(...arguments);
this.variant = "small";
this.shrink = false;
this.hasSlotController = new HasSlotController(this, "label-large");
this.labelLargeRef = e$1();
this.defaultSlotRef = e$1();
}
render() {
const hasLabelLargeSlot = this.hasSlotController.test("label-large");
const className = e({
shrink: this.shrink,
"variant-center-aligned": this.variant === "center-aligned",
"variant-small": this.variant === "small",
"variant-medium": this.variant === "medium",
"variant-large": this.variant === "large"
});
return b`
this.onSlotChange(hasLabelLargeSlot)}">${hasLabelLargeSlot ? b`
` : b`
`}`;
}
onSlotChange(hasLabelLargeSlot) {
if (!hasLabelLargeSlot) this.labelLargeRef.value.innerHTML = getInnerHtmlFromSlot(this.defaultSlotRef.value);
}
};
TopAppBarTitle.styles = [componentStyle, topAppBarTitleStyle];
__decorate([r$2()], TopAppBarTitle.prototype, "variant", void 0);
__decorate([r$2()], TopAppBarTitle.prototype, "shrink", void 0);
TopAppBarTitle = __decorate([t$3("mdui-top-app-bar-title")], TopAppBarTitle);
var topAppBarStyle = i$7`:host{--shape-corner:var(--mdui-shape-corner-none);--z-index:2000;position:fixed;top:0;right:0;left:0;display:flex;flex:0 0 auto;align-items:flex-start;justify-content:flex-start;border-bottom-left-radius:var(--shape-corner);border-bottom-right-radius:var(--shape-corner);z-index:var(--z-index);transition:top var(--mdui-motion-duration-long2) var(--mdui-motion-easing-standard),height var(--mdui-motion-duration-long2) var(--mdui-motion-easing-standard),box-shadow var(--mdui-motion-duration-short4) var(--mdui-motion-easing-linear),background-color var(--mdui-motion-duration-short4) var(--mdui-motion-easing-linear);padding:.75rem .5rem;height:4rem;background-color:rgb(var(--mdui-color-surface))}:host([scroll-target]:not([scroll-target=''])){position:absolute}:host([scroll-behavior~=shrink]){transition-duration:var(--mdui-motion-duration-short4)}:host([scrolling]){background-color:rgb(var(--mdui-color-surface-container));box-shadow:var(--mdui-elevation-level2)}::slotted(mdui-button-icon){color:rgb(var(--mdui-color-on-surface-variant));font-size:1.5rem}::slotted(mdui-button-icon:first-child){color:rgb(var(--mdui-color-on-surface))}::slotted(mdui-avatar){width:1.875rem;height:1.875rem;margin-top:.3125rem;margin-bottom:.3125rem}::slotted(*){flex-shrink:0}::slotted(:not(:last-child)){margin-right:.5rem}:host([variant=medium]){height:7rem}:host([variant=large]){height:9.5rem}:host([hide]:not([hide=false i])){transition-duration:var(--mdui-motion-duration-short4);top:-4.625rem}:host([hide][variant=medium]:not([hide=false i])){top:-7.625rem}:host([hide][variant=large]:not([hide=false i])){top:-10.125rem}:host([shrink][variant=large]:not([shrink=false i])),:host([shrink][variant=medium]:not([shrink=false i])){transition-duration:var(--mdui-motion-duration-short4);height:4rem}`;
var TopAppBar = class TopAppBar extends ScrollBehaviorMixin(LayoutItemBase) {
constructor() {
super(...arguments);
this.variant = "small";
this.hide = false;
this.shrink = false;
this.scrolling = false;
this.definedController = new DefinedController(this, { relatedElements: ["mdui-top-app-bar-title"] });
}
get scrollPaddingPosition() {
return "top";
}
get layoutPlacement() {
return "top";
}
async onVariantChange() {
if (this.hasUpdated) this.addEventListener("transitionend", async () => {
await this.scrollBehaviorDefinedController.whenDefined();
this.setContainerPadding("update", this.scrollTarget);
}, { once: true });
else await this.updateComplete;
await this.definedController.whenDefined();
this.titleElements.forEach((titleElement) => {
titleElement.variant = this.variant;
});
}
async onShrinkChange() {
if (!this.hasUpdated) await this.updateComplete;
await this.definedController.whenDefined();
this.titleElements.forEach((titleElement) => {
titleElement.shrink = this.shrink;
});
}
firstUpdated(_changedProperties) {
super.firstUpdated(_changedProperties);
this.addEventListener("transitionend", (e) => {
if (e.target === this) this.emit(this.hide ? "hidden" : "shown");
});
}
render() {
return b`
`;
}
runScrollNoThreshold(isScrollingUp, scrollTop) {
if (this.hasScrollBehavior("shrink")) {
if (isScrollingUp && scrollTop < 8) this.shrink = false;
}
}
runScrollThreshold(isScrollingUp, scrollTop) {
if (this.hasScrollBehavior("elevate")) this.scrolling = !!scrollTop;
if (this.hasScrollBehavior("shrink")) {
if (!isScrollingUp) this.shrink = true;
}
if (this.hasScrollBehavior("hide")) {
if (!isScrollingUp && !this.hide) {
if (this.emit("hide", { cancelable: true })) this.hide = true;
}
if (isScrollingUp && this.hide) {
if (this.emit("show", { cancelable: true })) this.hide = false;
}
}
}
};
TopAppBar.styles = [componentStyle, topAppBarStyle];
__decorate([n$6({ reflect: true })], TopAppBar.prototype, "variant", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TopAppBar.prototype, "hide", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TopAppBar.prototype, "shrink", void 0);
__decorate([n$6({
reflect: true,
attribute: "scroll-behavior"
})], TopAppBar.prototype, "scrollBehavior", void 0);
__decorate([n$6({
type: Boolean,
reflect: true,
converter: booleanConverter
})], TopAppBar.prototype, "scrolling", void 0);
__decorate([o$7({
selector: "mdui-top-app-bar-title",
flatten: true
})], TopAppBar.prototype, "titleElements", void 0);
__decorate([watch("variant")], TopAppBar.prototype, "onVariantChange", null);
__decorate([watch("shrink")], TopAppBar.prototype, "onShrinkChange", null);
TopAppBar = __decorate([t$3("mdui-top-app-bar")], TopAppBar);
function isPromise(obj) {
return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
}
var container = {};
function queue(name, func) {
if (isUndefined(container[name])) container[name] = [];
if (isUndefined(func)) return container[name];
container[name].push(func);
}
function dequeue(name) {
if (isUndefined(container[name])) return;
if (!container[name].length) return;
container[name].shift()();
}
var defaultAction = { onClick: returnTrue };
var queueName$1 = "mdui.functions.dialog.";
var currentDialog = void 0;
var dialog = (options) => {
const dialog = new Dialog();
const $dialog = $$1(dialog);
const properties = [
"headline",
"description",
"icon",
"closeOnEsc",
"closeOnOverlayClick",
"stackedActions"
];
const callbacks = [
"onOpen",
"onOpened",
"onClose",
"onClosed",
"onOverlayClick"
];
Object.entries(options).forEach(([key, value]) => {
if (properties.includes(key)) dialog[key] = value;
else if (callbacks.includes(key)) {
const eventName = toKebabCase(key.slice(2));
$dialog.on(eventName, (e) => {
if (e.target === dialog) value.call(dialog, dialog);
});
}
});
if (options.body) $dialog.append(options.body);
if (options.actions) options.actions.forEach((action) => {
const mergedAction = Object.assign({}, defaultAction, action);
$$1(`
${mergedAction.text}`).appendTo($dialog).on("click", function() {
const clickResult = mergedAction.onClick.call(dialog, dialog);
if (isPromise(clickResult)) {
this.loading = true;
clickResult.then(() => {
dialog.open = false;
}).finally(() => {
this.loading = false;
});
} else if (clickResult !== false) dialog.open = false;
});
});
$dialog.appendTo("body").on("closed", (e) => {
if (e.target !== dialog) return;
$dialog.remove();
if (options.queue) {
currentDialog = void 0;
dequeue(queueName$1 + options.queue);
}
});
if (!options.queue) setTimeout(() => {
dialog.open = true;
});
else if (currentDialog) queue(queueName$1 + options.queue, () => {
dialog.open = true;
currentDialog = dialog;
});
else {
setTimeout(() => {
dialog.open = true;
});
currentDialog = dialog;
}
return dialog;
};
var getConfirmText$1 = () => {
return msg("OK", { id: "functions.confirm.confirmText" });
};
var getCancelText$1 = () => {
return msg("Cancel", { id: "functions.confirm.cancelText" });
};
var confirm = (options) => {
const mergedOptions = Object.assign({}, {
confirmText: getConfirmText$1(),
cancelText: getCancelText$1(),
onConfirm: returnTrue,
onCancel: returnTrue
}, options);
const properties = [
"headline",
"description",
"icon",
"closeOnEsc",
"closeOnOverlayClick",
"stackedActions",
"queue",
"onOpen",
"onOpened",
"onClose",
"onClosed",
"onOverlayClick"
];
return new Promise((resolve, reject) => {
let isResolve = false;
const dialog$2 = dialog({
...Object.fromEntries(properties.filter((key) => !isUndefined(mergedOptions[key])).map((key) => [key, mergedOptions[key]])),
actions: [{
text: mergedOptions.cancelText,
onClick: (dialog) => {
return mergedOptions.onCancel.call(dialog, dialog);
}
}, {
text: mergedOptions.confirmText,
onClick: (dialog) => {
const clickResult = mergedOptions.onConfirm.call(dialog, dialog);
if (isPromise(clickResult)) clickResult.then(() => {
isResolve = true;
});
else if (clickResult !== false) isResolve = true;
return clickResult;
}
}]
});
if (!options.confirmText) onLocaleReady(dialog$2, () => {
$$1(dialog$2).find("[slot=\"action\"]").last().text(getConfirmText$1());
});
if (!options.cancelText) onLocaleReady(dialog$2, () => {
$$1(dialog$2).find("[slot=\"action\"]").first().text(getCancelText$1());
});
$$1(dialog$2).on("close", (e) => {
if (e.target === dialog$2) {
if (isResolve) resolve();
else reject();
offLocaleReady(dialog$2);
}
});
});
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function signum(num) {
if (num < 0) return -1;
else if (num === 0) return 0;
else return 1;
}
function lerp(start, stop, amount) {
return (1 - amount) * start + amount * stop;
}
function clampInt(min, max, input) {
if (input < min) return min;
else if (input > max) return max;
return input;
}
function clampDouble(min, max, input) {
if (input < min) return min;
else if (input > max) return max;
return input;
}
function sanitizeDegreesInt(degrees) {
degrees = degrees % 360;
if (degrees < 0) degrees = degrees + 360;
return degrees;
}
function sanitizeDegreesDouble(degrees) {
degrees = degrees % 360;
if (degrees < 0) degrees = degrees + 360;
return degrees;
}
function rotationDirection(from, to) {
return sanitizeDegreesDouble(to - from) <= 180 ? 1 : -1;
}
function differenceDegrees(a, b) {
return 180 - Math.abs(Math.abs(a - b) - 180);
}
function matrixMultiply(row, matrix) {
return [
row[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2],
row[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2],
row[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2]
];
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SRGB_TO_XYZ = [
[
.41233895,
.35762064,
.18051042
],
[
.2126,
.7152,
.0722
],
[
.01932141,
.11916382,
.95034478
]
];
var XYZ_TO_SRGB = [
[
3.2413774792388685,
-1.5376652402851851,
-.49885366846268053
],
[
-.9691452513005321,
1.8758853451067872,
.04156585616912061
],
[
.05562093689691305,
-.20395524564742123,
1.0571799111220335
]
];
var WHITE_POINT_D65 = [
95.047,
100,
108.883
];
function argbFromRgb(red, green, blue) {
return (255 << 24 | (red & 255) << 16 | (green & 255) << 8 | blue & 255) >>> 0;
}
function argbFromLinrgb(linrgb) {
return argbFromRgb(delinearized(linrgb[0]), delinearized(linrgb[1]), delinearized(linrgb[2]));
}
function redFromArgb(argb) {
return argb >> 16 & 255;
}
function greenFromArgb(argb) {
return argb >> 8 & 255;
}
function blueFromArgb(argb) {
return argb & 255;
}
function argbFromXyz(x, y, z) {
const matrix = XYZ_TO_SRGB;
const linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z;
const linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z;
const linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z;
return argbFromRgb(delinearized(linearR), delinearized(linearG), delinearized(linearB));
}
function xyzFromArgb(argb) {
return matrixMultiply([
linearized(redFromArgb(argb)),
linearized(greenFromArgb(argb)),
linearized(blueFromArgb(argb))
], SRGB_TO_XYZ);
}
function argbFromLstar(lstar) {
const component = delinearized(yFromLstar(lstar));
return argbFromRgb(component, component, component);
}
function lstarFromArgb(argb) {
const y = xyzFromArgb(argb)[1];
return 116 * labF(y / 100) - 16;
}
function yFromLstar(lstar) {
return 100 * labInvf((lstar + 16) / 116);
}
function lstarFromY(y) {
return labF(y / 100) * 116 - 16;
}
function linearized(rgbComponent) {
const normalized = rgbComponent / 255;
if (normalized <= .040449936) return normalized / 12.92 * 100;
else return Math.pow((normalized + .055) / 1.055, 2.4) * 100;
}
function delinearized(rgbComponent) {
const normalized = rgbComponent / 100;
let delinearized = 0;
if (normalized <= .0031308) delinearized = normalized * 12.92;
else delinearized = 1.055 * Math.pow(normalized, 1 / 2.4) - .055;
return clampInt(0, 255, Math.round(delinearized * 255));
}
function whitePointD65() {
return WHITE_POINT_D65;
}
function labF(t) {
const e = 216 / 24389;
const kappa = 24389 / 27;
if (t > e) return Math.pow(t, 1 / 3);
else return (kappa * t + 16) / 116;
}
function labInvf(ft) {
const e = 216 / 24389;
const kappa = 24389 / 27;
const ft3 = ft * ft * ft;
if (ft3 > e) return ft3;
else return (116 * ft - 16) / kappa;
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ViewingConditions = class ViewingConditions {
static make(whitePoint = whitePointD65(), adaptingLuminance = 200 / Math.PI * yFromLstar(50) / 100, backgroundLstar = 50, surround = 2, discountingIlluminant = false) {
const xyz = whitePoint;
const rW = xyz[0] * .401288 + xyz[1] * .650173 + xyz[2] * -.051461;
const gW = xyz[0] * -.250268 + xyz[1] * 1.204414 + xyz[2] * .045854;
const bW = xyz[0] * -.002079 + xyz[1] * .048952 + xyz[2] * .953127;
const f = .8 + surround / 10;
const c = f >= .9 ? lerp(.59, .69, (f - .9) * 10) : lerp(.525, .59, (f - .8) * 10);
let d = discountingIlluminant ? 1 : f * (1 - 1 / 3.6 * Math.exp((-adaptingLuminance - 42) / 92));
d = d > 1 ? 1 : d < 0 ? 0 : d;
const nc = f;
const rgbD = [
d * (100 / rW) + 1 - d,
d * (100 / gW) + 1 - d,
d * (100 / bW) + 1 - d
];
const k = 1 / (5 * adaptingLuminance + 1);
const k4 = k * k * k * k;
const k4F = 1 - k4;
const fl = k4 * adaptingLuminance + .1 * k4F * k4F * Math.cbrt(5 * adaptingLuminance);
const n = yFromLstar(backgroundLstar) / whitePoint[1];
const z = 1.48 + Math.sqrt(n);
const nbb = .725 / Math.pow(n, .2);
const ncb = nbb;
const rgbAFactors = [
Math.pow(fl * rgbD[0] * rW / 100, .42),
Math.pow(fl * rgbD[1] * gW / 100, .42),
Math.pow(fl * rgbD[2] * bW / 100, .42)
];
const rgbA = [
400 * rgbAFactors[0] / (rgbAFactors[0] + 27.13),
400 * rgbAFactors[1] / (rgbAFactors[1] + 27.13),
400 * rgbAFactors[2] / (rgbAFactors[2] + 27.13)
];
return new ViewingConditions(n, (2 * rgbA[0] + rgbA[1] + .05 * rgbA[2]) * nbb, nbb, ncb, c, nc, rgbD, fl, Math.pow(fl, .25), z);
}
constructor(n, aw, nbb, ncb, c, nc, rgbD, fl, fLRoot, z) {
this.n = n;
this.aw = aw;
this.nbb = nbb;
this.ncb = ncb;
this.c = c;
this.nc = nc;
this.rgbD = rgbD;
this.fl = fl;
this.fLRoot = fLRoot;
this.z = z;
}
};
ViewingConditions.DEFAULT = ViewingConditions.make();
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Cam16 = class Cam16 {
constructor(hue, chroma, j, q, m, s, jstar, astar, bstar) {
this.hue = hue;
this.chroma = chroma;
this.j = j;
this.q = q;
this.m = m;
this.s = s;
this.jstar = jstar;
this.astar = astar;
this.bstar = bstar;
}
distance(other) {
const dJ = this.jstar - other.jstar;
const dA = this.astar - other.astar;
const dB = this.bstar - other.bstar;
const dEPrime = Math.sqrt(dJ * dJ + dA * dA + dB * dB);
return 1.41 * Math.pow(dEPrime, .63);
}
static fromInt(argb) {
return Cam16.fromIntInViewingConditions(argb, ViewingConditions.DEFAULT);
}
static fromIntInViewingConditions(argb, viewingConditions) {
const red = (argb & 16711680) >> 16;
const green = (argb & 65280) >> 8;
const blue = argb & 255;
const redL = linearized(red);
const greenL = linearized(green);
const blueL = linearized(blue);
const x = .41233895 * redL + .35762064 * greenL + .18051042 * blueL;
const y = .2126 * redL + .7152 * greenL + .0722 * blueL;
const z = .01932141 * redL + .11916382 * greenL + .95034478 * blueL;
const rC = .401288 * x + .650173 * y - .051461 * z;
const gC = -.250268 * x + 1.204414 * y + .045854 * z;
const bC = -.002079 * x + .048952 * y + .953127 * z;
const rD = viewingConditions.rgbD[0] * rC;
const gD = viewingConditions.rgbD[1] * gC;
const bD = viewingConditions.rgbD[2] * bC;
const rAF = Math.pow(viewingConditions.fl * Math.abs(rD) / 100, .42);
const gAF = Math.pow(viewingConditions.fl * Math.abs(gD) / 100, .42);
const bAF = Math.pow(viewingConditions.fl * Math.abs(bD) / 100, .42);
const rA = signum(rD) * 400 * rAF / (rAF + 27.13);
const gA = signum(gD) * 400 * gAF / (gAF + 27.13);
const bA = signum(bD) * 400 * bAF / (bAF + 27.13);
const a = (11 * rA + -12 * gA + bA) / 11;
const b = (rA + gA - 2 * bA) / 9;
const u = (20 * rA + 20 * gA + 21 * bA) / 20;
const p2 = (40 * rA + 20 * gA + bA) / 20;
const atanDegrees = Math.atan2(b, a) * 180 / Math.PI;
const hue = atanDegrees < 0 ? atanDegrees + 360 : atanDegrees >= 360 ? atanDegrees - 360 : atanDegrees;
const hueRadians = hue * Math.PI / 180;
const ac = p2 * viewingConditions.nbb;
const j = 100 * Math.pow(ac / viewingConditions.aw, viewingConditions.c * viewingConditions.z);
const q = 4 / viewingConditions.c * Math.sqrt(j / 100) * (viewingConditions.aw + 4) * viewingConditions.fLRoot;
const huePrime = hue < 20.14 ? hue + 360 : hue;
const t = 5e4 / 13 * (.25 * (Math.cos(huePrime * Math.PI / 180 + 2) + 3.8)) * viewingConditions.nc * viewingConditions.ncb * Math.sqrt(a * a + b * b) / (u + .305);
const alpha = Math.pow(t, .9) * Math.pow(1.64 - Math.pow(.29, viewingConditions.n), .73);
const c = alpha * Math.sqrt(j / 100);
const m = c * viewingConditions.fLRoot;
const s = 50 * Math.sqrt(alpha * viewingConditions.c / (viewingConditions.aw + 4));
const jstar = 1.7000000000000002 * j / (1 + .007 * j);
const mstar = 1 / .0228 * Math.log(1 + .0228 * m);
return new Cam16(hue, c, j, q, m, s, jstar, mstar * Math.cos(hueRadians), mstar * Math.sin(hueRadians));
}
static fromJch(j, c, h) {
return Cam16.fromJchInViewingConditions(j, c, h, ViewingConditions.DEFAULT);
}
static fromJchInViewingConditions(j, c, h, viewingConditions) {
const q = 4 / viewingConditions.c * Math.sqrt(j / 100) * (viewingConditions.aw + 4) * viewingConditions.fLRoot;
const m = c * viewingConditions.fLRoot;
const alpha = c / Math.sqrt(j / 100);
const s = 50 * Math.sqrt(alpha * viewingConditions.c / (viewingConditions.aw + 4));
const hueRadians = h * Math.PI / 180;
const jstar = 1.7000000000000002 * j / (1 + .007 * j);
const mstar = 1 / .0228 * Math.log(1 + .0228 * m);
return new Cam16(h, c, j, q, m, s, jstar, mstar * Math.cos(hueRadians), mstar * Math.sin(hueRadians));
}
static fromUcs(jstar, astar, bstar) {
return Cam16.fromUcsInViewingConditions(jstar, astar, bstar, ViewingConditions.DEFAULT);
}
static fromUcsInViewingConditions(jstar, astar, bstar, viewingConditions) {
const a = astar;
const b = bstar;
const m = Math.sqrt(a * a + b * b);
const c = (Math.exp(m * .0228) - 1) / .0228 / viewingConditions.fLRoot;
let h = Math.atan2(b, a) * (180 / Math.PI);
if (h < 0) h += 360;
const j = jstar / (1 - (jstar - 100) * .007);
return Cam16.fromJchInViewingConditions(j, c, h, viewingConditions);
}
toInt() {
return this.viewed(ViewingConditions.DEFAULT);
}
viewed(viewingConditions) {
const alpha = this.chroma === 0 || this.j === 0 ? 0 : this.chroma / Math.sqrt(this.j / 100);
const t = Math.pow(alpha / Math.pow(1.64 - Math.pow(.29, viewingConditions.n), .73), 1 / .9);
const hRad = this.hue * Math.PI / 180;
const eHue = .25 * (Math.cos(hRad + 2) + 3.8);
const ac = viewingConditions.aw * Math.pow(this.j / 100, 1 / viewingConditions.c / viewingConditions.z);
const p1 = eHue * (5e4 / 13) * viewingConditions.nc * viewingConditions.ncb;
const p2 = ac / viewingConditions.nbb;
const hSin = Math.sin(hRad);
const hCos = Math.cos(hRad);
const gamma = 23 * (p2 + .305) * t / (23 * p1 + 11 * t * hCos + 108 * t * hSin);
const a = gamma * hCos;
const b = gamma * hSin;
const rA = (460 * p2 + 451 * a + 288 * b) / 1403;
const gA = (460 * p2 - 891 * a - 261 * b) / 1403;
const bA = (460 * p2 - 220 * a - 6300 * b) / 1403;
const rCBase = Math.max(0, 27.13 * Math.abs(rA) / (400 - Math.abs(rA)));
const rC = signum(rA) * (100 / viewingConditions.fl) * Math.pow(rCBase, 1 / .42);
const gCBase = Math.max(0, 27.13 * Math.abs(gA) / (400 - Math.abs(gA)));
const gC = signum(gA) * (100 / viewingConditions.fl) * Math.pow(gCBase, 1 / .42);
const bCBase = Math.max(0, 27.13 * Math.abs(bA) / (400 - Math.abs(bA)));
const bC = signum(bA) * (100 / viewingConditions.fl) * Math.pow(bCBase, 1 / .42);
const rF = rC / viewingConditions.rgbD[0];
const gF = gC / viewingConditions.rgbD[1];
const bF = bC / viewingConditions.rgbD[2];
return argbFromXyz(1.86206786 * rF - 1.01125463 * gF + .14918677 * bF, .38752654 * rF + .62144744 * gF - .00897398 * bF, -.0158415 * rF - .03412294 * gF + 1.04996444 * bF);
}
static fromXyzInViewingConditions(x, y, z, viewingConditions) {
const rC = .401288 * x + .650173 * y - .051461 * z;
const gC = -.250268 * x + 1.204414 * y + .045854 * z;
const bC = -.002079 * x + .048952 * y + .953127 * z;
const rD = viewingConditions.rgbD[0] * rC;
const gD = viewingConditions.rgbD[1] * gC;
const bD = viewingConditions.rgbD[2] * bC;
const rAF = Math.pow(viewingConditions.fl * Math.abs(rD) / 100, .42);
const gAF = Math.pow(viewingConditions.fl * Math.abs(gD) / 100, .42);
const bAF = Math.pow(viewingConditions.fl * Math.abs(bD) / 100, .42);
const rA = signum(rD) * 400 * rAF / (rAF + 27.13);
const gA = signum(gD) * 400 * gAF / (gAF + 27.13);
const bA = signum(bD) * 400 * bAF / (bAF + 27.13);
const a = (11 * rA + -12 * gA + bA) / 11;
const b = (rA + gA - 2 * bA) / 9;
const u = (20 * rA + 20 * gA + 21 * bA) / 20;
const p2 = (40 * rA + 20 * gA + bA) / 20;
const atanDegrees = Math.atan2(b, a) * 180 / Math.PI;
const hue = atanDegrees < 0 ? atanDegrees + 360 : atanDegrees >= 360 ? atanDegrees - 360 : atanDegrees;
const hueRadians = hue * Math.PI / 180;
const ac = p2 * viewingConditions.nbb;
const J = 100 * Math.pow(ac / viewingConditions.aw, viewingConditions.c * viewingConditions.z);
const Q = 4 / viewingConditions.c * Math.sqrt(J / 100) * (viewingConditions.aw + 4) * viewingConditions.fLRoot;
const huePrime = hue < 20.14 ? hue + 360 : hue;
const t = 5e4 / 13 * (1 / 4 * (Math.cos(huePrime * Math.PI / 180 + 2) + 3.8)) * viewingConditions.nc * viewingConditions.ncb * Math.sqrt(a * a + b * b) / (u + .305);
const alpha = Math.pow(t, .9) * Math.pow(1.64 - Math.pow(.29, viewingConditions.n), .73);
const C = alpha * Math.sqrt(J / 100);
const M = C * viewingConditions.fLRoot;
const s = 50 * Math.sqrt(alpha * viewingConditions.c / (viewingConditions.aw + 4));
const jstar = 1.7000000000000002 * J / (1 + .007 * J);
const mstar = Math.log(1 + .0228 * M) / .0228;
return new Cam16(hue, C, J, Q, M, s, jstar, mstar * Math.cos(hueRadians), mstar * Math.sin(hueRadians));
}
xyzInViewingConditions(viewingConditions) {
const alpha = this.chroma === 0 || this.j === 0 ? 0 : this.chroma / Math.sqrt(this.j / 100);
const t = Math.pow(alpha / Math.pow(1.64 - Math.pow(.29, viewingConditions.n), .73), 1 / .9);
const hRad = this.hue * Math.PI / 180;
const eHue = .25 * (Math.cos(hRad + 2) + 3.8);
const ac = viewingConditions.aw * Math.pow(this.j / 100, 1 / viewingConditions.c / viewingConditions.z);
const p1 = eHue * (5e4 / 13) * viewingConditions.nc * viewingConditions.ncb;
const p2 = ac / viewingConditions.nbb;
const hSin = Math.sin(hRad);
const hCos = Math.cos(hRad);
const gamma = 23 * (p2 + .305) * t / (23 * p1 + 11 * t * hCos + 108 * t * hSin);
const a = gamma * hCos;
const b = gamma * hSin;
const rA = (460 * p2 + 451 * a + 288 * b) / 1403;
const gA = (460 * p2 - 891 * a - 261 * b) / 1403;
const bA = (460 * p2 - 220 * a - 6300 * b) / 1403;
const rCBase = Math.max(0, 27.13 * Math.abs(rA) / (400 - Math.abs(rA)));
const rC = signum(rA) * (100 / viewingConditions.fl) * Math.pow(rCBase, 1 / .42);
const gCBase = Math.max(0, 27.13 * Math.abs(gA) / (400 - Math.abs(gA)));
const gC = signum(gA) * (100 / viewingConditions.fl) * Math.pow(gCBase, 1 / .42);
const bCBase = Math.max(0, 27.13 * Math.abs(bA) / (400 - Math.abs(bA)));
const bC = signum(bA) * (100 / viewingConditions.fl) * Math.pow(bCBase, 1 / .42);
const rF = rC / viewingConditions.rgbD[0];
const gF = gC / viewingConditions.rgbD[1];
const bF = bC / viewingConditions.rgbD[2];
return [
1.86206786 * rF - 1.01125463 * gF + .14918677 * bF,
.38752654 * rF + .62144744 * gF - .00897398 * bF,
-.0158415 * rF - .03412294 * gF + 1.04996444 * bF
];
}
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var HctSolver = class HctSolver {
static sanitizeRadians(angle) {
return (angle + Math.PI * 8) % (Math.PI * 2);
}
static trueDelinearized(rgbComponent) {
const normalized = rgbComponent / 100;
let delinearized = 0;
if (normalized <= .0031308) delinearized = normalized * 12.92;
else delinearized = 1.055 * Math.pow(normalized, 1 / 2.4) - .055;
return delinearized * 255;
}
static chromaticAdaptation(component) {
const af = Math.pow(Math.abs(component), .42);
return signum(component) * 400 * af / (af + 27.13);
}
static hueOf(linrgb) {
const scaledDiscount = matrixMultiply(linrgb, HctSolver.SCALED_DISCOUNT_FROM_LINRGB);
const rA = HctSolver.chromaticAdaptation(scaledDiscount[0]);
const gA = HctSolver.chromaticAdaptation(scaledDiscount[1]);
const bA = HctSolver.chromaticAdaptation(scaledDiscount[2]);
const a = (11 * rA + -12 * gA + bA) / 11;
const b = (rA + gA - 2 * bA) / 9;
return Math.atan2(b, a);
}
static areInCyclicOrder(a, b, c) {
return HctSolver.sanitizeRadians(b - a) < HctSolver.sanitizeRadians(c - a);
}
static intercept(source, mid, target) {
return (mid - source) / (target - source);
}
static lerpPoint(source, t, target) {
return [
source[0] + (target[0] - source[0]) * t,
source[1] + (target[1] - source[1]) * t,
source[2] + (target[2] - source[2]) * t
];
}
static setCoordinate(source, coordinate, target, axis) {
const t = HctSolver.intercept(source[axis], coordinate, target[axis]);
return HctSolver.lerpPoint(source, t, target);
}
static isBounded(x) {
return 0 <= x && x <= 100;
}
static nthVertex(y, n) {
const kR = HctSolver.Y_FROM_LINRGB[0];
const kG = HctSolver.Y_FROM_LINRGB[1];
const kB = HctSolver.Y_FROM_LINRGB[2];
const coordA = n % 4 <= 1 ? 0 : 100;
const coordB = n % 2 === 0 ? 0 : 100;
if (n < 4) {
const g = coordA;
const b = coordB;
const r = (y - g * kG - b * kB) / kR;
if (HctSolver.isBounded(r)) return [
r,
g,
b
];
else return [
-1,
-1,
-1
];
} else if (n < 8) {
const b = coordA;
const r = coordB;
const g = (y - r * kR - b * kB) / kG;
if (HctSolver.isBounded(g)) return [
r,
g,
b
];
else return [
-1,
-1,
-1
];
} else {
const r = coordA;
const g = coordB;
const b = (y - r * kR - g * kG) / kB;
if (HctSolver.isBounded(b)) return [
r,
g,
b
];
else return [
-1,
-1,
-1
];
}
}
static bisectToSegment(y, targetHue) {
let left = [
-1,
-1,
-1
];
let right = left;
let leftHue = 0;
let rightHue = 0;
let initialized = false;
let uncut = true;
for (let n = 0; n < 12; n++) {
const mid = HctSolver.nthVertex(y, n);
if (mid[0] < 0) continue;
const midHue = HctSolver.hueOf(mid);
if (!initialized) {
left = mid;
right = mid;
leftHue = midHue;
rightHue = midHue;
initialized = true;
continue;
}
if (uncut || HctSolver.areInCyclicOrder(leftHue, midHue, rightHue)) {
uncut = false;
if (HctSolver.areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid;
rightHue = midHue;
} else {
left = mid;
leftHue = midHue;
}
}
}
return [left, right];
}
static midpoint(a, b) {
return [
(a[0] + b[0]) / 2,
(a[1] + b[1]) / 2,
(a[2] + b[2]) / 2
];
}
static criticalPlaneBelow(x) {
return Math.floor(x - .5);
}
static criticalPlaneAbove(x) {
return Math.ceil(x - .5);
}
static bisectToLimit(y, targetHue) {
const segment = HctSolver.bisectToSegment(y, targetHue);
let left = segment[0];
let leftHue = HctSolver.hueOf(left);
let right = segment[1];
for (let axis = 0; axis < 3; axis++) if (left[axis] !== right[axis]) {
let lPlane = -1;
let rPlane = 255;
if (left[axis] < right[axis]) {
lPlane = HctSolver.criticalPlaneBelow(HctSolver.trueDelinearized(left[axis]));
rPlane = HctSolver.criticalPlaneAbove(HctSolver.trueDelinearized(right[axis]));
} else {
lPlane = HctSolver.criticalPlaneAbove(HctSolver.trueDelinearized(left[axis]));
rPlane = HctSolver.criticalPlaneBelow(HctSolver.trueDelinearized(right[axis]));
}
for (let i = 0; i < 8; i++) if (Math.abs(rPlane - lPlane) <= 1) break;
else {
const mPlane = Math.floor((lPlane + rPlane) / 2);
const midPlaneCoordinate = HctSolver.CRITICAL_PLANES[mPlane];
const mid = HctSolver.setCoordinate(left, midPlaneCoordinate, right, axis);
const midHue = HctSolver.hueOf(mid);
if (HctSolver.areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid;
rPlane = mPlane;
} else {
left = mid;
leftHue = midHue;
lPlane = mPlane;
}
}
}
return HctSolver.midpoint(left, right);
}
static inverseChromaticAdaptation(adapted) {
const adaptedAbs = Math.abs(adapted);
const base = Math.max(0, 27.13 * adaptedAbs / (400 - adaptedAbs));
return signum(adapted) * Math.pow(base, 1 / .42);
}
static findResultByJ(hueRadians, chroma, y) {
let j = Math.sqrt(y) * 11;
const viewingConditions = ViewingConditions.DEFAULT;
const tInnerCoeff = 1 / Math.pow(1.64 - Math.pow(.29, viewingConditions.n), .73);
const p1 = .25 * (Math.cos(hueRadians + 2) + 3.8) * (5e4 / 13) * viewingConditions.nc * viewingConditions.ncb;
const hSin = Math.sin(hueRadians);
const hCos = Math.cos(hueRadians);
for (let iterationRound = 0; iterationRound < 5; iterationRound++) {
const jNormalized = j / 100;
const alpha = chroma === 0 || j === 0 ? 0 : chroma / Math.sqrt(jNormalized);
const t = Math.pow(alpha * tInnerCoeff, 1 / .9);
const p2 = viewingConditions.aw * Math.pow(jNormalized, 1 / viewingConditions.c / viewingConditions.z) / viewingConditions.nbb;
const gamma = 23 * (p2 + .305) * t / (23 * p1 + 11 * t * hCos + 108 * t * hSin);
const a = gamma * hCos;
const b = gamma * hSin;
const rA = (460 * p2 + 451 * a + 288 * b) / 1403;
const gA = (460 * p2 - 891 * a - 261 * b) / 1403;
const bA = (460 * p2 - 220 * a - 6300 * b) / 1403;
const linrgb = matrixMultiply([
HctSolver.inverseChromaticAdaptation(rA),
HctSolver.inverseChromaticAdaptation(gA),
HctSolver.inverseChromaticAdaptation(bA)
], HctSolver.LINRGB_FROM_SCALED_DISCOUNT);
if (linrgb[0] < 0 || linrgb[1] < 0 || linrgb[2] < 0) return 0;
const kR = HctSolver.Y_FROM_LINRGB[0];
const kG = HctSolver.Y_FROM_LINRGB[1];
const kB = HctSolver.Y_FROM_LINRGB[2];
const fnj = kR * linrgb[0] + kG * linrgb[1] + kB * linrgb[2];
if (fnj <= 0) return 0;
if (iterationRound === 4 || Math.abs(fnj - y) < .002) {
if (linrgb[0] > 100.01 || linrgb[1] > 100.01 || linrgb[2] > 100.01) return 0;
return argbFromLinrgb(linrgb);
}
j = j - (fnj - y) * j / (2 * fnj);
}
return 0;
}
static solveToInt(hueDegrees, chroma, lstar) {
if (chroma < 1e-4 || lstar < 1e-4 || lstar > 99.9999) return argbFromLstar(lstar);
hueDegrees = sanitizeDegreesDouble(hueDegrees);
const hueRadians = hueDegrees / 180 * Math.PI;
const y = yFromLstar(lstar);
const exactAnswer = HctSolver.findResultByJ(hueRadians, chroma, y);
if (exactAnswer !== 0) return exactAnswer;
return argbFromLinrgb(HctSolver.bisectToLimit(y, hueRadians));
}
static solveToCam(hueDegrees, chroma, lstar) {
return Cam16.fromInt(HctSolver.solveToInt(hueDegrees, chroma, lstar));
}
};
HctSolver.SCALED_DISCOUNT_FROM_LINRGB = [
[
.001200833568784504,
.002389694492170889,
.0002795742885861124
],
[
.0005891086651375999,
.0029785502573438758,
.0003270666104008398
],
[
.00010146692491640572,
.0005364214359186694,
.0032979401770712076
]
];
HctSolver.LINRGB_FROM_SCALED_DISCOUNT = [
[
1373.2198709594231,
-1100.4251190754821,
-7.278681089101213
],
[
-271.815969077903,
559.6580465940733,
-32.46047482791194
],
[
1.9622899599665666,
-57.173814538844006,
308.7233197812385
]
];
HctSolver.Y_FROM_LINRGB = [
.2126,
.7152,
.0722
];
HctSolver.CRITICAL_PLANES = [
.015176349177441876,
.045529047532325624,
.07588174588720938,
.10623444424209313,
.13658714259697685,
.16693984095186062,
.19729253930674434,
.2276452376616281,
.2579979360165119,
.28835063437139563,
.3188300904430532,
.350925934958123,
.3848314933096426,
.42057480301049466,
.458183274052838,
.4976837250274023,
.5391024159806381,
.5824650784040898,
.6277969426914107,
.6751227633498623,
.7244668422128921,
.775853049866786,
.829304845476233,
.8848452951698498,
.942497089126609,
1.0022825574869039,
1.0642236851973577,
1.1283421258858297,
1.1946592148522128,
1.2631959812511864,
1.3339731595349034,
1.407011200216447,
1.4823302800086415,
1.5599503113873272,
1.6398909516233677,
1.7221716113234105,
1.8068114625156377,
1.8938294463134073,
1.9832442801866852,
2.075074464868551,
2.1693382909216234,
2.2660538449872063,
2.36523901573795,
2.4669114995532007,
2.5710888059345764,
2.6777882626779785,
2.7870270208169257,
2.898822059350997,
3.0131901897720907,
3.1301480604002863,
3.2497121605402226,
3.3718988244681087,
3.4967242352587946,
3.624204428461639,
3.754355295633311,
3.887192587735158,
4.022731918402185,
4.160988767090289,
4.301978482107941,
4.445716283538092,
4.592217266055746,
4.741496401646282,
4.893568542229298,
5.048448422192488,
5.20615066083972,
5.3666897647573375,
5.5300801301023865,
5.696336044816294,
5.865471690767354,
6.037501145825082,
6.212438385869475,
6.390297286737924,
6.571091626112461,
6.7548350853498045,
6.941541251256611,
7.131223617812143,
7.323895587840543,
7.5195704746346665,
7.7182615035334345,
7.919981813454504,
8.124744458384042,
8.332562408825165,
8.543448553206703,
8.757415699253682,
8.974476575321063,
9.194643831691977,
9.417930041841839,
9.644347703669503,
9.873909240696694,
10.106627003236781,
10.342513269534024,
10.58158024687427,
10.8238400726681,
11.069304815507364,
11.317986476196008,
11.569896988756009,
11.825048221409341,
12.083451977536606,
12.345119996613247,
12.610063955123938,
12.878295467455942,
13.149826086772048,
13.42466730586372,
13.702830557985108,
13.984327217668513,
14.269168601521828,
14.55736596900856,
14.848930523210871,
15.143873411576273,
15.44220572664832,
15.743938506781891,
16.04908273684337,
16.35764934889634,
16.66964922287304,
16.985093187232053,
17.30399201960269,
17.62635644741625,
17.95219714852476,
18.281524751807332,
18.614349837764564,
18.95068293910138,
19.290534541298456,
19.633915083172692,
19.98083495742689,
20.331304511189067,
20.685334046541502,
21.042933821039977,
21.404114048223256,
21.76888489811322,
22.137256497705877,
22.50923893145328,
22.884842241736916,
23.264076429332462,
23.6469514538663,
24.033477234264016,
24.42366364919083,
24.817520537484558,
25.21505769858089,
25.61628489293138,
26.021211842414342,
26.429848230738664,
26.842203703840827,
27.258287870275353,
27.678110301598522,
28.10168053274597,
28.529008062403893,
28.96010235337422,
29.39497283293396,
29.83362889318845,
30.276079891419332,
30.722335150426627,
31.172403958865512,
31.62629557157785,
32.08401920991837,
32.54558406207592,
33.010999283389665,
33.4802739966603,
33.953417292456834,
34.430438229418264,
34.911345834551085,
35.39614910352207,
35.88485700094671,
36.37747846067349,
36.87402238606382,
37.37449765026789,
37.87891309649659,
38.38727753828926,
38.89959975977785,
39.41588851594697,
39.93615253289054,
40.460400508064545,
40.98864111053629,
41.520882981230194,
42.05713473317016,
42.597404951718396,
43.141702194811224,
43.6900349931913,
44.24241185063697,
44.798841244188324,
45.35933162437017,
45.92389141541209,
46.49252901546552,
47.065252796817916,
47.64207110610409,
48.22299226451468,
48.808024568002054,
49.3971762874833,
49.9904556690408,
50.587870934119984,
51.189430279724725,
51.79514187861014,
52.40501387947288,
53.0190544071392,
53.637271562750364,
54.259673423945976,
54.88626804504493,
55.517063457223934,
56.15206766869424,
56.79128866487574,
57.43473440856916,
58.08241284012621,
58.734331877617365,
59.39049941699807,
60.05092333227251,
60.715611475655585,
61.38457167773311,
62.057811747619894,
62.7353394731159,
63.417162620860914,
64.10328893648692,
64.79372614476921,
65.48848194977529,
66.18756403501224,
66.89098006357258,
67.59873767827808,
68.31084450182222,
69.02730813691093,
69.74813616640164,
70.47333615344107,
71.20291564160104,
71.93688215501312,
72.67524319850172,
73.41800625771542,
74.16517879925733,
74.9167682708136,
75.67278210128072,
76.43322770089146,
77.1981124613393,
77.96744375590167,
78.74122893956174,
79.51947534912904,
80.30219030335869,
81.08938110306934,
81.88105503125999,
82.67721935322541,
83.4778813166706,
84.28304815182372,
85.09272707154808,
85.90692527145302,
86.72564993000343,
87.54890820862819,
88.3767072518277,
89.2090541872801,
90.04595612594655,
90.88742016217518,
91.73345337380438,
92.58406282226491,
93.43925555268066,
94.29903859396902,
95.16341895893969,
96.03240364439274,
96.9059996312159,
97.78421388448044,
98.6670533535366,
99.55452497210776
];
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Hct = class Hct {
static from(hue, chroma, tone) {
return new Hct(HctSolver.solveToInt(hue, chroma, tone));
}
static fromInt(argb) {
return new Hct(argb);
}
toInt() {
return this.argb;
}
get hue() {
return this.internalHue;
}
set hue(newHue) {
this.setInternalState(HctSolver.solveToInt(newHue, this.internalChroma, this.internalTone));
}
get chroma() {
return this.internalChroma;
}
set chroma(newChroma) {
this.setInternalState(HctSolver.solveToInt(this.internalHue, newChroma, this.internalTone));
}
get tone() {
return this.internalTone;
}
set tone(newTone) {
this.setInternalState(HctSolver.solveToInt(this.internalHue, this.internalChroma, newTone));
}
constructor(argb) {
this.argb = argb;
const cam = Cam16.fromInt(argb);
this.internalHue = cam.hue;
this.internalChroma = cam.chroma;
this.internalTone = lstarFromArgb(argb);
this.argb = argb;
}
setInternalState(argb) {
const cam = Cam16.fromInt(argb);
this.internalHue = cam.hue;
this.internalChroma = cam.chroma;
this.internalTone = lstarFromArgb(argb);
this.argb = argb;
}
inViewingConditions(vc) {
const viewedInVc = Cam16.fromInt(this.toInt()).xyzInViewingConditions(vc);
const recastInVc = Cam16.fromXyzInViewingConditions(viewedInVc[0], viewedInVc[1], viewedInVc[2], ViewingConditions.make());
return Hct.from(recastInVc.hue, recastInVc.chroma, lstarFromY(viewedInVc[1]));
}
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Blend = class Blend {
static harmonize(designColor, sourceColor) {
const fromHct = Hct.fromInt(designColor);
const toHct = Hct.fromInt(sourceColor);
const differenceDegrees$2 = differenceDegrees(fromHct.hue, toHct.hue);
const rotationDegrees = Math.min(differenceDegrees$2 * .5, 15);
const outputHue = sanitizeDegreesDouble(fromHct.hue + rotationDegrees * rotationDirection(fromHct.hue, toHct.hue));
return Hct.from(outputHue, fromHct.chroma, fromHct.tone).toInt();
}
static hctHue(from, to, amount) {
const ucs = Blend.cam16Ucs(from, to, amount);
const ucsCam = Cam16.fromInt(ucs);
const fromCam = Cam16.fromInt(from);
return Hct.from(ucsCam.hue, fromCam.chroma, lstarFromArgb(from)).toInt();
}
static cam16Ucs(from, to, amount) {
const fromCam = Cam16.fromInt(from);
const toCam = Cam16.fromInt(to);
const fromJ = fromCam.jstar;
const fromA = fromCam.astar;
const fromB = fromCam.bstar;
const toJ = toCam.jstar;
const toA = toCam.astar;
const toB = toCam.bstar;
const jstar = fromJ + (toJ - fromJ) * amount;
const astar = fromA + (toA - fromA) * amount;
const bstar = fromB + (toB - fromB) * amount;
return Cam16.fromUcs(jstar, astar, bstar).toInt();
}
};
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Contrast = class Contrast {
static ratioOfTones(toneA, toneB) {
toneA = clampDouble(0, 100, toneA);
toneB = clampDouble(0, 100, toneB);
return Contrast.ratioOfYs(yFromLstar(toneA), yFromLstar(toneB));
}
static ratioOfYs(y1, y2) {
const lighter = y1 > y2 ? y1 : y2;
const darker = lighter === y2 ? y1 : y2;
return (lighter + 5) / (darker + 5);
}
static lighter(tone, ratio) {
if (tone < 0 || tone > 100) return -1;
const darkY = yFromLstar(tone);
const lightY = ratio * (darkY + 5) - 5;
const realContrast = Contrast.ratioOfYs(lightY, darkY);
const delta = Math.abs(realContrast - ratio);
if (realContrast < ratio && delta > .04) return -1;
const returnValue = lstarFromY(lightY) + .4;
if (returnValue < 0 || returnValue > 100) return -1;
return returnValue;
}
static darker(tone, ratio) {
if (tone < 0 || tone > 100) return -1;
const lightY = yFromLstar(tone);
const darkY = (lightY + 5) / ratio - 5;
const realContrast = Contrast.ratioOfYs(lightY, darkY);
const delta = Math.abs(realContrast - ratio);
if (realContrast < ratio && delta > .04) return -1;
const returnValue = lstarFromY(darkY) - .4;
if (returnValue < 0 || returnValue > 100) return -1;
return returnValue;
}
static lighterUnsafe(tone, ratio) {
const lighterSafe = Contrast.lighter(tone, ratio);
return lighterSafe < 0 ? 100 : lighterSafe;
}
static darkerUnsafe(tone, ratio) {
const darkerSafe = Contrast.darker(tone, ratio);
return darkerSafe < 0 ? 0 : darkerSafe;
}
};
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DislikeAnalyzer = class DislikeAnalyzer {
static isDisliked(hct) {
const huePasses = Math.round(hct.hue) >= 90 && Math.round(hct.hue) <= 111;
const chromaPasses = Math.round(hct.chroma) > 16;
const tonePasses = Math.round(hct.tone) < 65;
return huePasses && chromaPasses && tonePasses;
}
static fixIfDisliked(hct) {
if (DislikeAnalyzer.isDisliked(hct)) return Hct.from(hct.hue, hct.chroma, 70);
return hct;
}
};
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DynamicColor = class DynamicColor {
static fromPalette(args) {
return new DynamicColor(args.name ?? "", args.palette, args.tone, args.isBackground ?? false, args.background, args.secondBackground, args.contrastCurve, args.toneDeltaPair);
}
constructor(name, palette, tone, isBackground, background, secondBackground, contrastCurve, toneDeltaPair) {
this.name = name;
this.palette = palette;
this.tone = tone;
this.isBackground = isBackground;
this.background = background;
this.secondBackground = secondBackground;
this.contrastCurve = contrastCurve;
this.toneDeltaPair = toneDeltaPair;
this.hctCache = new Map();
if (!background && secondBackground) throw new Error(`Color ${name} has secondBackgrounddefined, but background is not defined.`);
if (!background && contrastCurve) throw new Error(`Color ${name} has contrastCurvedefined, but background is not defined.`);
if (background && !contrastCurve) throw new Error(`Color ${name} has backgrounddefined, but contrastCurve is not defined.`);
}
getArgb(scheme) {
return this.getHct(scheme).toInt();
}
getHct(scheme) {
const cachedAnswer = this.hctCache.get(scheme);
if (cachedAnswer != null) return cachedAnswer;
const tone = this.getTone(scheme);
const answer = this.palette(scheme).getHct(tone);
if (this.hctCache.size > 4) this.hctCache.clear();
this.hctCache.set(scheme, answer);
return answer;
}
getTone(scheme) {
const decreasingContrast = scheme.contrastLevel < 0;
if (this.toneDeltaPair) {
const toneDeltaPair = this.toneDeltaPair(scheme);
const roleA = toneDeltaPair.roleA;
const roleB = toneDeltaPair.roleB;
const delta = toneDeltaPair.delta;
const polarity = toneDeltaPair.polarity;
const stayTogether = toneDeltaPair.stayTogether;
const bgTone = this.background(scheme).getTone(scheme);
const aIsNearer = polarity === "nearer" || polarity === "lighter" && !scheme.isDark || polarity === "darker" && scheme.isDark;
const nearer = aIsNearer ? roleA : roleB;
const farther = aIsNearer ? roleB : roleA;
const amNearer = this.name === nearer.name;
const expansionDir = scheme.isDark ? 1 : -1;
const nContrast = nearer.contrastCurve.get(scheme.contrastLevel);
const fContrast = farther.contrastCurve.get(scheme.contrastLevel);
const nInitialTone = nearer.tone(scheme);
let nTone = Contrast.ratioOfTones(bgTone, nInitialTone) >= nContrast ? nInitialTone : DynamicColor.foregroundTone(bgTone, nContrast);
const fInitialTone = farther.tone(scheme);
let fTone = Contrast.ratioOfTones(bgTone, fInitialTone) >= fContrast ? fInitialTone : DynamicColor.foregroundTone(bgTone, fContrast);
if (decreasingContrast) {
nTone = DynamicColor.foregroundTone(bgTone, nContrast);
fTone = DynamicColor.foregroundTone(bgTone, fContrast);
}
if ((fTone - nTone) * expansionDir >= delta) {} else {
fTone = clampDouble(0, 100, nTone + delta * expansionDir);
if ((fTone - nTone) * expansionDir >= delta) {} else nTone = clampDouble(0, 100, fTone - delta * expansionDir);
}
if (50 <= nTone && nTone < 60) if (expansionDir > 0) {
nTone = 60;
fTone = Math.max(fTone, nTone + delta * expansionDir);
} else {
nTone = 49;
fTone = Math.min(fTone, nTone + delta * expansionDir);
}
else if (50 <= fTone && fTone < 60) if (stayTogether) if (expansionDir > 0) {
nTone = 60;
fTone = Math.max(fTone, nTone + delta * expansionDir);
} else {
nTone = 49;
fTone = Math.min(fTone, nTone + delta * expansionDir);
}
else if (expansionDir > 0) fTone = 60;
else fTone = 49;
return amNearer ? nTone : fTone;
} else {
let answer = this.tone(scheme);
if (this.background == null) return answer;
const bgTone = this.background(scheme).getTone(scheme);
const desiredRatio = this.contrastCurve.get(scheme.contrastLevel);
if (Contrast.ratioOfTones(bgTone, answer) >= desiredRatio) {} else answer = DynamicColor.foregroundTone(bgTone, desiredRatio);
if (decreasingContrast) answer = DynamicColor.foregroundTone(bgTone, desiredRatio);
if (this.isBackground && 50 <= answer && answer < 60) if (Contrast.ratioOfTones(49, bgTone) >= desiredRatio) answer = 49;
else answer = 60;
if (this.secondBackground) {
const [bg1, bg2] = [this.background, this.secondBackground];
const [bgTone1, bgTone2] = [bg1(scheme).getTone(scheme), bg2(scheme).getTone(scheme)];
const [upper, lower] = [Math.max(bgTone1, bgTone2), Math.min(bgTone1, bgTone2)];
if (Contrast.ratioOfTones(upper, answer) >= desiredRatio && Contrast.ratioOfTones(lower, answer) >= desiredRatio) return answer;
const lightOption = Contrast.lighter(upper, desiredRatio);
const darkOption = Contrast.darker(lower, desiredRatio);
const availables = [];
if (lightOption !== -1) availables.push(lightOption);
if (darkOption !== -1) availables.push(darkOption);
if (DynamicColor.tonePrefersLightForeground(bgTone1) || DynamicColor.tonePrefersLightForeground(bgTone2)) return lightOption < 0 ? 100 : lightOption;
if (availables.length === 1) return availables[0];
return darkOption < 0 ? 0 : darkOption;
}
return answer;
}
}
static foregroundTone(bgTone, ratio) {
const lighterTone = Contrast.lighterUnsafe(bgTone, ratio);
const darkerTone = Contrast.darkerUnsafe(bgTone, ratio);
const lighterRatio = Contrast.ratioOfTones(lighterTone, bgTone);
const darkerRatio = Contrast.ratioOfTones(darkerTone, bgTone);
if (DynamicColor.tonePrefersLightForeground(bgTone)) {
const negligibleDifference = Math.abs(lighterRatio - darkerRatio) < .1 && lighterRatio < ratio && darkerRatio < ratio;
return lighterRatio >= ratio || lighterRatio >= darkerRatio || negligibleDifference ? lighterTone : darkerTone;
} else return darkerRatio >= ratio || darkerRatio >= lighterRatio ? darkerTone : lighterTone;
}
static tonePrefersLightForeground(tone) {
return Math.round(tone) < 60;
}
static toneAllowsLightForeground(tone) {
return Math.round(tone) <= 49;
}
static enableLightForeground(tone) {
if (DynamicColor.tonePrefersLightForeground(tone) && !DynamicColor.toneAllowsLightForeground(tone)) return 49;
return tone;
}
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var TonalPalette = class TonalPalette {
static fromInt(argb) {
const hct = Hct.fromInt(argb);
return TonalPalette.fromHct(hct);
}
static fromHct(hct) {
return new TonalPalette(hct.hue, hct.chroma, hct);
}
static fromHueAndChroma(hue, chroma) {
return new TonalPalette(hue, chroma, new KeyColor(hue, chroma).create());
}
constructor(hue, chroma, keyColor) {
this.hue = hue;
this.chroma = chroma;
this.keyColor = keyColor;
this.cache = new Map();
}
tone(tone) {
let argb = this.cache.get(tone);
if (argb === void 0) {
argb = Hct.from(this.hue, this.chroma, tone).toInt();
this.cache.set(tone, argb);
}
return argb;
}
getHct(tone) {
return Hct.fromInt(this.tone(tone));
}
};
var KeyColor = class {
constructor(hue, requestedChroma) {
this.hue = hue;
this.requestedChroma = requestedChroma;
this.chromaCache = new Map();
this.maxChromaValue = 200;
}
create() {
const pivotTone = 50;
const toneStepSize = 1;
const epsilon = .01;
let lowerTone = 0;
let upperTone = 100;
while (lowerTone < upperTone) {
const midTone = Math.floor((lowerTone + upperTone) / 2);
const isAscending = this.maxChroma(midTone) < this.maxChroma(midTone + toneStepSize);
if (this.maxChroma(midTone) >= this.requestedChroma - epsilon) if (Math.abs(lowerTone - pivotTone) < Math.abs(upperTone - pivotTone)) upperTone = midTone;
else {
if (lowerTone === midTone) return Hct.from(this.hue, this.requestedChroma, lowerTone);
lowerTone = midTone;
}
else if (isAscending) lowerTone = midTone + toneStepSize;
else upperTone = midTone;
}
return Hct.from(this.hue, this.requestedChroma, lowerTone);
}
maxChroma(tone) {
if (this.chromaCache.has(tone)) return this.chromaCache.get(tone);
const chroma = Hct.from(this.hue, this.maxChromaValue, tone).chroma;
this.chromaCache.set(tone, chroma);
return chroma;
}
};
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ContrastCurve = class {
constructor(low, normal, medium, high) {
this.low = low;
this.normal = normal;
this.medium = medium;
this.high = high;
}
get(contrastLevel) {
if (contrastLevel <= -1) return this.low;
else if (contrastLevel < 0) return lerp(this.low, this.normal, (contrastLevel - -1) / 1);
else if (contrastLevel < .5) return lerp(this.normal, this.medium, (contrastLevel - 0) / .5);
else if (contrastLevel < 1) return lerp(this.medium, this.high, (contrastLevel - .5) / .5);
else return this.high;
}
};
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ToneDeltaPair = class {
constructor(roleA, roleB, delta, polarity, stayTogether) {
this.roleA = roleA;
this.roleB = roleB;
this.delta = delta;
this.polarity = polarity;
this.stayTogether = stayTogether;
}
};
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Variant;
(function(Variant) {
Variant[Variant["MONOCHROME"] = 0] = "MONOCHROME";
Variant[Variant["NEUTRAL"] = 1] = "NEUTRAL";
Variant[Variant["TONAL_SPOT"] = 2] = "TONAL_SPOT";
Variant[Variant["VIBRANT"] = 3] = "VIBRANT";
Variant[Variant["EXPRESSIVE"] = 4] = "EXPRESSIVE";
Variant[Variant["FIDELITY"] = 5] = "FIDELITY";
Variant[Variant["CONTENT"] = 6] = "CONTENT";
Variant[Variant["RAINBOW"] = 7] = "RAINBOW";
Variant[Variant["FRUIT_SALAD"] = 8] = "FRUIT_SALAD";
})(Variant || (Variant = {}));
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function isFidelity(scheme) {
return scheme.variant === Variant.FIDELITY || scheme.variant === Variant.CONTENT;
}
function isMonochrome(scheme) {
return scheme.variant === Variant.MONOCHROME;
}
function findDesiredChromaByTone(hue, chroma, tone, byDecreasingTone) {
let answer = tone;
let closestToChroma = Hct.from(hue, chroma, tone);
if (closestToChroma.chroma < chroma) {
let chromaPeak = closestToChroma.chroma;
while (closestToChroma.chroma < chroma) {
answer += byDecreasingTone ? -1 : 1;
const potentialSolution = Hct.from(hue, chroma, answer);
if (chromaPeak > potentialSolution.chroma) break;
if (Math.abs(potentialSolution.chroma - chroma) < .4) break;
if (Math.abs(potentialSolution.chroma - chroma) < Math.abs(closestToChroma.chroma - chroma)) closestToChroma = potentialSolution;
chromaPeak = Math.max(chromaPeak, potentialSolution.chroma);
}
}
return answer;
}
var MaterialDynamicColors = class MaterialDynamicColors {
static highestSurface(s) {
return s.isDark ? MaterialDynamicColors.surfaceBright : MaterialDynamicColors.surfaceDim;
}
};
MaterialDynamicColors.contentAccentToneDelta = 15;
MaterialDynamicColors.primaryPaletteKeyColor = DynamicColor.fromPalette({
name: "primary_palette_key_color",
palette: (s) => s.primaryPalette,
tone: (s) => s.primaryPalette.keyColor.tone
});
MaterialDynamicColors.secondaryPaletteKeyColor = DynamicColor.fromPalette({
name: "secondary_palette_key_color",
palette: (s) => s.secondaryPalette,
tone: (s) => s.secondaryPalette.keyColor.tone
});
MaterialDynamicColors.tertiaryPaletteKeyColor = DynamicColor.fromPalette({
name: "tertiary_palette_key_color",
palette: (s) => s.tertiaryPalette,
tone: (s) => s.tertiaryPalette.keyColor.tone
});
MaterialDynamicColors.neutralPaletteKeyColor = DynamicColor.fromPalette({
name: "neutral_palette_key_color",
palette: (s) => s.neutralPalette,
tone: (s) => s.neutralPalette.keyColor.tone
});
MaterialDynamicColors.neutralVariantPaletteKeyColor = DynamicColor.fromPalette({
name: "neutral_variant_palette_key_color",
palette: (s) => s.neutralVariantPalette,
tone: (s) => s.neutralVariantPalette.keyColor.tone
});
MaterialDynamicColors.background = DynamicColor.fromPalette({
name: "background",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 6 : 98,
isBackground: true
});
MaterialDynamicColors.onBackground = DynamicColor.fromPalette({
name: "on_background",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 90 : 10,
background: (s) => MaterialDynamicColors.background,
contrastCurve: new ContrastCurve(3, 3, 4.5, 7)
});
MaterialDynamicColors.surface = DynamicColor.fromPalette({
name: "surface",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 6 : 98,
isBackground: true
});
MaterialDynamicColors.surfaceDim = DynamicColor.fromPalette({
name: "surface_dim",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 6 : new ContrastCurve(87, 87, 80, 75).get(s.contrastLevel),
isBackground: true
});
MaterialDynamicColors.surfaceBright = DynamicColor.fromPalette({
name: "surface_bright",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(24, 24, 29, 34).get(s.contrastLevel) : 98,
isBackground: true
});
MaterialDynamicColors.surfaceContainerLowest = DynamicColor.fromPalette({
name: "surface_container_lowest",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(4, 4, 2, 0).get(s.contrastLevel) : 100,
isBackground: true
});
MaterialDynamicColors.surfaceContainerLow = DynamicColor.fromPalette({
name: "surface_container_low",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(10, 10, 11, 12).get(s.contrastLevel) : new ContrastCurve(96, 96, 96, 95).get(s.contrastLevel),
isBackground: true
});
MaterialDynamicColors.surfaceContainer = DynamicColor.fromPalette({
name: "surface_container",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(12, 12, 16, 20).get(s.contrastLevel) : new ContrastCurve(94, 94, 92, 90).get(s.contrastLevel),
isBackground: true
});
MaterialDynamicColors.surfaceContainerHigh = DynamicColor.fromPalette({
name: "surface_container_high",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(17, 17, 21, 25).get(s.contrastLevel) : new ContrastCurve(92, 92, 88, 85).get(s.contrastLevel),
isBackground: true
});
MaterialDynamicColors.surfaceContainerHighest = DynamicColor.fromPalette({
name: "surface_container_highest",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? new ContrastCurve(22, 22, 26, 30).get(s.contrastLevel) : new ContrastCurve(90, 90, 84, 80).get(s.contrastLevel),
isBackground: true
});
MaterialDynamicColors.onSurface = DynamicColor.fromPalette({
name: "on_surface",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 90 : 10,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.surfaceVariant = DynamicColor.fromPalette({
name: "surface_variant",
palette: (s) => s.neutralVariantPalette,
tone: (s) => s.isDark ? 30 : 90,
isBackground: true
});
MaterialDynamicColors.onSurfaceVariant = DynamicColor.fromPalette({
name: "on_surface_variant",
palette: (s) => s.neutralVariantPalette,
tone: (s) => s.isDark ? 80 : 30,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.inverseSurface = DynamicColor.fromPalette({
name: "inverse_surface",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 90 : 20
});
MaterialDynamicColors.inverseOnSurface = DynamicColor.fromPalette({
name: "inverse_on_surface",
palette: (s) => s.neutralPalette,
tone: (s) => s.isDark ? 20 : 95,
background: (s) => MaterialDynamicColors.inverseSurface,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.outline = DynamicColor.fromPalette({
name: "outline",
palette: (s) => s.neutralVariantPalette,
tone: (s) => s.isDark ? 60 : 50,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1.5, 3, 4.5, 7)
});
MaterialDynamicColors.outlineVariant = DynamicColor.fromPalette({
name: "outline_variant",
palette: (s) => s.neutralVariantPalette,
tone: (s) => s.isDark ? 30 : 80,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5)
});
MaterialDynamicColors.shadow = DynamicColor.fromPalette({
name: "shadow",
palette: (s) => s.neutralPalette,
tone: (s) => 0
});
MaterialDynamicColors.scrim = DynamicColor.fromPalette({
name: "scrim",
palette: (s) => s.neutralPalette,
tone: (s) => 0
});
MaterialDynamicColors.surfaceTint = DynamicColor.fromPalette({
name: "surface_tint",
palette: (s) => s.primaryPalette,
tone: (s) => s.isDark ? 80 : 40,
isBackground: true
});
MaterialDynamicColors.primary = DynamicColor.fromPalette({
name: "primary",
palette: (s) => s.primaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 100 : 0;
return s.isDark ? 80 : 40;
},
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(3, 4.5, 7, 7),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.primaryContainer, MaterialDynamicColors.primary, 10, "nearer", false)
});
MaterialDynamicColors.onPrimary = DynamicColor.fromPalette({
name: "on_primary",
palette: (s) => s.primaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 10 : 90;
return s.isDark ? 20 : 100;
},
background: (s) => MaterialDynamicColors.primary,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.primaryContainer = DynamicColor.fromPalette({
name: "primary_container",
palette: (s) => s.primaryPalette,
tone: (s) => {
if (isFidelity(s)) return s.sourceColorHct.tone;
if (isMonochrome(s)) return s.isDark ? 85 : 25;
return s.isDark ? 30 : 90;
},
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.primaryContainer, MaterialDynamicColors.primary, 10, "nearer", false)
});
MaterialDynamicColors.onPrimaryContainer = DynamicColor.fromPalette({
name: "on_primary_container",
palette: (s) => s.primaryPalette,
tone: (s) => {
if (isFidelity(s)) return DynamicColor.foregroundTone(MaterialDynamicColors.primaryContainer.tone(s), 4.5);
if (isMonochrome(s)) return s.isDark ? 0 : 100;
return s.isDark ? 90 : 30;
},
background: (s) => MaterialDynamicColors.primaryContainer,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.inversePrimary = DynamicColor.fromPalette({
name: "inverse_primary",
palette: (s) => s.primaryPalette,
tone: (s) => s.isDark ? 40 : 80,
background: (s) => MaterialDynamicColors.inverseSurface,
contrastCurve: new ContrastCurve(3, 4.5, 7, 7)
});
MaterialDynamicColors.secondary = DynamicColor.fromPalette({
name: "secondary",
palette: (s) => s.secondaryPalette,
tone: (s) => s.isDark ? 80 : 40,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(3, 4.5, 7, 7),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.secondaryContainer, MaterialDynamicColors.secondary, 10, "nearer", false)
});
MaterialDynamicColors.onSecondary = DynamicColor.fromPalette({
name: "on_secondary",
palette: (s) => s.secondaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 10 : 100;
else return s.isDark ? 20 : 100;
},
background: (s) => MaterialDynamicColors.secondary,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.secondaryContainer = DynamicColor.fromPalette({
name: "secondary_container",
palette: (s) => s.secondaryPalette,
tone: (s) => {
const initialTone = s.isDark ? 30 : 90;
if (isMonochrome(s)) return s.isDark ? 30 : 85;
if (!isFidelity(s)) return initialTone;
return findDesiredChromaByTone(s.secondaryPalette.hue, s.secondaryPalette.chroma, initialTone, s.isDark ? false : true);
},
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.secondaryContainer, MaterialDynamicColors.secondary, 10, "nearer", false)
});
MaterialDynamicColors.onSecondaryContainer = DynamicColor.fromPalette({
name: "on_secondary_container",
palette: (s) => s.secondaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 90 : 10;
if (!isFidelity(s)) return s.isDark ? 90 : 30;
return DynamicColor.foregroundTone(MaterialDynamicColors.secondaryContainer.tone(s), 4.5);
},
background: (s) => MaterialDynamicColors.secondaryContainer,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.tertiary = DynamicColor.fromPalette({
name: "tertiary",
palette: (s) => s.tertiaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 90 : 25;
return s.isDark ? 80 : 40;
},
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(3, 4.5, 7, 7),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.tertiaryContainer, MaterialDynamicColors.tertiary, 10, "nearer", false)
});
MaterialDynamicColors.onTertiary = DynamicColor.fromPalette({
name: "on_tertiary",
palette: (s) => s.tertiaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 10 : 90;
return s.isDark ? 20 : 100;
},
background: (s) => MaterialDynamicColors.tertiary,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.tertiaryContainer = DynamicColor.fromPalette({
name: "tertiary_container",
palette: (s) => s.tertiaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 60 : 49;
if (!isFidelity(s)) return s.isDark ? 30 : 90;
const proposedHct = s.tertiaryPalette.getHct(s.sourceColorHct.tone);
return DislikeAnalyzer.fixIfDisliked(proposedHct).tone;
},
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.tertiaryContainer, MaterialDynamicColors.tertiary, 10, "nearer", false)
});
MaterialDynamicColors.onTertiaryContainer = DynamicColor.fromPalette({
name: "on_tertiary_container",
palette: (s) => s.tertiaryPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 0 : 100;
if (!isFidelity(s)) return s.isDark ? 90 : 30;
return DynamicColor.foregroundTone(MaterialDynamicColors.tertiaryContainer.tone(s), 4.5);
},
background: (s) => MaterialDynamicColors.tertiaryContainer,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.error = DynamicColor.fromPalette({
name: "error",
palette: (s) => s.errorPalette,
tone: (s) => s.isDark ? 80 : 40,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(3, 4.5, 7, 7),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.errorContainer, MaterialDynamicColors.error, 10, "nearer", false)
});
MaterialDynamicColors.onError = DynamicColor.fromPalette({
name: "on_error",
palette: (s) => s.errorPalette,
tone: (s) => s.isDark ? 20 : 100,
background: (s) => MaterialDynamicColors.error,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.errorContainer = DynamicColor.fromPalette({
name: "error_container",
palette: (s) => s.errorPalette,
tone: (s) => s.isDark ? 30 : 90,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.errorContainer, MaterialDynamicColors.error, 10, "nearer", false)
});
MaterialDynamicColors.onErrorContainer = DynamicColor.fromPalette({
name: "on_error_container",
palette: (s) => s.errorPalette,
tone: (s) => {
if (isMonochrome(s)) return s.isDark ? 90 : 10;
return s.isDark ? 90 : 30;
},
background: (s) => MaterialDynamicColors.errorContainer,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.primaryFixed = DynamicColor.fromPalette({
name: "primary_fixed",
palette: (s) => s.primaryPalette,
tone: (s) => isMonochrome(s) ? 40 : 90,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.primaryFixed, MaterialDynamicColors.primaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.primaryFixedDim = DynamicColor.fromPalette({
name: "primary_fixed_dim",
palette: (s) => s.primaryPalette,
tone: (s) => isMonochrome(s) ? 30 : 80,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.primaryFixed, MaterialDynamicColors.primaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.onPrimaryFixed = DynamicColor.fromPalette({
name: "on_primary_fixed",
palette: (s) => s.primaryPalette,
tone: (s) => isMonochrome(s) ? 100 : 10,
background: (s) => MaterialDynamicColors.primaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.primaryFixed,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.onPrimaryFixedVariant = DynamicColor.fromPalette({
name: "on_primary_fixed_variant",
palette: (s) => s.primaryPalette,
tone: (s) => isMonochrome(s) ? 90 : 30,
background: (s) => MaterialDynamicColors.primaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.primaryFixed,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.secondaryFixed = DynamicColor.fromPalette({
name: "secondary_fixed",
palette: (s) => s.secondaryPalette,
tone: (s) => isMonochrome(s) ? 80 : 90,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.secondaryFixed, MaterialDynamicColors.secondaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.secondaryFixedDim = DynamicColor.fromPalette({
name: "secondary_fixed_dim",
palette: (s) => s.secondaryPalette,
tone: (s) => isMonochrome(s) ? 70 : 80,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.secondaryFixed, MaterialDynamicColors.secondaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.onSecondaryFixed = DynamicColor.fromPalette({
name: "on_secondary_fixed",
palette: (s) => s.secondaryPalette,
tone: (s) => 10,
background: (s) => MaterialDynamicColors.secondaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.secondaryFixed,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.onSecondaryFixedVariant = DynamicColor.fromPalette({
name: "on_secondary_fixed_variant",
palette: (s) => s.secondaryPalette,
tone: (s) => isMonochrome(s) ? 25 : 30,
background: (s) => MaterialDynamicColors.secondaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.secondaryFixed,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
MaterialDynamicColors.tertiaryFixed = DynamicColor.fromPalette({
name: "tertiary_fixed",
palette: (s) => s.tertiaryPalette,
tone: (s) => isMonochrome(s) ? 40 : 90,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.tertiaryFixed, MaterialDynamicColors.tertiaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.tertiaryFixedDim = DynamicColor.fromPalette({
name: "tertiary_fixed_dim",
palette: (s) => s.tertiaryPalette,
tone: (s) => isMonochrome(s) ? 30 : 80,
isBackground: true,
background: (s) => MaterialDynamicColors.highestSurface(s),
contrastCurve: new ContrastCurve(1, 1, 3, 4.5),
toneDeltaPair: (s) => new ToneDeltaPair(MaterialDynamicColors.tertiaryFixed, MaterialDynamicColors.tertiaryFixedDim, 10, "lighter", true)
});
MaterialDynamicColors.onTertiaryFixed = DynamicColor.fromPalette({
name: "on_tertiary_fixed",
palette: (s) => s.tertiaryPalette,
tone: (s) => isMonochrome(s) ? 100 : 10,
background: (s) => MaterialDynamicColors.tertiaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.tertiaryFixed,
contrastCurve: new ContrastCurve(4.5, 7, 11, 21)
});
MaterialDynamicColors.onTertiaryFixedVariant = DynamicColor.fromPalette({
name: "on_tertiary_fixed_variant",
palette: (s) => s.tertiaryPalette,
tone: (s) => isMonochrome(s) ? 90 : 30,
background: (s) => MaterialDynamicColors.tertiaryFixedDim,
secondBackground: (s) => MaterialDynamicColors.tertiaryFixed,
contrastCurve: new ContrastCurve(3, 4.5, 7, 11)
});
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DynamicScheme = class {
constructor(args) {
this.sourceColorArgb = args.sourceColorArgb;
this.variant = args.variant;
this.contrastLevel = args.contrastLevel;
this.isDark = args.isDark;
this.sourceColorHct = Hct.fromInt(args.sourceColorArgb);
this.primaryPalette = args.primaryPalette;
this.secondaryPalette = args.secondaryPalette;
this.tertiaryPalette = args.tertiaryPalette;
this.neutralPalette = args.neutralPalette;
this.neutralVariantPalette = args.neutralVariantPalette;
this.errorPalette = TonalPalette.fromHueAndChroma(25, 84);
}
static getRotatedHue(sourceColor, hues, rotations) {
const sourceHue = sourceColor.hue;
if (hues.length !== rotations.length) throw new Error(`mismatch between hue length ${hues.length} & rotations ${rotations.length}`);
if (rotations.length === 1) return sanitizeDegreesDouble(sourceColor.hue + rotations[0]);
const size = hues.length;
for (let i = 0; i <= size - 2; i++) {
const thisHue = hues[i];
const nextHue = hues[i + 1];
if (thisHue < sourceHue && sourceHue < nextHue) return sanitizeDegreesDouble(sourceHue + rotations[i]);
}
return sourceHue;
}
getArgb(dynamicColor) {
return dynamicColor.getArgb(this);
}
getHct(dynamicColor) {
return dynamicColor.getHct(this);
}
get primaryPaletteKeyColor() {
return this.getArgb(MaterialDynamicColors.primaryPaletteKeyColor);
}
get secondaryPaletteKeyColor() {
return this.getArgb(MaterialDynamicColors.secondaryPaletteKeyColor);
}
get tertiaryPaletteKeyColor() {
return this.getArgb(MaterialDynamicColors.tertiaryPaletteKeyColor);
}
get neutralPaletteKeyColor() {
return this.getArgb(MaterialDynamicColors.neutralPaletteKeyColor);
}
get neutralVariantPaletteKeyColor() {
return this.getArgb(MaterialDynamicColors.neutralVariantPaletteKeyColor);
}
get background() {
return this.getArgb(MaterialDynamicColors.background);
}
get onBackground() {
return this.getArgb(MaterialDynamicColors.onBackground);
}
get surface() {
return this.getArgb(MaterialDynamicColors.surface);
}
get surfaceDim() {
return this.getArgb(MaterialDynamicColors.surfaceDim);
}
get surfaceBright() {
return this.getArgb(MaterialDynamicColors.surfaceBright);
}
get surfaceContainerLowest() {
return this.getArgb(MaterialDynamicColors.surfaceContainerLowest);
}
get surfaceContainerLow() {
return this.getArgb(MaterialDynamicColors.surfaceContainerLow);
}
get surfaceContainer() {
return this.getArgb(MaterialDynamicColors.surfaceContainer);
}
get surfaceContainerHigh() {
return this.getArgb(MaterialDynamicColors.surfaceContainerHigh);
}
get surfaceContainerHighest() {
return this.getArgb(MaterialDynamicColors.surfaceContainerHighest);
}
get onSurface() {
return this.getArgb(MaterialDynamicColors.onSurface);
}
get surfaceVariant() {
return this.getArgb(MaterialDynamicColors.surfaceVariant);
}
get onSurfaceVariant() {
return this.getArgb(MaterialDynamicColors.onSurfaceVariant);
}
get inverseSurface() {
return this.getArgb(MaterialDynamicColors.inverseSurface);
}
get inverseOnSurface() {
return this.getArgb(MaterialDynamicColors.inverseOnSurface);
}
get outline() {
return this.getArgb(MaterialDynamicColors.outline);
}
get outlineVariant() {
return this.getArgb(MaterialDynamicColors.outlineVariant);
}
get shadow() {
return this.getArgb(MaterialDynamicColors.shadow);
}
get scrim() {
return this.getArgb(MaterialDynamicColors.scrim);
}
get surfaceTint() {
return this.getArgb(MaterialDynamicColors.surfaceTint);
}
get primary() {
return this.getArgb(MaterialDynamicColors.primary);
}
get onPrimary() {
return this.getArgb(MaterialDynamicColors.onPrimary);
}
get primaryContainer() {
return this.getArgb(MaterialDynamicColors.primaryContainer);
}
get onPrimaryContainer() {
return this.getArgb(MaterialDynamicColors.onPrimaryContainer);
}
get inversePrimary() {
return this.getArgb(MaterialDynamicColors.inversePrimary);
}
get secondary() {
return this.getArgb(MaterialDynamicColors.secondary);
}
get onSecondary() {
return this.getArgb(MaterialDynamicColors.onSecondary);
}
get secondaryContainer() {
return this.getArgb(MaterialDynamicColors.secondaryContainer);
}
get onSecondaryContainer() {
return this.getArgb(MaterialDynamicColors.onSecondaryContainer);
}
get tertiary() {
return this.getArgb(MaterialDynamicColors.tertiary);
}
get onTertiary() {
return this.getArgb(MaterialDynamicColors.onTertiary);
}
get tertiaryContainer() {
return this.getArgb(MaterialDynamicColors.tertiaryContainer);
}
get onTertiaryContainer() {
return this.getArgb(MaterialDynamicColors.onTertiaryContainer);
}
get error() {
return this.getArgb(MaterialDynamicColors.error);
}
get onError() {
return this.getArgb(MaterialDynamicColors.onError);
}
get errorContainer() {
return this.getArgb(MaterialDynamicColors.errorContainer);
}
get onErrorContainer() {
return this.getArgb(MaterialDynamicColors.onErrorContainer);
}
get primaryFixed() {
return this.getArgb(MaterialDynamicColors.primaryFixed);
}
get primaryFixedDim() {
return this.getArgb(MaterialDynamicColors.primaryFixedDim);
}
get onPrimaryFixed() {
return this.getArgb(MaterialDynamicColors.onPrimaryFixed);
}
get onPrimaryFixedVariant() {
return this.getArgb(MaterialDynamicColors.onPrimaryFixedVariant);
}
get secondaryFixed() {
return this.getArgb(MaterialDynamicColors.secondaryFixed);
}
get secondaryFixedDim() {
return this.getArgb(MaterialDynamicColors.secondaryFixedDim);
}
get onSecondaryFixed() {
return this.getArgb(MaterialDynamicColors.onSecondaryFixed);
}
get onSecondaryFixedVariant() {
return this.getArgb(MaterialDynamicColors.onSecondaryFixedVariant);
}
get tertiaryFixed() {
return this.getArgb(MaterialDynamicColors.tertiaryFixed);
}
get tertiaryFixedDim() {
return this.getArgb(MaterialDynamicColors.tertiaryFixedDim);
}
get onTertiaryFixed() {
return this.getArgb(MaterialDynamicColors.onTertiaryFixed);
}
get onTertiaryFixedVariant() {
return this.getArgb(MaterialDynamicColors.onTertiaryFixedVariant);
}
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var CorePalette = class CorePalette {
static of(argb) {
return new CorePalette(argb, false);
}
static contentOf(argb) {
return new CorePalette(argb, true);
}
static fromColors(colors) {
return CorePalette.createPaletteFromColors(false, colors);
}
static contentFromColors(colors) {
return CorePalette.createPaletteFromColors(true, colors);
}
static createPaletteFromColors(content, colors) {
const palette = new CorePalette(colors.primary, content);
if (colors.secondary) palette.a2 = new CorePalette(colors.secondary, content).a1;
if (colors.tertiary) palette.a3 = new CorePalette(colors.tertiary, content).a1;
if (colors.error) palette.error = new CorePalette(colors.error, content).a1;
if (colors.neutral) palette.n1 = new CorePalette(colors.neutral, content).n1;
if (colors.neutralVariant) palette.n2 = new CorePalette(colors.neutralVariant, content).n2;
return palette;
}
constructor(argb, isContent) {
const hct = Hct.fromInt(argb);
const hue = hct.hue;
const chroma = hct.chroma;
if (isContent) {
this.a1 = TonalPalette.fromHueAndChroma(hue, chroma);
this.a2 = TonalPalette.fromHueAndChroma(hue, chroma / 3);
this.a3 = TonalPalette.fromHueAndChroma(hue + 60, chroma / 2);
this.n1 = TonalPalette.fromHueAndChroma(hue, Math.min(chroma / 12, 4));
this.n2 = TonalPalette.fromHueAndChroma(hue, Math.min(chroma / 6, 8));
} else {
this.a1 = TonalPalette.fromHueAndChroma(hue, Math.max(48, chroma));
this.a2 = TonalPalette.fromHueAndChroma(hue, 16);
this.a3 = TonalPalette.fromHueAndChroma(hue + 60, 24);
this.n1 = TonalPalette.fromHueAndChroma(hue, 4);
this.n2 = TonalPalette.fromHueAndChroma(hue, 8);
}
this.error = TonalPalette.fromHueAndChroma(25, 84);
}
};
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Scheme = class Scheme {
get primary() {
return this.props.primary;
}
get onPrimary() {
return this.props.onPrimary;
}
get primaryContainer() {
return this.props.primaryContainer;
}
get onPrimaryContainer() {
return this.props.onPrimaryContainer;
}
get secondary() {
return this.props.secondary;
}
get onSecondary() {
return this.props.onSecondary;
}
get secondaryContainer() {
return this.props.secondaryContainer;
}
get onSecondaryContainer() {
return this.props.onSecondaryContainer;
}
get tertiary() {
return this.props.tertiary;
}
get onTertiary() {
return this.props.onTertiary;
}
get tertiaryContainer() {
return this.props.tertiaryContainer;
}
get onTertiaryContainer() {
return this.props.onTertiaryContainer;
}
get error() {
return this.props.error;
}
get onError() {
return this.props.onError;
}
get errorContainer() {
return this.props.errorContainer;
}
get onErrorContainer() {
return this.props.onErrorContainer;
}
get background() {
return this.props.background;
}
get onBackground() {
return this.props.onBackground;
}
get surface() {
return this.props.surface;
}
get onSurface() {
return this.props.onSurface;
}
get surfaceVariant() {
return this.props.surfaceVariant;
}
get onSurfaceVariant() {
return this.props.onSurfaceVariant;
}
get outline() {
return this.props.outline;
}
get outlineVariant() {
return this.props.outlineVariant;
}
get shadow() {
return this.props.shadow;
}
get scrim() {
return this.props.scrim;
}
get inverseSurface() {
return this.props.inverseSurface;
}
get inverseOnSurface() {
return this.props.inverseOnSurface;
}
get inversePrimary() {
return this.props.inversePrimary;
}
static light(argb) {
return Scheme.lightFromCorePalette(CorePalette.of(argb));
}
static dark(argb) {
return Scheme.darkFromCorePalette(CorePalette.of(argb));
}
static lightContent(argb) {
return Scheme.lightFromCorePalette(CorePalette.contentOf(argb));
}
static darkContent(argb) {
return Scheme.darkFromCorePalette(CorePalette.contentOf(argb));
}
static lightFromCorePalette(core) {
return new Scheme({
primary: core.a1.tone(40),
onPrimary: core.a1.tone(100),
primaryContainer: core.a1.tone(90),
onPrimaryContainer: core.a1.tone(10),
secondary: core.a2.tone(40),
onSecondary: core.a2.tone(100),
secondaryContainer: core.a2.tone(90),
onSecondaryContainer: core.a2.tone(10),
tertiary: core.a3.tone(40),
onTertiary: core.a3.tone(100),
tertiaryContainer: core.a3.tone(90),
onTertiaryContainer: core.a3.tone(10),
error: core.error.tone(40),
onError: core.error.tone(100),
errorContainer: core.error.tone(90),
onErrorContainer: core.error.tone(10),
background: core.n1.tone(99),
onBackground: core.n1.tone(10),
surface: core.n1.tone(99),
onSurface: core.n1.tone(10),
surfaceVariant: core.n2.tone(90),
onSurfaceVariant: core.n2.tone(30),
outline: core.n2.tone(50),
outlineVariant: core.n2.tone(80),
shadow: core.n1.tone(0),
scrim: core.n1.tone(0),
inverseSurface: core.n1.tone(20),
inverseOnSurface: core.n1.tone(95),
inversePrimary: core.a1.tone(80)
});
}
static darkFromCorePalette(core) {
return new Scheme({
primary: core.a1.tone(80),
onPrimary: core.a1.tone(20),
primaryContainer: core.a1.tone(30),
onPrimaryContainer: core.a1.tone(90),
secondary: core.a2.tone(80),
onSecondary: core.a2.tone(20),
secondaryContainer: core.a2.tone(30),
onSecondaryContainer: core.a2.tone(90),
tertiary: core.a3.tone(80),
onTertiary: core.a3.tone(20),
tertiaryContainer: core.a3.tone(30),
onTertiaryContainer: core.a3.tone(90),
error: core.error.tone(80),
onError: core.error.tone(20),
errorContainer: core.error.tone(30),
onErrorContainer: core.error.tone(80),
background: core.n1.tone(10),
onBackground: core.n1.tone(90),
surface: core.n1.tone(10),
onSurface: core.n1.tone(90),
surfaceVariant: core.n2.tone(30),
onSurfaceVariant: core.n2.tone(80),
outline: core.n2.tone(60),
outlineVariant: core.n2.tone(30),
shadow: core.n1.tone(0),
scrim: core.n1.tone(0),
inverseSurface: core.n1.tone(90),
inverseOnSurface: core.n1.tone(20),
inversePrimary: core.a1.tone(40)
});
}
constructor(props) {
this.props = props;
}
toJSON() {
return { ...this.props };
}
};
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SchemeExpressive = class SchemeExpressive extends DynamicScheme {
constructor(sourceColorHct, isDark, contrastLevel) {
super({
sourceColorArgb: sourceColorHct.toInt(),
variant: Variant.EXPRESSIVE,
contrastLevel,
isDark,
primaryPalette: TonalPalette.fromHueAndChroma(sanitizeDegreesDouble(sourceColorHct.hue + 240), 40),
secondaryPalette: TonalPalette.fromHueAndChroma(DynamicScheme.getRotatedHue(sourceColorHct, SchemeExpressive.hues, SchemeExpressive.secondaryRotations), 24),
tertiaryPalette: TonalPalette.fromHueAndChroma(DynamicScheme.getRotatedHue(sourceColorHct, SchemeExpressive.hues, SchemeExpressive.tertiaryRotations), 32),
neutralPalette: TonalPalette.fromHueAndChroma(sourceColorHct.hue + 15, 8),
neutralVariantPalette: TonalPalette.fromHueAndChroma(sourceColorHct.hue + 15, 12)
});
}
};
SchemeExpressive.hues = [
0,
21,
51,
121,
151,
191,
271,
321,
360
];
SchemeExpressive.secondaryRotations = [
45,
95,
45,
20,
45,
90,
45,
45,
45
];
SchemeExpressive.tertiaryRotations = [
120,
120,
20,
45,
20,
15,
20,
120,
120
];
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SchemeVibrant = class SchemeVibrant extends DynamicScheme {
constructor(sourceColorHct, isDark, contrastLevel) {
super({
sourceColorArgb: sourceColorHct.toInt(),
variant: Variant.VIBRANT,
contrastLevel,
isDark,
primaryPalette: TonalPalette.fromHueAndChroma(sourceColorHct.hue, 200),
secondaryPalette: TonalPalette.fromHueAndChroma(DynamicScheme.getRotatedHue(sourceColorHct, SchemeVibrant.hues, SchemeVibrant.secondaryRotations), 24),
tertiaryPalette: TonalPalette.fromHueAndChroma(DynamicScheme.getRotatedHue(sourceColorHct, SchemeVibrant.hues, SchemeVibrant.tertiaryRotations), 32),
neutralPalette: TonalPalette.fromHueAndChroma(sourceColorHct.hue, 10),
neutralVariantPalette: TonalPalette.fromHueAndChroma(sourceColorHct.hue, 12)
});
}
};
SchemeVibrant.hues = [
0,
41,
61,
101,
131,
181,
251,
301,
360
];
SchemeVibrant.secondaryRotations = [
18,
15,
10,
12,
15,
18,
15,
12,
12
];
SchemeVibrant.tertiaryRotations = [
35,
30,
20,
25,
30,
35,
30,
25,
25
];
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var SCORE_OPTION_DEFAULTS = {
desired: 4,
fallbackColorARGB: 4282549748,
filter: true
};
function compare(a, b) {
if (a.score > b.score) return -1;
else if (a.score < b.score) return 1;
return 0;
}
var Score = class Score {
constructor() {}
static score(colorsToPopulation, options) {
const { desired, fallbackColorARGB, filter } = {
...SCORE_OPTION_DEFAULTS,
...options
};
const colorsHct = [];
const huePopulation = new Array(360).fill(0);
let populationSum = 0;
for (const [argb, population] of colorsToPopulation.entries()) {
const hct = Hct.fromInt(argb);
colorsHct.push(hct);
const hue = Math.floor(hct.hue);
huePopulation[hue] += population;
populationSum += population;
}
const hueExcitedProportions = new Array(360).fill(0);
for (let hue = 0; hue < 360; hue++) {
const proportion = huePopulation[hue] / populationSum;
for (let i = hue - 14; i < hue + 16; i++) {
const neighborHue = sanitizeDegreesInt(i);
hueExcitedProportions[neighborHue] += proportion;
}
}
const scoredHct = new Array();
for (const hct of colorsHct) {
const proportion = hueExcitedProportions[sanitizeDegreesInt(Math.round(hct.hue))];
if (filter && (hct.chroma < Score.CUTOFF_CHROMA || proportion <= Score.CUTOFF_EXCITED_PROPORTION)) continue;
const proportionScore = proportion * 100 * Score.WEIGHT_PROPORTION;
const chromaWeight = hct.chroma < Score.TARGET_CHROMA ? Score.WEIGHT_CHROMA_BELOW : Score.WEIGHT_CHROMA_ABOVE;
const score = proportionScore + (hct.chroma - Score.TARGET_CHROMA) * chromaWeight;
scoredHct.push({
hct,
score
});
}
scoredHct.sort(compare);
const chosenColors = [];
for (let differenceDegrees$1 = 90; differenceDegrees$1 >= 15; differenceDegrees$1--) {
chosenColors.length = 0;
for (const { hct } of scoredHct) {
if (!chosenColors.find((chosenHct) => {
return differenceDegrees(hct.hue, chosenHct.hue) < differenceDegrees$1;
})) chosenColors.push(hct);
if (chosenColors.length >= desired) break;
}
if (chosenColors.length >= desired) break;
}
const colors = [];
if (chosenColors.length === 0) colors.push(fallbackColorARGB);
for (const chosenHct of chosenColors) colors.push(chosenHct.toInt());
return colors;
}
};
Score.TARGET_CHROMA = 48;
Score.WEIGHT_PROPORTION = .7;
Score.WEIGHT_CHROMA_ABOVE = .3;
Score.WEIGHT_CHROMA_BELOW = .1;
Score.CUTOFF_CHROMA = 5;
Score.CUTOFF_EXCITED_PROPORTION = .01;
function argbFromHex(hex) {
hex = hex.replace("#", "");
const isThree = hex.length === 3;
const isSix = hex.length === 6;
const isEight = hex.length === 8;
if (!isThree && !isSix && !isEight) throw new Error("unexpected hex " + hex);
let r = 0;
let g = 0;
let b = 0;
if (isThree) {
r = parseIntHex(hex.slice(0, 1).repeat(2));
g = parseIntHex(hex.slice(1, 2).repeat(2));
b = parseIntHex(hex.slice(2, 3).repeat(2));
} else if (isSix) {
r = parseIntHex(hex.slice(0, 2));
g = parseIntHex(hex.slice(2, 4));
b = parseIntHex(hex.slice(4, 6));
} else if (isEight) {
r = parseIntHex(hex.slice(2, 4));
g = parseIntHex(hex.slice(4, 6));
b = parseIntHex(hex.slice(6, 8));
}
return (255 << 24 | (r & 255) << 16 | (g & 255) << 8 | b & 255) >>> 0;
}
function parseIntHex(value) {
return parseInt(value, 16);
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function customColor(source, color) {
let value = color.value;
const from = value;
const to = source;
if (color.blend) value = Blend.harmonize(from, to);
const tones = CorePalette.of(value).a1;
return {
color,
value,
light: {
color: tones.tone(40),
onColor: tones.tone(100),
colorContainer: tones.tone(90),
onColorContainer: tones.tone(10)
},
dark: {
color: tones.tone(80),
onColor: tones.tone(20),
colorContainer: tones.tone(30),
onColorContainer: tones.tone(90)
}
};
}
var getConfirmText = () => {
return msg("OK", { id: "functions.prompt.confirmText" });
};
var getCancelText = () => {
return msg("Cancel", { id: "functions.prompt.cancelText" });
};
var prompt = (options) => {
const mergedOptions = Object.assign({}, {
confirmText: getConfirmText(),
cancelText: getCancelText(),
onConfirm: returnTrue,
onCancel: returnTrue,
validator: returnTrue,
textFieldOptions: {}
}, options);
const properties = [
"headline",
"description",
"icon",
"closeOnEsc",
"closeOnOverlayClick",
"stackedActions",
"queue",
"onOpen",
"onOpened",
"onClose",
"onClosed",
"onOverlayClick"
];
const textField = new TextField();
Object.entries(mergedOptions.textFieldOptions).forEach(([key, value]) => {
textField[key] = value;
});
return new Promise((resolve, reject) => {
let isResolve = false;
const dialog$1 = dialog({
...Object.fromEntries(properties.filter((key) => !isUndefined(mergedOptions[key])).map((key) => [key, mergedOptions[key]])),
body: textField,
actions: [{
text: mergedOptions.cancelText,
onClick: (dialog) => {
return mergedOptions.onCancel.call(dialog, textField.value, dialog);
}
}, {
text: mergedOptions.confirmText,
onClick: (dialog) => {
const onConfirm = () => {
const clickResult = mergedOptions.onConfirm.call(dialog, textField.value, dialog);
if (isPromise(clickResult)) clickResult.then(() => {
isResolve = true;
});
else if (clickResult !== false) isResolve = true;
return clickResult;
};
textField.setCustomValidity("");
if (!textField.reportValidity()) return false;
const validateResult = mergedOptions.validator.call(textField, textField.value);
if (isBoolean(validateResult) && !validateResult) {
textField.setCustomValidity(" ");
return false;
}
if (isString(validateResult)) {
textField.setCustomValidity(validateResult);
return false;
}
if (isPromise(validateResult)) return new Promise((resolve, reject) => {
validateResult.then(resolve).catch((reason) => {
textField.setCustomValidity(reason);
reject(reason);
});
});
return onConfirm();
}
}]
});
if (!options.confirmText) onLocaleReady(dialog$1, () => {
$$1(dialog$1).find("[slot=\"action\"]").last().text(getConfirmText());
});
if (!options.cancelText) onLocaleReady(dialog$1, () => {
$$1(dialog$1).find("[slot=\"action\"]").first().text(getCancelText());
});
$$1(dialog$1).on("close", (e) => {
if (e.target === dialog$1) {
if (isResolve) resolve(textField.value);
else reject();
offLocaleReady(dialog$1);
}
});
});
};
var themeArr = ["light", "dark"];
var prefix = "mdui-custom-color-scheme-";
var themeIndex = 0;
var rgbFromArgb = (source) => {
return [
redFromArgb(source),
greenFromArgb(source),
blueFromArgb(source)
].join(", ");
};
var remove = (target) => {
const $target = $$1(target);
let classNames = $target.get().map((element) => Array.from(element.classList)).flat();
classNames = unique(classNames).filter((className) => className.startsWith(prefix));
$target.removeClass(classNames.join(" "));
$$1(classNames.filter((className) => $$1(`.${className}`).length === 0).map((i) => `#${i}`).join(",")).remove();
};
var setFromSource = (source, options) => {
const document = getDocument();
const $target = $$1(options?.target || document.documentElement);
const schemes = {
light: Scheme.light(source).toJSON(),
dark: Scheme.dark(source).toJSON()
};
const palette = CorePalette.of(source);
Object.assign(schemes.light, {
"surface-dim": palette.n1.tone(87),
"surface-bright": palette.n1.tone(98),
"surface-container-lowest": palette.n1.tone(100),
"surface-container-low": palette.n1.tone(96),
"surface-container": palette.n1.tone(94),
"surface-container-high": palette.n1.tone(92),
"surface-container-highest": palette.n1.tone(90),
"surface-tint-color": schemes.light.primary
});
Object.assign(schemes.dark, {
"surface-dim": palette.n1.tone(6),
"surface-bright": palette.n1.tone(24),
"surface-container-lowest": palette.n1.tone(4),
"surface-container-low": palette.n1.tone(10),
"surface-container": palette.n1.tone(12),
"surface-container-high": palette.n1.tone(17),
"surface-container-highest": palette.n1.tone(22),
"surface-tint-color": schemes.dark.primary
});
(options?.customColors || []).map((color) => {
const name = toKebabCase(color.name);
const custom = customColor(source, {
name,
value: argbFromHex(color.value),
blend: true
});
themeArr.forEach((theme) => {
schemes[theme][name] = custom[theme].color;
schemes[theme][`on-${name}`] = custom[theme].onColor;
schemes[theme][`${name}-container`] = custom[theme].colorContainer;
schemes[theme][`on-${name}-container`] = custom[theme].onColorContainer;
});
});
const colorVar = (theme, callback) => {
return Object.entries(schemes[theme]).map(([key, value]) => callback(toKebabCase(key), rgbFromArgb(value))).join("");
};
const className = `mdui-custom-color-scheme-${source}-${themeIndex++}`;
const cssText = `.${className} {
${colorVar("light", (token, rgb) => `--mdui-color-${token}-light: ${rgb};`)}
${colorVar("dark", (token, rgb) => `--mdui-color-${token}-dark: ${rgb};`)}
${colorVar("light", (token) => `--mdui-color-${token}: var(--mdui-color-${token}-light);`)}
color: rgb(var(--mdui-color-on-background));
background-color: rgb(var(--mdui-color-background));
}
.mdui-theme-dark .${className},
.mdui-theme-dark.${className} {
${colorVar("dark", (token) => `--mdui-color-${token}: var(--mdui-color-${token}-dark);`)}
}
@media (prefers-color-scheme: dark) {
.mdui-theme-auto .${className},
.mdui-theme-auto.${className} {
${colorVar("dark", (token) => `--mdui-color-${token}: var(--mdui-color-${token}-dark);`)}
}
}`;
remove($target);
$$1(document.head).append(``);
$target.addClass(className);
};
var setColorScheme = (hex, options) => {
setFromSource(argbFromHex(hex), options);
};
var queueName = "mdui.functions.snackbar.";
var currentSnackbar = void 0;
var snackbar = (options) => {
const snackbar = new Snackbar();
const $snackbar = $$1(snackbar);
Object.entries(options).forEach(([key, value]) => {
if (key === "message") snackbar.innerHTML = value;
else if ([
"onClick",
"onActionClick",
"onOpen",
"onOpened",
"onClose",
"onClosed"
].includes(key)) {
const eventName = toKebabCase(key.slice(2));
$snackbar.on(eventName, (e) => {
if (e.target !== snackbar) return;
if (key === "onActionClick") {
const actionClick = (options.onActionClick ?? returnTrue).call(snackbar, snackbar);
if (isPromise(actionClick)) {
snackbar.actionLoading = true;
actionClick.then(() => {
snackbar.open = false;
}).finally(() => {
snackbar.actionLoading = false;
});
} else if (actionClick !== false) snackbar.open = false;
} else value.call(snackbar, snackbar);
});
} else snackbar[key] = value;
});
$snackbar.appendTo("body").on("closed", (e) => {
if (e.target !== snackbar) return;
$snackbar.remove();
if (options.queue) {
currentSnackbar = void 0;
dequeue(queueName + options.queue);
}
});
if (!options.queue) setTimeout(() => {
snackbar.open = true;
});
else if (currentSnackbar) queue(queueName + options.queue, () => {
snackbar.open = true;
currentSnackbar = snackbar;
});
else {
setTimeout(() => {
snackbar.open = true;
});
currentSnackbar = snackbar;
}
return snackbar;
};
var require_localforage = __commonJSMin(((exports, module) => {
(function(f) {
if (typeof exports === "object" && typeof module !== "undefined") module.exports = f();
else if (typeof define === "function" && define.amd) define([], f);
else {
var g;
if (typeof window !== "undefined") g = window;
else if (typeof global !== "undefined") g = global;
else if (typeof self !== "undefined") g = self;
else g = this;
g.localforage = f();
}
})(function() {
return (function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof __require == "function" && __require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw f.code = "MODULE_NOT_FOUND", f;
}
var l = n[o] = { exports: {} };
t[o][0].call(l.exports, function(e) {
var n = t[o][1][e];
return s(n ? n : e);
}, l, l.exports, e, t, n, r);
}
return n[o].exports;
}
var i = typeof __require == "function" && __require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
})({
1: [function(_dereq_, module$6, exports$2) {
(function(global) {
"use strict";
var Mutation = global.MutationObserver || global.WebKitMutationObserver;
var scheduleDrain;
if (Mutation) {
var called = 0;
var observer = new Mutation(nextTick);
var element = global.document.createTextNode("");
observer.observe(element, { characterData: true });
scheduleDrain = function() {
element.data = called = ++called % 2;
};
} else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") {
var channel = new global.MessageChannel();
channel.port1.onmessage = nextTick;
scheduleDrain = function() {
channel.port2.postMessage(0);
};
} else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) scheduleDrain = function() {
var scriptEl = global.document.createElement("script");
scriptEl.onreadystatechange = function() {
nextTick();
scriptEl.onreadystatechange = null;
scriptEl.parentNode.removeChild(scriptEl);
scriptEl = null;
};
global.document.documentElement.appendChild(scriptEl);
};
else scheduleDrain = function() {
setTimeout(nextTick, 0);
};
var draining;
var queue = [];
function nextTick() {
draining = true;
var i, oldQueue;
var len = queue.length;
while (len) {
oldQueue = queue;
queue = [];
i = -1;
while (++i < len) oldQueue[i]();
len = queue.length;
}
draining = false;
}
module$6.exports = immediate;
function immediate(task) {
if (queue.push(task) === 1 && !draining) scheduleDrain();
}
}).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
}, {}],
2: [function(_dereq_, module$7, exports$3) {
"use strict";
var immediate = _dereq_(1);
function INTERNAL() {}
var handlers = {};
var REJECTED = ["REJECTED"];
var FULFILLED = ["FULFILLED"];
var PENDING = ["PENDING"];
module$7.exports = Promise;
function Promise(resolver) {
if (typeof resolver !== "function") throw new TypeError("resolver must be a function");
this.state = PENDING;
this.queue = [];
this.outcome = void 0;
if (resolver !== INTERNAL) safelyResolveThenable(this, resolver);
}
Promise.prototype["catch"] = function(onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function(onFulfilled, onRejected) {
if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) return this;
var promise = new this.constructor(INTERNAL);
if (this.state !== PENDING) unwrap(promise, this.state === FULFILLED ? onFulfilled : onRejected, this.outcome);
else this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
return promise;
};
function QueueItem(promise, onFulfilled, onRejected) {
this.promise = promise;
if (typeof onFulfilled === "function") {
this.onFulfilled = onFulfilled;
this.callFulfilled = this.otherCallFulfilled;
}
if (typeof onRejected === "function") {
this.onRejected = onRejected;
this.callRejected = this.otherCallRejected;
}
}
QueueItem.prototype.callFulfilled = function(value) {
handlers.resolve(this.promise, value);
};
QueueItem.prototype.otherCallFulfilled = function(value) {
unwrap(this.promise, this.onFulfilled, value);
};
QueueItem.prototype.callRejected = function(value) {
handlers.reject(this.promise, value);
};
QueueItem.prototype.otherCallRejected = function(value) {
unwrap(this.promise, this.onRejected, value);
};
function unwrap(promise, func, value) {
immediate(function() {
var returnValue;
try {
returnValue = func(value);
} catch (e) {
return handlers.reject(promise, e);
}
if (returnValue === promise) handlers.reject(promise, new TypeError("Cannot resolve promise with itself"));
else handlers.resolve(promise, returnValue);
});
}
handlers.resolve = function(self, value) {
var result = tryCatch(getThen, value);
if (result.status === "error") return handlers.reject(self, result.value);
var thenable = result.value;
if (thenable) safelyResolveThenable(self, thenable);
else {
self.state = FULFILLED;
self.outcome = value;
var i = -1;
var len = self.queue.length;
while (++i < len) self.queue[i].callFulfilled(value);
}
return self;
};
handlers.reject = function(self, error) {
self.state = REJECTED;
self.outcome = error;
var i = -1;
var len = self.queue.length;
while (++i < len) self.queue[i].callRejected(error);
return self;
};
function getThen(obj) {
var then = obj && obj.then;
if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") return function appyThen() {
then.apply(obj, arguments);
};
}
function safelyResolveThenable(self, thenable) {
var called = false;
function onError(value) {
if (called) return;
called = true;
handlers.reject(self, value);
}
function onSuccess(value) {
if (called) return;
called = true;
handlers.resolve(self, value);
}
function tryToUnwrap() {
thenable(onSuccess, onError);
}
var result = tryCatch(tryToUnwrap);
if (result.status === "error") onError(result.value);
}
function tryCatch(func, value) {
var out = {};
try {
out.value = func(value);
out.status = "success";
} catch (e) {
out.status = "error";
out.value = e;
}
return out;
}
Promise.resolve = resolve;
function resolve(value) {
if (value instanceof this) return value;
return handlers.resolve(new this(INTERNAL), value);
}
Promise.reject = reject;
function reject(reason) {
var promise = new this(INTERNAL);
return handlers.reject(promise, reason);
}
Promise.all = all;
function all(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== "[object Array]") return this.reject( new TypeError("must be an array"));
var len = iterable.length;
var called = false;
if (!len) return this.resolve([]);
var values = new Array(len);
var resolved = 0;
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) allResolver(iterable[i], i);
return promise;
function allResolver(value, i) {
self.resolve(value).then(resolveFromAll, function(error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
function resolveFromAll(outValue) {
values[i] = outValue;
if (++resolved === len && !called) {
called = true;
handlers.resolve(promise, values);
}
}
}
}
Promise.race = race;
function race(iterable) {
var self = this;
if (Object.prototype.toString.call(iterable) !== "[object Array]") return this.reject( new TypeError("must be an array"));
var len = iterable.length;
var called = false;
if (!len) return this.resolve([]);
var i = -1;
var promise = new this(INTERNAL);
while (++i < len) resolver(iterable[i]);
return promise;
function resolver(value) {
self.resolve(value).then(function(response) {
if (!called) {
called = true;
handlers.resolve(promise, response);
}
}, function(error) {
if (!called) {
called = true;
handlers.reject(promise, error);
}
});
}
}
}, { "1": 1 }],
3: [function(_dereq_, module$8, exports$4) {
(function(global) {
"use strict";
if (typeof global.Promise !== "function") global.Promise = _dereq_(2);
}).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
}, { "2": 2 }],
4: [function(_dereq_, module$9, exports$5) {
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function getIDB() {
try {
if (typeof indexedDB !== "undefined") return indexedDB;
if (typeof webkitIndexedDB !== "undefined") return webkitIndexedDB;
if (typeof mozIndexedDB !== "undefined") return mozIndexedDB;
if (typeof OIndexedDB !== "undefined") return OIndexedDB;
if (typeof msIndexedDB !== "undefined") return msIndexedDB;
} catch (e) {
return;
}
}
var idb = getIDB();
function isIndexedDBValid() {
try {
if (!idb || !idb.open) return false;
var isSafari = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1;
return (!isSafari || hasFetch) && typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined";
} catch (e) {
return false;
}
}
function createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== "TypeError") throw e;
var builder = new (typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder)();
for (var i = 0; i < parts.length; i += 1) builder.append(parts[i]);
return builder.getBlob(properties.type);
}
}
if (typeof Promise === "undefined") _dereq_(3);
var Promise$1 = Promise;
function executeCallback(promise, callback) {
if (callback) promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
function executeTwoCallbacks(promise, callback, errorCallback) {
if (typeof callback === "function") promise.then(callback);
if (typeof errorCallback === "function") promise["catch"](errorCallback);
}
function normalizeKey(key) {
if (typeof key !== "string") {
console.warn(key + " used as a key, but it is not a string.");
key = String(key);
}
return key;
}
function getCallback() {
if (arguments.length && typeof arguments[arguments.length - 1] === "function") return arguments[arguments.length - 1];
}
var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support";
var supportsBlobs = void 0;
var dbContexts = {};
var toString = Object.prototype.toString;
var READ_ONLY = "readonly";
var READ_WRITE = "readwrite";
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) arr[i] = bin.charCodeAt(i);
return buf;
}
function _checkBlobSupportWithoutCaching(idb) {
return new Promise$1(function(resolve) {
var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
var blob = createBlob([""]);
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key");
txn.onabort = function(e) {
e.preventDefault();
e.stopPropagation();
resolve(false);
};
txn.oncomplete = function() {
var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
resolve(navigator.userAgent.match(/Edge\//) || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
};
})["catch"](function() {
return false;
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === "boolean") return Promise$1.resolve(supportsBlobs);
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
var deferredOperation = {};
deferredOperation.promise = new Promise$1(function(resolve, reject) {
deferredOperation.resolve = resolve;
deferredOperation.reject = reject;
});
dbContext.deferredOperations.push(deferredOperation);
if (!dbContext.dbReady) dbContext.dbReady = deferredOperation.promise;
else dbContext.dbReady = dbContext.dbReady.then(function() {
return deferredOperation.promise;
});
}
function _advanceReadiness(dbInfo) {
var deferredOperation = dbContexts[dbInfo.name].deferredOperations.pop();
if (deferredOperation) {
deferredOperation.resolve();
return deferredOperation.promise;
}
}
function _rejectReadiness(dbInfo, err) {
var deferredOperation = dbContexts[dbInfo.name].deferredOperations.pop();
if (deferredOperation) {
deferredOperation.reject(err);
return deferredOperation.promise;
}
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise$1(function(resolve, reject) {
dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
if (dbInfo.db) if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else return resolve(dbInfo.db);
var dbArgs = [dbInfo.name];
if (upgradeNeeded) dbArgs.push(dbInfo.version);
var openreq = idb.open.apply(idb, dbArgs);
if (upgradeNeeded) openreq.onupgradeneeded = function(e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
} catch (ex) {
if (ex.name === "ConstraintError") console.warn("The database \"" + dbInfo.name + "\" has been upgraded from version " + e.oldVersion + " to version " + e.newVersion + ", but the storage \"" + dbInfo.storeName + "\" already exists.");
else throw ex;
}
};
openreq.onerror = function(e) {
e.preventDefault();
reject(openreq.error);
};
openreq.onsuccess = function() {
var db = openreq.result;
db.onversionchange = function(e) {
e.target.close();
};
resolve(db);
_advanceReadiness(dbInfo);
};
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) return true;
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
if (dbInfo.version !== defaultVersion) console.warn("The database \"" + dbInfo.name + "\" can't be downgraded from version " + dbInfo.db.version + " to version " + dbInfo.version + ".");
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) dbInfo.version = incVersion;
}
return true;
}
return false;
}
function _encodeBlob(blob) {
return new Promise$1(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
resolve({
__local_forage_encoded_blob: true,
data: btoa(e.target.result || ""),
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
function _decodeBlob(encodedBlob) {
return createBlob([_binStringToArrayBuffer(atob(encodedBlob.data))], { type: encodedBlob.type });
}
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function() {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) return dbContext.dbReady;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
}
function _tryReconnect(dbInfo) {
_deferReadiness(dbInfo);
var dbContext = dbContexts[dbInfo.name];
var forages = dbContext.forages;
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
if (forage._dbInfo.db) {
forage._dbInfo.db.close();
forage._dbInfo.db = null;
}
}
dbInfo.db = null;
return _getOriginalConnection(dbInfo).then(function(db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo)) return _getUpgradedConnection(dbInfo);
return db;
}).then(function(db) {
dbInfo.db = dbContext.db = db;
for (var i = 0; i < forages.length; i++) forages[i]._dbInfo.db = db;
})["catch"](function(err) {
_rejectReadiness(dbInfo, err);
throw err;
});
}
function createTransaction(dbInfo, mode, callback, retries) {
if (retries === void 0) retries = 1;
try {
callback(null, dbInfo.db.transaction(dbInfo.storeName, mode));
} catch (err) {
if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) return Promise$1.resolve().then(function() {
if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
if (dbInfo.db) dbInfo.version = dbInfo.db.version + 1;
return _getUpgradedConnection(dbInfo);
}
}).then(function() {
return _tryReconnect(dbInfo).then(function() {
createTransaction(dbInfo, mode, callback, retries - 1);
});
})["catch"](callback);
callback(err);
}
}
function createDbContext() {
return {
forages: [],
db: null,
dbReady: null,
deferredOperations: []
};
}
function _initStorage(options) {
var self = this;
var dbInfo = { db: null };
if (options) for (var i in options) dbInfo[i] = options[i];
var dbContext = dbContexts[dbInfo.name];
if (!dbContext) {
dbContext = createDbContext();
dbContexts[dbInfo.name] = dbContext;
}
dbContext.forages.push(self);
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
var initPromises = [];
function ignoreErrors() {
return Promise$1.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) initPromises.push(forage._initReady()["catch"](ignoreErrors));
}
var forages = dbContext.forages.slice(0);
return Promise$1.all(initPromises).then(function() {
dbInfo.db = dbContext.db;
return _getOriginalConnection(dbInfo);
}).then(function(db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) return _getUpgradedConnection(dbInfo);
return db;
}).then(function(db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function getItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_ONLY, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName).get(key);
req.onsuccess = function() {
var value = req.result;
if (value === void 0) value = null;
if (_isEncodedBlob(value)) value = _decodeBlob(value);
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_ONLY, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName).openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) value = _decodeBlob(value);
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) resolve(result);
else cursor["continue"]();
} else resolve();
};
req.onerror = function() {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
if (toString.call(value) === "[object Blob]") return _checkBlobSupport(dbInfo.db).then(function(blobSupport) {
if (blobSupport) return value;
return _encodeBlob(value);
});
return value;
}).then(function(value) {
createTransaction(self._dbInfo, READ_WRITE, function(err, transaction) {
if (err) return reject(err);
try {
var store = transaction.objectStore(self._dbInfo.storeName);
if (value === null) value = void 0;
var req = store.put(value, key);
transaction.oncomplete = function() {
if (value === void 0) value = null;
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
reject(req.error ? req.error : req.transaction.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_WRITE, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName)["delete"](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
transaction.onabort = function() {
reject(req.error ? req.error : req.transaction.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_WRITE, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName).clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
reject(req.error ? req.error : req.transaction.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_ONLY, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName).count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
createTransaction(self._dbInfo, READ_ONLY, function(err, transaction) {
if (err) return reject(err);
try {
var store = transaction.objectStore(self._dbInfo.storeName);
var advanced = false;
var req = store.openKeyCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(null);
return;
}
if (n === 0) resolve(cursor.key);
else if (!advanced) {
advanced = true;
cursor.advance(n);
} else resolve(cursor.key);
};
req.onerror = function() {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
createTransaction(self._dbInfo, READ_ONLY, function(err, transaction) {
if (err) return reject(err);
try {
var req = transaction.objectStore(self._dbInfo.storeName).openKeyCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor["continue"]();
};
req.onerror = function() {
reject(req.error);
};
} catch (e) {
reject(e);
}
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function dropInstance(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== "function" && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) promise = Promise$1.reject("Invalid arguments");
else {
var dbPromise = options.name === currentConfig.name && self._dbInfo.db ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function(db) {
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
dbContext.db = db;
for (var i = 0; i < forages.length; i++) forages[i]._dbInfo.db = db;
return db;
});
if (!options.storeName) promise = dbPromise.then(function(db) {
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
}
return new Promise$1(function(resolve, reject) {
var req = idb.deleteDatabase(options.name);
req.onerror = function() {
var db = req.result;
if (db) db.close();
reject(req.error);
};
req.onblocked = function() {
console.warn("dropInstance blocked for database \"" + options.name + "\" until all open connections are closed");
};
req.onsuccess = function() {
var db = req.result;
if (db) db.close();
resolve(db);
};
}).then(function(db) {
dbContext.db = db;
for (var i = 0; i < forages.length; i++) {
var _forage = forages[i];
_advanceReadiness(_forage._dbInfo);
}
})["catch"](function(err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {});
throw err;
});
});
else promise = dbPromise.then(function(db) {
if (!db.objectStoreNames.contains(options.storeName)) return;
var newVersion = db.version + 1;
_deferReadiness(options);
var dbContext = dbContexts[options.name];
var forages = dbContext.forages;
db.close();
for (var i = 0; i < forages.length; i++) {
var forage = forages[i];
forage._dbInfo.db = null;
forage._dbInfo.version = newVersion;
}
return new Promise$1(function(resolve, reject) {
var req = idb.open(options.name, newVersion);
req.onerror = function(err) {
req.result.close();
reject(err);
};
req.onupgradeneeded = function() {
req.result.deleteObjectStore(options.storeName);
};
req.onsuccess = function() {
var db = req.result;
db.close();
resolve(db);
};
}).then(function(db) {
dbContext.db = db;
for (var j = 0; j < forages.length; j++) {
var _forage2 = forages[j];
_forage2._dbInfo.db = db;
_advanceReadiness(_forage2._dbInfo);
}
})["catch"](function(err) {
(_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() {});
throw err;
});
});
}
executeCallback(promise, callback);
return promise;
}
var asyncStorage = {
_driver: "asyncStorage",
_initStorage,
_support: isIndexedDBValid(),
iterate,
getItem,
setItem,
removeItem,
clear,
length,
key,
keys,
dropInstance
};
function isWebSQLValid() {
return typeof openDatabase === "function";
}
var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var BLOB_TYPE_PREFIX = "~~local_forage_type~";
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = "__lfsc__:";
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
var TYPE_ARRAYBUFFER = "arbf";
var TYPE_BLOB = "blob";
var TYPE_INT8ARRAY = "si08";
var TYPE_UINT8ARRAY = "ui08";
var TYPE_UINT8CLAMPEDARRAY = "uic8";
var TYPE_INT16ARRAY = "si16";
var TYPE_INT32ARRAY = "si32";
var TYPE_UINT16ARRAY = "ur16";
var TYPE_UINT32ARRAY = "ui32";
var TYPE_FLOAT32ARRAY = "fl32";
var TYPE_FLOAT64ARRAY = "fl64";
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
var toString$1 = Object.prototype.toString;
function stringToBuffer(serializedString) {
var bufferLength = serializedString.length * .75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === "=") {
bufferLength--;
if (serializedString[serializedString.length - 2] === "=") bufferLength--;
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
function bufferToString(buffer) {
var bytes = new Uint8Array(buffer);
var base64String = "";
var i;
for (i = 0; i < bytes.length; i += 3) {
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) base64String = base64String.substring(0, base64String.length - 1) + "=";
else if (bytes.length % 3 === 1) base64String = base64String.substring(0, base64String.length - 2) + "==";
return base64String;
}
function serialize(value, callback) {
var valueType = "";
if (value) valueType = toString$1.call(value);
if (value && (valueType === "[object ArrayBuffer]" || value.buffer && toString$1.call(value.buffer) === "[object ArrayBuffer]")) {
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueType === "[object Int8Array]") marker += TYPE_INT8ARRAY;
else if (valueType === "[object Uint8Array]") marker += TYPE_UINT8ARRAY;
else if (valueType === "[object Uint8ClampedArray]") marker += TYPE_UINT8CLAMPEDARRAY;
else if (valueType === "[object Int16Array]") marker += TYPE_INT16ARRAY;
else if (valueType === "[object Uint16Array]") marker += TYPE_UINT16ARRAY;
else if (valueType === "[object Int32Array]") marker += TYPE_INT32ARRAY;
else if (valueType === "[object Uint32Array]") marker += TYPE_UINT32ARRAY;
else if (valueType === "[object Float32Array]") marker += TYPE_FLOAT32ARRAY;
else if (valueType === "[object Float64Array]") marker += TYPE_FLOAT64ARRAY;
else callback( new Error("Failed to get type for BinaryArray"));
}
callback(marker + bufferToString(buffer));
} else if (valueType === "[object Blob]") {
var fileReader = new FileReader();
fileReader.onload = function() {
var str = BLOB_TYPE_PREFIX + value.type + "~" + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
function deserialize(value) {
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) return JSON.parse(value);
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
switch (type) {
case TYPE_ARRAYBUFFER: return buffer;
case TYPE_BLOB: return createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY: return new Int8Array(buffer);
case TYPE_UINT8ARRAY: return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY: return new Int16Array(buffer);
case TYPE_UINT16ARRAY: return new Uint16Array(buffer);
case TYPE_INT32ARRAY: return new Int32Array(buffer);
case TYPE_UINT32ARRAY: return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY: return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY: return new Float64Array(buffer);
default: throw new Error("Unkown type: " + type);
}
}
var localforageSerializer = {
serialize,
deserialize,
stringToBuffer,
bufferToString
};
function createDbTable(t, dbInfo, callback, errorCallback) {
t.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " (id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback);
}
function _initStorage$1(options) {
var self = this;
var dbInfo = { db: null };
if (options) for (var i in options) dbInfo[i] = typeof options[i] !== "string" ? options[i].toString() : options[i];
var dbInfoPromise = new Promise$1(function(resolve, reject) {
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
dbInfo.db.transaction(function(t) {
createDbTable(t, dbInfo, function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
}, reject);
});
dbInfo.serializer = localforageSerializer;
return dbInfoPromise;
}
function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
t.executeSql(sqlStatement, args, callback, function(t, error) {
if (error.code === error.SYNTAX_ERR) t.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?", [dbInfo.storeName], function(t, results) {
if (!results.rows.length) createDbTable(t, dbInfo, function() {
t.executeSql(sqlStatement, args, callback, errorCallback);
}, errorCallback);
else errorCallback(t, error);
}, errorCallback);
else errorCallback(t, error);
}, errorCallback);
}
function getItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key], function(t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
if (result) result = dbInfo.serializer.deserialize(result);
resolve(result);
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate$1(iterator, callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
if (result) result = dbInfo.serializer.deserialize(result);
result = iterator(result, item.key, i + 1);
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function _setItem(key, value, callback, retriesLeft) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
if (value === void 0) value = null;
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function(value, error) {
if (error) reject(error);
else dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " (key, value) VALUES (?, ?)", [key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
if (sqlError.code === sqlError.QUOTA_ERR) {
if (retriesLeft > 0) {
resolve(_setItem.apply(self, [
key,
originalValue,
callback,
retriesLeft - 1
]));
return;
}
reject(sqlError);
}
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem$1(key, value, callback) {
return _setItem.apply(this, [
key,
value,
callback,
1
]);
}
function removeItem$1(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key], function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear$1(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function length$1(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function key$1(n, callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n + 1], function(t, results) {
resolve(results.rows.length ? results.rows.item(0).key : null);
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys$1(callback) {
var self = this;
var promise = new Promise$1(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) keys.push(results.rows.item(i).key);
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})["catch"](reject);
});
executeCallback(promise, callback);
return promise;
}
function getAllStoreNames(db) {
return new Promise$1(function(resolve, reject) {
db.transaction(function(t) {
t.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t, results) {
var storeNames = [];
for (var i = 0; i < results.rows.length; i++) storeNames.push(results.rows.item(i).name);
resolve({
db,
storeNames
});
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
reject(sqlError);
});
});
}
function dropInstance$1(options, callback) {
callback = getCallback.apply(this, arguments);
var currentConfig = this.config();
options = typeof options !== "function" && options || {};
if (!options.name) {
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) promise = Promise$1.reject("Invalid arguments");
else promise = new Promise$1(function(resolve) {
var db;
if (options.name === currentConfig.name) db = self._dbInfo.db;
else db = openDatabase(options.name, "", "", 0);
if (!options.storeName) resolve(getAllStoreNames(db));
else resolve({
db,
storeNames: [options.storeName]
});
}).then(function(operationInfo) {
return new Promise$1(function(resolve, reject) {
operationInfo.db.transaction(function(t) {
function dropTable(storeName) {
return new Promise$1(function(resolve, reject) {
t.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() {
resolve();
}, function(t, error) {
reject(error);
});
});
}
var operations = [];
for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) operations.push(dropTable(operationInfo.storeNames[i]));
Promise$1.all(operations).then(function() {
resolve();
})["catch"](function(e) {
reject(e);
});
}, function(sqlError) {
reject(sqlError);
});
});
});
executeCallback(promise, callback);
return promise;
}
var webSQLStorage = {
_driver: "webSQLStorage",
_initStorage: _initStorage$1,
_support: isWebSQLValid(),
iterate: iterate$1,
getItem: getItem$1,
setItem: setItem$1,
removeItem: removeItem$1,
clear: clear$1,
length: length$1,
key: key$1,
keys: keys$1,
dropInstance: dropInstance$1
};
function isLocalStorageValid() {
try {
return typeof localStorage !== "undefined" && "setItem" in localStorage && !!localStorage.setItem;
} catch (e) {
return false;
}
}
function _getKeyPrefix(options, defaultConfig) {
var keyPrefix = options.name + "/";
if (options.storeName !== defaultConfig.storeName) keyPrefix += options.storeName + "/";
return keyPrefix;
}
function checkIfLocalStorageThrows() {
var localStorageTestKey = "_localforage_support_test";
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
}
function _isLocalStorageUsable() {
return !checkIfLocalStorageThrows() || localStorage.length > 0;
}
function _initStorage$2(options) {
var self = this;
var dbInfo = {};
if (options) for (var i in options) dbInfo[i] = options[i];
dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
if (!_isLocalStorageUsable()) return Promise$1.reject();
self._dbInfo = dbInfo;
dbInfo.serializer = localforageSerializer;
return Promise$1.resolve();
}
function clear$2(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) localStorage.removeItem(key);
}
});
executeCallback(promise, callback);
return promise;
}
function getItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
if (result) result = dbInfo.serializer.deserialize(result);
return result;
});
executeCallback(promise, callback);
return promise;
}
function iterate$2(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) continue;
var value = localStorage.getItem(key);
if (value) value = dbInfo.serializer.deserialize(value);
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) return value;
}
});
executeCallback(promise, callback);
return promise;
}
function key$2(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
if (result) result = result.substring(dbInfo.keyPrefix.length);
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys$2(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
var itemKey = localStorage.key(i);
if (itemKey.indexOf(dbInfo.keyPrefix) === 0) keys.push(itemKey.substring(dbInfo.keyPrefix.length));
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
function length$2(callback) {
var promise = this.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
function removeItem$2(key, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
function setItem$2(key, value, callback) {
var self = this;
key = normalizeKey(key);
var promise = self.ready().then(function() {
if (value === void 0) value = null;
var originalValue = value;
return new Promise$1(function(resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function(value, error) {
if (error) reject(error);
else try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") reject(e);
reject(e);
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function dropInstance$2(options, callback) {
callback = getCallback.apply(this, arguments);
options = typeof options !== "function" && options || {};
if (!options.name) {
var currentConfig = this.config();
options.name = options.name || currentConfig.name;
options.storeName = options.storeName || currentConfig.storeName;
}
var self = this;
var promise;
if (!options.name) promise = Promise$1.reject("Invalid arguments");
else promise = new Promise$1(function(resolve) {
if (!options.storeName) resolve(options.name + "/");
else resolve(_getKeyPrefix(options, self._defaultConfig));
}).then(function(keyPrefix) {
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) localStorage.removeItem(key);
}
});
executeCallback(promise, callback);
return promise;
}
var localStorageWrapper = {
_driver: "localStorageWrapper",
_initStorage: _initStorage$2,
_support: isLocalStorageValid(),
iterate: iterate$2,
getItem: getItem$2,
setItem: setItem$2,
removeItem: removeItem$2,
clear: clear$2,
length: length$2,
key: key$2,
keys: keys$2,
dropInstance: dropInstance$2
};
var sameValue = function sameValue(x, y) {
return x === y || typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y);
};
var includes = function includes(array, searchElement) {
var len = array.length;
var i = 0;
while (i < len) {
if (sameValue(array[i], searchElement)) return true;
i++;
}
return false;
};
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === "[object Array]";
};
var DefinedDrivers = {};
var DriverSupport = {};
var DefaultDrivers = {
INDEXEDDB: asyncStorage,
WEBSQL: webSQLStorage,
LOCALSTORAGE: localStorageWrapper
};
var DefaultDriverOrder = [
DefaultDrivers.INDEXEDDB._driver,
DefaultDrivers.WEBSQL._driver,
DefaultDrivers.LOCALSTORAGE._driver
];
var OptionalDriverMethods = ["dropInstance"];
var LibraryMethods = [
"clear",
"getItem",
"iterate",
"key",
"keys",
"length",
"removeItem",
"setItem"
].concat(OptionalDriverMethods);
var DefaultConfig = {
description: "",
driver: DefaultDriverOrder.slice(),
name: "localforage",
size: 4980736,
storeName: "keyvaluepairs",
version: 1
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var _key in arg) if (arg.hasOwnProperty(_key)) if (isArray(arg[_key])) arguments[0][_key] = arg[_key].slice();
else arguments[0][_key] = arg[_key];
}
}
return arguments[0];
}
module$9.exports = new (function() {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
for (var driverTypeKey in DefaultDrivers) if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
var driver = DefaultDrivers[driverTypeKey];
var driverName = driver._driver;
this[driverTypeKey] = driverName;
if (!DefinedDrivers[driverName]) this.defineDriver(driver);
}
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver)["catch"](function() {});
}
LocalForage.prototype.config = function config(options) {
if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") {
if (this._ready) return new Error("Can't call config() after localforage has been used.");
for (var i in options) {
if (i === "storeName") options[i] = options[i].replace(/\W/g, "_");
if (i === "version" && typeof options[i] !== "number") return new Error("Database version must be a number.");
this._config[i] = options[i];
}
if ("driver" in options && options.driver) return this.setDriver(this._config.driver);
return true;
} else if (typeof options === "string") return this._config[options];
else return this._config;
};
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise$1(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");
if (!driverObject._driver) {
reject(complianceError);
return;
}
var driverMethods = LibraryMethods.concat("_initStorage");
for (var i = 0, len = driverMethods.length; i < len; i++) {
var driverMethodName = driverMethods[i];
if ((!includes(OptionalDriverMethods, driverMethodName) || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") {
reject(complianceError);
return;
}
}
(function configureMissingMethods() {
var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
return function() {
var error = new Error("Method " + methodName + " is not implemented by the current driver");
var promise = Promise$1.reject(error);
executeCallback(promise, arguments[arguments.length - 1]);
return promise;
};
};
for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
var optionalDriverMethod = OptionalDriverMethods[_i];
if (!driverObject[optionalDriverMethod]) driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
}
})();
var setDriverSupport = function setDriverSupport(support) {
if (DefinedDrivers[driverName]) console.info("Redefining LocalForage driver: " + driverName);
DefinedDrivers[driverName] = driverObject;
DriverSupport[driverName] = support;
resolve();
};
if ("_support" in driverObject) if (driverObject._support && typeof driverObject._support === "function") driverObject._support().then(setDriverSupport, reject);
else setDriverSupport(!!driverObject._support);
else setDriverSupport(true);
} catch (e) {
reject(e);
}
});
executeTwoCallbacks(promise, callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject( new Error("Driver not found."));
executeTwoCallbacks(getDriverPromise, callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = Promise$1.resolve(localforageSerializer);
executeTwoCallbacks(serializerPromise, callback);
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function() {
if (self._ready === null) self._ready = self._initDriver();
return self._ready;
});
executeTwoCallbacks(promise, callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) drivers = [drivers];
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function extendSelfWithDriver(driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
}
function initDriver(supportedDrivers) {
return function() {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error("No available storage method found.");
self._driverSet = Promise$1.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
this._driverSet = (this._driverSet !== null ? this._driverSet["catch"](function() {
return Promise$1.resolve();
}) : Promise$1.resolve()).then(function() {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function(driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})["catch"](function() {
setDriverToConfig();
var error = new Error("No available storage method found.");
self._driverSet = Promise$1.reject(error);
return self._driverSet;
});
executeTwoCallbacks(this._driverSet, callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!DriverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) supportedDrivers.push(driverName);
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
for (var i = 0, len = LibraryMethods.length; i < len; i++) callWhenReady(this, LibraryMethods[i]);
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
}())();
}, { "3": 3 }]
}, {}, [4])(4);
});
}));
var require_jszip_min = __commonJSMin(((exports, module) => {
(function(e) {
if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();
else if ("function" == typeof define && define.amd) define([], e);
else ("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this).JSZip = e();
})(function() {
return function s(a, o, h) {
function u(r, e) {
if (!o[r]) {
if (!a[r]) {
var t = "function" == typeof __require && __require;
if (!e && t) return t(r, !0);
if (l) return l(r, !0);
var n = new Error("Cannot find module '" + r + "'");
throw n.code = "MODULE_NOT_FOUND", n;
}
var i = o[r] = { exports: {} };
a[r][0].call(i.exports, function(e) {
var t = a[r][1][e];
return u(t || e);
}, i, i.exports, s, a, o, h);
}
return o[r].exports;
}
for (var l = "function" == typeof __require && __require, e = 0; e < h.length; e++) u(h[e]);
return u;
}({
1: [function(e, t, r) {
"use strict";
var d = e("./utils"), c = e("./support"), p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
r.encode = function(e) {
for (var t, r, n, i, s, a, o, h = [], u = 0, l = e.length, f = l, c = "string" !== d.getTypeOf(e); u < e.length;) f = l - u, n = c ? (t = e[u++], r = u < l ? e[u++] : 0, u < l ? e[u++] : 0) : (t = e.charCodeAt(u++), r = u < l ? e.charCodeAt(u++) : 0, u < l ? e.charCodeAt(u++) : 0), i = t >> 2, s = (3 & t) << 4 | r >> 4, a = 1 < f ? (15 & r) << 2 | n >> 6 : 64, o = 2 < f ? 63 & n : 64, h.push(p.charAt(i) + p.charAt(s) + p.charAt(a) + p.charAt(o));
return h.join("");
}, r.decode = function(e) {
var t, r, n, i, s, a, o = 0, h = 0, u = "data:";
if (e.substr(0, u.length) === u) throw new Error("Invalid base64 input, it looks like a data url.");
var l, f = 3 * (e = e.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4;
if (e.charAt(e.length - 1) === p.charAt(64) && f--, e.charAt(e.length - 2) === p.charAt(64) && f--, f % 1 != 0) throw new Error("Invalid base64 input, bad content length.");
for (l = c.uint8array ? new Uint8Array(0 | f) : new Array(0 | f); o < e.length;) t = p.indexOf(e.charAt(o++)) << 2 | (i = p.indexOf(e.charAt(o++))) >> 4, r = (15 & i) << 4 | (s = p.indexOf(e.charAt(o++))) >> 2, n = (3 & s) << 6 | (a = p.indexOf(e.charAt(o++))), l[h++] = t, 64 !== s && (l[h++] = r), 64 !== a && (l[h++] = n);
return l;
};
}, {
"./support": 30,
"./utils": 32
}],
2: [function(e, t, r) {
"use strict";
var n = e("./external"), i = e("./stream/DataWorker"), s = e("./stream/Crc32Probe"), a = e("./stream/DataLengthProbe");
function o(e, t, r, n, i) {
this.compressedSize = e, this.uncompressedSize = t, this.crc32 = r, this.compression = n, this.compressedContent = i;
}
o.prototype = {
getContentWorker: function() {
var e = new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")), t = this;
return e.on("end", function() {
if (this.streamInfo.data_length !== t.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch");
}), e;
},
getCompressedWorker: function() {
return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression);
}
}, o.createWorkerFrom = function(e, t, r) {
return e.pipe(new s()).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression", t);
}, t.exports = o;
}, {
"./external": 6,
"./stream/Crc32Probe": 25,
"./stream/DataLengthProbe": 26,
"./stream/DataWorker": 27
}],
3: [function(e, t, r) {
"use strict";
var n = e("./stream/GenericWorker");
r.STORE = {
magic: "\0\0",
compressWorker: function() {
return new n("STORE compression");
},
uncompressWorker: function() {
return new n("STORE decompression");
}
}, r.DEFLATE = e("./flate");
}, {
"./flate": 7,
"./stream/GenericWorker": 28
}],
4: [function(e, t, r) {
"use strict";
var n = e("./utils");
var o = function() {
for (var e, t = [], r = 0; r < 256; r++) {
e = r;
for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1;
t[r] = e;
}
return t;
}();
t.exports = function(e, t) {
return void 0 !== e && e.length ? "string" !== n.getTypeOf(e) ? function(e, t, r, n) {
var i = o, s = n + r;
e ^= -1;
for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])];
return -1 ^ e;
}(0 | t, e, e.length, 0) : function(e, t, r, n) {
var i = o, s = n + r;
e ^= -1;
for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t.charCodeAt(a))];
return -1 ^ e;
}(0 | t, e, e.length, 0) : 0;
};
}, { "./utils": 32 }],
5: [function(e, t, r) {
"use strict";
r.base64 = !1, r.binary = !1, r.dir = !1, r.createFolders = !0, r.date = null, r.compression = null, r.compressionOptions = null, r.comment = null, r.unixPermissions = null, r.dosPermissions = null;
}, {}],
6: [function(e, t, r) {
"use strict";
var n = null;
n = "undefined" != typeof Promise ? Promise : e("lie"), t.exports = { Promise: n };
}, { lie: 37 }],
7: [function(e, t, r) {
"use strict";
var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i = e("pako"), s = e("./utils"), a = e("./stream/GenericWorker"), o = n ? "uint8array" : "array";
function h(e, t) {
a.call(this, "FlateWorker/" + e), this._pako = null, this._pakoAction = e, this._pakoOptions = t, this.meta = {};
}
r.magic = "\b\0", s.inherits(h, a), h.prototype.processChunk = function(e) {
this.meta = e.meta, null === this._pako && this._createPako(), this._pako.push(s.transformTo(o, e.data), !1);
}, h.prototype.flush = function() {
a.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], !0);
}, h.prototype.cleanUp = function() {
a.prototype.cleanUp.call(this), this._pako = null;
}, h.prototype._createPako = function() {
this._pako = new i[this._pakoAction]({
raw: !0,
level: this._pakoOptions.level || -1
});
var t = this;
this._pako.onData = function(e) {
t.push({
data: e,
meta: t.meta
});
};
}, r.compressWorker = function(e) {
return new h("Deflate", e);
}, r.uncompressWorker = function() {
return new h("Inflate", {});
};
}, {
"./stream/GenericWorker": 28,
"./utils": 32,
pako: 38
}],
8: [function(e, t, r) {
"use strict";
function A(e, t) {
var r, n = "";
for (r = 0; r < t; r++) n += String.fromCharCode(255 & e), e >>>= 8;
return n;
}
function n(e, t, r, n, i, s) {
var a, o, h = e.file, u = e.compression, l = s !== O.utf8encode, f = I.transformTo("string", s(h.name)), c = I.transformTo("string", O.utf8encode(h.name)), d = h.comment, p = I.transformTo("string", s(d)), m = I.transformTo("string", O.utf8encode(d)), _ = c.length !== h.name.length, g = m.length !== d.length, b = "", v = "", y = "", w = h.dir, k = h.date, x = {
crc32: 0,
compressedSize: 0,
uncompressedSize: 0
};
t && !r || (x.crc32 = e.crc32, x.compressedSize = e.compressedSize, x.uncompressedSize = e.uncompressedSize);
var S = 0;
t && (S |= 8), l || !_ && !g || (S |= 2048);
var z = 0, C = 0;
w && (z |= 16), "UNIX" === i ? (C = 798, z |= function(e, t) {
var r = e;
return e || (r = t ? 16893 : 33204), (65535 & r) << 16;
}(h.unixPermissions, w)) : (C = 20, z |= function(e) {
return 63 & (e || 0);
}(h.dosPermissions)), a = k.getUTCHours(), a <<= 6, a |= k.getUTCMinutes(), a <<= 5, a |= k.getUTCSeconds() / 2, o = k.getUTCFullYear() - 1980, o <<= 4, o |= k.getUTCMonth() + 1, o <<= 5, o |= k.getUTCDate(), _ && (v = A(1, 1) + A(B(f), 4) + c, b += "up" + A(v.length, 2) + v), g && (y = A(1, 1) + A(B(p), 4) + m, b += "uc" + A(y.length, 2) + y);
var E = "";
return E += "\n\0", E += A(S, 2), E += u.magic, E += A(a, 2), E += A(o, 2), E += A(x.crc32, 4), E += A(x.compressedSize, 4), E += A(x.uncompressedSize, 4), E += A(f.length, 2), E += A(b.length, 2), {
fileRecord: R.LOCAL_FILE_HEADER + E + f + b,
dirRecord: R.CENTRAL_FILE_HEADER + A(C, 2) + E + A(p.length, 2) + "\0\0\0\0" + A(z, 4) + A(n, 4) + f + b + p
};
}
var I = e("../utils"), i = e("../stream/GenericWorker"), O = e("../utf8"), B = e("../crc32"), R = e("../signature");
function s(e, t, r, n) {
i.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t, this.zipPlatform = r, this.encodeFileName = n, this.streamFiles = e, this.accumulate = !1, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = [];
}
I.inherits(s, i), s.prototype.push = function(e) {
var t = e.meta.percent || 0, r = this.entriesCount, n = this._sources.length;
this.accumulate ? this.contentBuffer.push(e) : (this.bytesWritten += e.data.length, i.prototype.push.call(this, {
data: e.data,
meta: {
currentFile: this.currentFile,
percent: r ? (t + 100 * (r - n - 1)) / r : 100
}
}));
}, s.prototype.openedSource = function(e) {
this.currentSourceOffset = this.bytesWritten, this.currentFile = e.file.name;
var t = this.streamFiles && !e.file.dir;
if (t) {
var r = n(e, t, !1, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
this.push({
data: r.fileRecord,
meta: { percent: 0 }
});
} else this.accumulate = !0;
}, s.prototype.closedSource = function(e) {
this.accumulate = !1;
var t = this.streamFiles && !e.file.dir, r = n(e, t, !0, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
if (this.dirRecords.push(r.dirRecord), t) this.push({
data: function(e) {
return R.DATA_DESCRIPTOR + A(e.crc32, 4) + A(e.compressedSize, 4) + A(e.uncompressedSize, 4);
}(e),
meta: { percent: 100 }
});
else for (this.push({
data: r.fileRecord,
meta: { percent: 0 }
}); this.contentBuffer.length;) this.push(this.contentBuffer.shift());
this.currentFile = null;
}, s.prototype.flush = function() {
for (var e = this.bytesWritten, t = 0; t < this.dirRecords.length; t++) this.push({
data: this.dirRecords[t],
meta: { percent: 100 }
});
var r = this.bytesWritten - e, n = function(e, t, r, n, i) {
var s = I.transformTo("string", i(n));
return R.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A(e, 2) + A(e, 2) + A(t, 4) + A(r, 4) + A(s.length, 2) + s;
}(this.dirRecords.length, r, e, this.zipComment, this.encodeFileName);
this.push({
data: n,
meta: { percent: 100 }
});
}, s.prototype.prepareNextSource = function() {
this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume();
}, s.prototype.registerPrevious = function(e) {
this._sources.push(e);
var t = this;
return e.on("data", function(e) {
t.processChunk(e);
}), e.on("end", function() {
t.closedSource(t.previous.streamInfo), t._sources.length ? t.prepareNextSource() : t.end();
}), e.on("error", function(e) {
t.error(e);
}), this;
}, s.prototype.resume = function() {
return !!i.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), !0) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), !0));
}, s.prototype.error = function(e) {
var t = this._sources;
if (!i.prototype.error.call(this, e)) return !1;
for (var r = 0; r < t.length; r++) try {
t[r].error(e);
} catch (e) {}
return !0;
}, s.prototype.lock = function() {
i.prototype.lock.call(this);
for (var e = this._sources, t = 0; t < e.length; t++) e[t].lock();
}, t.exports = s;
}, {
"../crc32": 4,
"../signature": 23,
"../stream/GenericWorker": 28,
"../utf8": 31,
"../utils": 32
}],
9: [function(e, t, r) {
"use strict";
var u = e("../compressions"), n = e("./ZipFileWorker");
r.generateWorker = function(e, a, t) {
var o = new n(a.streamFiles, t, a.platform, a.encodeFileName), h = 0;
try {
e.forEach(function(e, t) {
h++;
var r = function(e, t) {
var r = e || t, n = u[r];
if (!n) throw new Error(r + " is not a valid compression method !");
return n;
}(t.options.compression, a.compression), n = t.options.compressionOptions || a.compressionOptions || {}, i = t.dir, s = t.date;
t._compressWorker(r, n).withStreamInfo("file", {
name: e,
dir: i,
date: s,
comment: t.comment || "",
unixPermissions: t.unixPermissions,
dosPermissions: t.dosPermissions
}).pipe(o);
}), o.entriesCount = h;
} catch (e) {
o.error(e);
}
return o;
};
}, {
"../compressions": 3,
"./ZipFileWorker": 8
}],
10: [function(e, t, r) {
"use strict";
function n() {
if (!(this instanceof n)) return new n();
if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
this.files = Object.create(null), this.comment = null, this.root = "", this.clone = function() {
var e = new n();
for (var t in this) "function" != typeof this[t] && (e[t] = this[t]);
return e;
};
}
(n.prototype = e("./object")).loadAsync = e("./load"), n.support = e("./support"), n.defaults = e("./defaults"), n.version = "3.10.1", n.loadAsync = function(e, t) {
return new n().loadAsync(e, t);
}, n.external = e("./external"), t.exports = n;
}, {
"./defaults": 5,
"./external": 6,
"./load": 11,
"./object": 15,
"./support": 30
}],
11: [function(e, t, r) {
"use strict";
var u = e("./utils"), i = e("./external"), n = e("./utf8"), s = e("./zipEntries"), a = e("./stream/Crc32Probe"), l = e("./nodejsUtils");
function f(n) {
return new i.Promise(function(e, t) {
var r = n.decompressed.getContentWorker().pipe(new a());
r.on("error", function(e) {
t(e);
}).on("end", function() {
r.streamInfo.crc32 !== n.decompressed.crc32 ? t( new Error("Corrupted zip : CRC32 mismatch")) : e();
}).resume();
});
}
t.exports = function(e, o) {
var h = this;
return o = u.extend(o || {}, {
base64: !1,
checkCRC32: !1,
optimizedBinaryString: !1,
createFolders: !1,
decodeFileName: n.utf8decode
}), l.isNode && l.isStream(e) ? i.Promise.reject( new Error("JSZip can't accept a stream when loading a zip file.")) : u.prepareContent("the loaded zip file", e, !0, o.optimizedBinaryString, o.base64).then(function(e) {
var t = new s(o);
return t.load(e), t;
}).then(function(e) {
var t = [i.Promise.resolve(e)], r = e.files;
if (o.checkCRC32) for (var n = 0; n < r.length; n++) t.push(f(r[n]));
return i.Promise.all(t);
}).then(function(e) {
for (var t = e.shift(), r = t.files, n = 0; n < r.length; n++) {
var i = r[n], s = i.fileNameStr, a = u.resolve(i.fileNameStr);
h.file(a, i.decompressed, {
binary: !0,
optimizedBinaryString: !0,
date: i.date,
dir: i.dir,
comment: i.fileCommentStr.length ? i.fileCommentStr : null,
unixPermissions: i.unixPermissions,
dosPermissions: i.dosPermissions,
createFolders: o.createFolders
}), i.dir || (h.file(a).unsafeOriginalName = s);
}
return t.zipComment.length && (h.comment = t.zipComment), h;
});
};
}, {
"./external": 6,
"./nodejsUtils": 14,
"./stream/Crc32Probe": 25,
"./utf8": 31,
"./utils": 32,
"./zipEntries": 33
}],
12: [function(e, t, r) {
"use strict";
var n = e("../utils"), i = e("../stream/GenericWorker");
function s(e, t) {
i.call(this, "Nodejs stream input adapter for " + e), this._upstreamEnded = !1, this._bindStream(t);
}
n.inherits(s, i), s.prototype._bindStream = function(e) {
var t = this;
(this._stream = e).pause(), e.on("data", function(e) {
t.push({
data: e,
meta: { percent: 0 }
});
}).on("error", function(e) {
t.isPaused ? this.generatedError = e : t.error(e);
}).on("end", function() {
t.isPaused ? t._upstreamEnded = !0 : t.end();
});
}, s.prototype.pause = function() {
return !!i.prototype.pause.call(this) && (this._stream.pause(), !0);
}, s.prototype.resume = function() {
return !!i.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), !0);
}, t.exports = s;
}, {
"../stream/GenericWorker": 28,
"../utils": 32
}],
13: [function(e, t, r) {
"use strict";
var i = e("readable-stream").Readable;
function n(e, t, r) {
i.call(this, t), this._helper = e;
var n = this;
e.on("data", function(e, t) {
n.push(e) || n._helper.pause(), r && r(t);
}).on("error", function(e) {
n.emit("error", e);
}).on("end", function() {
n.push(null);
});
}
e("../utils").inherits(n, i), n.prototype._read = function() {
this._helper.resume();
}, t.exports = n;
}, {
"../utils": 32,
"readable-stream": 16
}],
14: [function(e, t, r) {
"use strict";
t.exports = {
isNode: "undefined" != typeof Buffer,
newBufferFrom: function(e, t) {
if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e, t);
if ("number" == typeof e) throw new Error("The \"data\" argument must not be a number");
return new Buffer(e, t);
},
allocBuffer: function(e) {
if (Buffer.alloc) return Buffer.alloc(e);
var t = new Buffer(e);
return t.fill(0), t;
},
isBuffer: function(e) {
return Buffer.isBuffer(e);
},
isStream: function(e) {
return e && "function" == typeof e.on && "function" == typeof e.pause && "function" == typeof e.resume;
}
};
}, {}],
15: [function(e, t, r) {
"use strict";
function s(e, t, r) {
var n, i = u.getTypeOf(t), s = u.extend(r || {}, f);
s.date = s.date || new Date(), null !== s.compression && (s.compression = s.compression.toUpperCase()), "string" == typeof s.unixPermissions && (s.unixPermissions = parseInt(s.unixPermissions, 8)), s.unixPermissions && 16384 & s.unixPermissions && (s.dir = !0), s.dosPermissions && 16 & s.dosPermissions && (s.dir = !0), s.dir && (e = g(e)), s.createFolders && (n = _(e)) && b.call(this, n, !0);
var a = "string" === i && !1 === s.binary && !1 === s.base64;
r && void 0 !== r.binary || (s.binary = !a), (t instanceof c && 0 === t.uncompressedSize || s.dir || !t || 0 === t.length) && (s.base64 = !1, s.binary = !0, t = "", s.compression = "STORE", i = "string");
var o = null;
o = t instanceof c || t instanceof l ? t : p.isNode && p.isStream(t) ? new m(e, t) : u.prepareContent(e, t, s.binary, s.optimizedBinaryString, s.base64);
var h = new d(e, o, s);
this.files[e] = h;
}
var i = e("./utf8"), u = e("./utils"), l = e("./stream/GenericWorker"), a = e("./stream/StreamHelper"), f = e("./defaults"), c = e("./compressedObject"), d = e("./zipObject"), o = e("./generate"), p = e("./nodejsUtils"), m = e("./nodejs/NodejsStreamInputAdapter"), _ = function(e) {
"/" === e.slice(-1) && (e = e.substring(0, e.length - 1));
var t = e.lastIndexOf("/");
return 0 < t ? e.substring(0, t) : "";
}, g = function(e) {
return "/" !== e.slice(-1) && (e += "/"), e;
}, b = function(e, t) {
return t = void 0 !== t ? t : f.createFolders, e = g(e), this.files[e] || s.call(this, e, null, {
dir: !0,
createFolders: t
}), this.files[e];
};
function h(e) {
return "[object RegExp]" === Object.prototype.toString.call(e);
}
t.exports = {
load: function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
},
forEach: function(e) {
var t, r, n;
for (t in this.files) n = this.files[t], (r = t.slice(this.root.length, t.length)) && t.slice(0, this.root.length) === this.root && e(r, n);
},
filter: function(r) {
var n = [];
return this.forEach(function(e, t) {
r(e, t) && n.push(t);
}), n;
},
file: function(e, t, r) {
if (1 !== arguments.length) return e = this.root + e, s.call(this, e, t, r), this;
if (h(e)) {
var n = e;
return this.filter(function(e, t) {
return !t.dir && n.test(e);
});
}
var i = this.files[this.root + e];
return i && !i.dir ? i : null;
},
folder: function(r) {
if (!r) return this;
if (h(r)) return this.filter(function(e, t) {
return t.dir && r.test(e);
});
var e = this.root + r, t = b.call(this, e), n = this.clone();
return n.root = t.name, n;
},
remove: function(r) {
r = this.root + r;
var e = this.files[r];
if (e || ("/" !== r.slice(-1) && (r += "/"), e = this.files[r]), e && !e.dir) delete this.files[r];
else for (var t = this.filter(function(e, t) {
return t.name.slice(0, r.length) === r;
}), n = 0; n < t.length; n++) delete this.files[t[n].name];
return this;
},
generate: function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
},
generateInternalStream: function(e) {
var t, r = {};
try {
if ((r = u.extend(e || {}, {
streamFiles: !1,
compression: "STORE",
compressionOptions: null,
type: "",
platform: "DOS",
comment: null,
mimeType: "application/zip",
encodeFileName: i.utf8encode
})).type = r.type.toLowerCase(), r.compression = r.compression.toUpperCase(), "binarystring" === r.type && (r.type = "string"), !r.type) throw new Error("No output type specified.");
u.checkSupport(r.type), "darwin" !== r.platform && "freebsd" !== r.platform && "linux" !== r.platform && "sunos" !== r.platform || (r.platform = "UNIX"), "win32" === r.platform && (r.platform = "DOS");
var n = r.comment || this.comment || "";
t = o.generateWorker(this, r, n);
} catch (e) {
(t = new l("error")).error(e);
}
return new a(t, r.type || "string", r.mimeType);
},
generateAsync: function(e, t) {
return this.generateInternalStream(e).accumulate(t);
},
generateNodeStream: function(e, t) {
return (e = e || {}).type || (e.type = "nodebuffer"), this.generateInternalStream(e).toNodejsStream(t);
}
};
}, {
"./compressedObject": 2,
"./defaults": 5,
"./generate": 9,
"./nodejs/NodejsStreamInputAdapter": 12,
"./nodejsUtils": 14,
"./stream/GenericWorker": 28,
"./stream/StreamHelper": 29,
"./utf8": 31,
"./utils": 32,
"./zipObject": 35
}],
16: [function(e, t, r) {
"use strict";
t.exports = e("stream");
}, { stream: void 0 }],
17: [function(e, t, r) {
"use strict";
var n = e("./DataReader");
function i(e) {
n.call(this, e);
for (var t = 0; t < this.data.length; t++) e[t] = 255 & e[t];
}
e("../utils").inherits(i, n), i.prototype.byteAt = function(e) {
return this.data[this.zero + e];
}, i.prototype.lastIndexOfSignature = function(e) {
for (var t = e.charCodeAt(0), r = e.charCodeAt(1), n = e.charCodeAt(2), i = e.charCodeAt(3), s = this.length - 4; 0 <= s; --s) if (this.data[s] === t && this.data[s + 1] === r && this.data[s + 2] === n && this.data[s + 3] === i) return s - this.zero;
return -1;
}, i.prototype.readAndCheckSignature = function(e) {
var t = e.charCodeAt(0), r = e.charCodeAt(1), n = e.charCodeAt(2), i = e.charCodeAt(3), s = this.readData(4);
return t === s[0] && r === s[1] && n === s[2] && i === s[3];
}, i.prototype.readData = function(e) {
if (this.checkOffset(e), 0 === e) return [];
var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
return this.index += e, t;
}, t.exports = i;
}, {
"../utils": 32,
"./DataReader": 18
}],
18: [function(e, t, r) {
"use strict";
var n = e("../utils");
function i(e) {
this.data = e, this.length = e.length, this.index = 0, this.zero = 0;
}
i.prototype = {
checkOffset: function(e) {
this.checkIndex(this.index + e);
},
checkIndex: function(e) {
if (this.length < this.zero + e || e < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e + "). Corrupted zip ?");
},
setIndex: function(e) {
this.checkIndex(e), this.index = e;
},
skip: function(e) {
this.setIndex(this.index + e);
},
byteAt: function() {},
readInt: function(e) {
var t, r = 0;
for (this.checkOffset(e), t = this.index + e - 1; t >= this.index; t--) r = (r << 8) + this.byteAt(t);
return this.index += e, r;
},
readString: function(e) {
return n.transformTo("string", this.readData(e));
},
readData: function() {},
lastIndexOfSignature: function() {},
readAndCheckSignature: function() {},
readDate: function() {
var e = this.readInt(4);
return new Date(Date.UTC(1980 + (e >> 25 & 127), (e >> 21 & 15) - 1, e >> 16 & 31, e >> 11 & 31, e >> 5 & 63, (31 & e) << 1));
}
}, t.exports = i;
}, { "../utils": 32 }],
19: [function(e, t, r) {
"use strict";
var n = e("./Uint8ArrayReader");
function i(e) {
n.call(this, e);
}
e("../utils").inherits(i, n), i.prototype.readData = function(e) {
this.checkOffset(e);
var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
return this.index += e, t;
}, t.exports = i;
}, {
"../utils": 32,
"./Uint8ArrayReader": 21
}],
20: [function(e, t, r) {
"use strict";
var n = e("./DataReader");
function i(e) {
n.call(this, e);
}
e("../utils").inherits(i, n), i.prototype.byteAt = function(e) {
return this.data.charCodeAt(this.zero + e);
}, i.prototype.lastIndexOfSignature = function(e) {
return this.data.lastIndexOf(e) - this.zero;
}, i.prototype.readAndCheckSignature = function(e) {
return e === this.readData(4);
}, i.prototype.readData = function(e) {
this.checkOffset(e);
var t = this.data.slice(this.zero + this.index, this.zero + this.index + e);
return this.index += e, t;
}, t.exports = i;
}, {
"../utils": 32,
"./DataReader": 18
}],
21: [function(e, t, r) {
"use strict";
var n = e("./ArrayReader");
function i(e) {
n.call(this, e);
}
e("../utils").inherits(i, n), i.prototype.readData = function(e) {
if (this.checkOffset(e), 0 === e) return new Uint8Array(0);
var t = this.data.subarray(this.zero + this.index, this.zero + this.index + e);
return this.index += e, t;
}, t.exports = i;
}, {
"../utils": 32,
"./ArrayReader": 17
}],
22: [function(e, t, r) {
"use strict";
var n = e("../utils"), i = e("../support"), s = e("./ArrayReader"), a = e("./StringReader"), o = e("./NodeBufferReader"), h = e("./Uint8ArrayReader");
t.exports = function(e) {
var t = n.getTypeOf(e);
return n.checkSupport(t), "string" !== t || i.uint8array ? "nodebuffer" === t ? new o(e) : i.uint8array ? new h(n.transformTo("uint8array", e)) : new s(n.transformTo("array", e)) : new a(e);
};
}, {
"../support": 30,
"../utils": 32,
"./ArrayReader": 17,
"./NodeBufferReader": 19,
"./StringReader": 20,
"./Uint8ArrayReader": 21
}],
23: [function(e, t, r) {
"use strict";
r.LOCAL_FILE_HEADER = "PK", r.CENTRAL_FILE_HEADER = "PK", r.CENTRAL_DIRECTORY_END = "PK", r.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r.ZIP64_CENTRAL_DIRECTORY_END = "PK", r.DATA_DESCRIPTOR = "PK\x07\b";
}, {}],
24: [function(e, t, r) {
"use strict";
var n = e("./GenericWorker"), i = e("../utils");
function s(e) {
n.call(this, "ConvertWorker to " + e), this.destType = e;
}
i.inherits(s, n), s.prototype.processChunk = function(e) {
this.push({
data: i.transformTo(this.destType, e.data),
meta: e.meta
});
}, t.exports = s;
}, {
"../utils": 32,
"./GenericWorker": 28
}],
25: [function(e, t, r) {
"use strict";
var n = e("./GenericWorker"), i = e("../crc32");
function s() {
n.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0);
}
e("../utils").inherits(s, n), s.prototype.processChunk = function(e) {
this.streamInfo.crc32 = i(e.data, this.streamInfo.crc32 || 0), this.push(e);
}, t.exports = s;
}, {
"../crc32": 4,
"../utils": 32,
"./GenericWorker": 28
}],
26: [function(e, t, r) {
"use strict";
var n = e("../utils"), i = e("./GenericWorker");
function s(e) {
i.call(this, "DataLengthProbe for " + e), this.propName = e, this.withStreamInfo(e, 0);
}
n.inherits(s, i), s.prototype.processChunk = function(e) {
if (e) {
var t = this.streamInfo[this.propName] || 0;
this.streamInfo[this.propName] = t + e.data.length;
}
i.prototype.processChunk.call(this, e);
}, t.exports = s;
}, {
"../utils": 32,
"./GenericWorker": 28
}],
27: [function(e, t, r) {
"use strict";
var n = e("../utils"), i = e("./GenericWorker");
function s(e) {
i.call(this, "DataWorker");
var t = this;
this.dataIsReady = !1, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = !1, e.then(function(e) {
t.dataIsReady = !0, t.data = e, t.max = e && e.length || 0, t.type = n.getTypeOf(e), t.isPaused || t._tickAndRepeat();
}, function(e) {
t.error(e);
});
}
n.inherits(s, i), s.prototype.cleanUp = function() {
i.prototype.cleanUp.call(this), this.data = null;
}, s.prototype.resume = function() {
return !!i.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = !0, n.delay(this._tickAndRepeat, [], this)), !0);
}, s.prototype._tickAndRepeat = function() {
this._tickScheduled = !1, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n.delay(this._tickAndRepeat, [], this), this._tickScheduled = !0));
}, s.prototype._tick = function() {
if (this.isPaused || this.isFinished) return !1;
var e = null, t = Math.min(this.max, this.index + 16384);
if (this.index >= this.max) return this.end();
switch (this.type) {
case "string":
e = this.data.substring(this.index, t);
break;
case "uint8array":
e = this.data.subarray(this.index, t);
break;
case "array":
case "nodebuffer": e = this.data.slice(this.index, t);
}
return this.index = t, this.push({
data: e,
meta: { percent: this.max ? this.index / this.max * 100 : 0 }
});
}, t.exports = s;
}, {
"../utils": 32,
"./GenericWorker": 28
}],
28: [function(e, t, r) {
"use strict";
function n(e) {
this.name = e || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = !0, this.isFinished = !1, this.isLocked = !1, this._listeners = {
data: [],
end: [],
error: []
}, this.previous = null;
}
n.prototype = {
push: function(e) {
this.emit("data", e);
},
end: function() {
if (this.isFinished) return !1;
this.flush();
try {
this.emit("end"), this.cleanUp(), this.isFinished = !0;
} catch (e) {
this.emit("error", e);
}
return !0;
},
error: function(e) {
return !this.isFinished && (this.isPaused ? this.generatedError = e : (this.isFinished = !0, this.emit("error", e), this.previous && this.previous.error(e), this.cleanUp()), !0);
},
on: function(e, t) {
return this._listeners[e].push(t), this;
},
cleanUp: function() {
this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = [];
},
emit: function(e, t) {
if (this._listeners[e]) for (var r = 0; r < this._listeners[e].length; r++) this._listeners[e][r].call(this, t);
},
pipe: function(e) {
return e.registerPrevious(this);
},
registerPrevious: function(e) {
if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
this.streamInfo = e.streamInfo, this.mergeStreamInfo(), this.previous = e;
var t = this;
return e.on("data", function(e) {
t.processChunk(e);
}), e.on("end", function() {
t.end();
}), e.on("error", function(e) {
t.error(e);
}), this;
},
pause: function() {
return !this.isPaused && !this.isFinished && (this.isPaused = !0, this.previous && this.previous.pause(), !0);
},
resume: function() {
if (!this.isPaused || this.isFinished) return !1;
var e = this.isPaused = !1;
return this.generatedError && (this.error(this.generatedError), e = !0), this.previous && this.previous.resume(), !e;
},
flush: function() {},
processChunk: function(e) {
this.push(e);
},
withStreamInfo: function(e, t) {
return this.extraStreamInfo[e] = t, this.mergeStreamInfo(), this;
},
mergeStreamInfo: function() {
for (var e in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e) && (this.streamInfo[e] = this.extraStreamInfo[e]);
},
lock: function() {
if (this.isLocked) throw new Error("The stream '" + this + "' has already been used.");
this.isLocked = !0, this.previous && this.previous.lock();
},
toString: function() {
var e = "Worker " + this.name;
return this.previous ? this.previous + " -> " + e : e;
}
}, t.exports = n;
}, {}],
29: [function(e, t, r) {
"use strict";
var h = e("../utils"), i = e("./ConvertWorker"), s = e("./GenericWorker"), u = e("../base64"), n = e("../support"), a = e("../external"), o = null;
if (n.nodestream) try {
o = e("../nodejs/NodejsStreamOutputAdapter");
} catch (e) {}
function l(e, o) {
return new a.Promise(function(t, r) {
var n = [], i = e._internalType, s = e._outputType, a = e._mimeType;
e.on("data", function(e, t) {
n.push(e), o && o(t);
}).on("error", function(e) {
n = [], r(e);
}).on("end", function() {
try {
t(function(e, t, r) {
switch (e) {
case "blob": return h.newBlob(h.transformTo("arraybuffer", t), r);
case "base64": return u.encode(t);
default: return h.transformTo(e, t);
}
}(s, function(e, t) {
var r, n = 0, i = null, s = 0;
for (r = 0; r < t.length; r++) s += t[r].length;
switch (e) {
case "string": return t.join("");
case "array": return Array.prototype.concat.apply([], t);
case "uint8array":
for (i = new Uint8Array(s), r = 0; r < t.length; r++) i.set(t[r], n), n += t[r].length;
return i;
case "nodebuffer": return Buffer.concat(t);
default: throw new Error("concat : unsupported type '" + e + "'");
}
}(i, n), a));
} catch (e) {
r(e);
}
n = [];
}).resume();
});
}
function f(e, t, r) {
var n = t;
switch (t) {
case "blob":
case "arraybuffer":
n = "uint8array";
break;
case "base64": n = "string";
}
try {
this._internalType = n, this._outputType = t, this._mimeType = r, h.checkSupport(n), this._worker = e.pipe(new i(n)), e.lock();
} catch (e) {
this._worker = new s("error"), this._worker.error(e);
}
}
f.prototype = {
accumulate: function(e) {
return l(this, e);
},
on: function(e, t) {
var r = this;
return "data" === e ? this._worker.on(e, function(e) {
t.call(r, e.data, e.meta);
}) : this._worker.on(e, function() {
h.delay(t, arguments, r);
}), this;
},
resume: function() {
return h.delay(this._worker.resume, [], this._worker), this;
},
pause: function() {
return this._worker.pause(), this;
},
toNodejsStream: function(e) {
if (h.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method");
return new o(this, { objectMode: "nodebuffer" !== this._outputType }, e);
}
}, t.exports = f;
}, {
"../base64": 1,
"../external": 6,
"../nodejs/NodejsStreamOutputAdapter": 13,
"../support": 30,
"../utils": 32,
"./ConvertWorker": 24,
"./GenericWorker": 28
}],
30: [function(e, t, r) {
"use strict";
if (r.base64 = !0, r.array = !0, r.string = !0, r.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r.nodebuffer = "undefined" != typeof Buffer, r.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r.blob = !1;
else {
var n = new ArrayBuffer(0);
try {
r.blob = 0 === new Blob([n], { type: "application/zip" }).size;
} catch (e) {
try {
var i = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
i.append(n), r.blob = 0 === i.getBlob("application/zip").size;
} catch (e) {
r.blob = !1;
}
}
}
try {
r.nodestream = !!e("readable-stream").Readable;
} catch (e) {
r.nodestream = !1;
}
}, { "readable-stream": 16 }],
31: [function(e, t, s) {
"use strict";
for (var o = e("./utils"), h = e("./support"), r = e("./nodejsUtils"), n = e("./stream/GenericWorker"), u = new Array(256), i = 0; i < 256; i++) u[i] = 252 <= i ? 6 : 248 <= i ? 5 : 240 <= i ? 4 : 224 <= i ? 3 : 192 <= i ? 2 : 1;
u[254] = u[254] = 1;
function a() {
n.call(this, "utf-8 decode"), this.leftOver = null;
}
function l() {
n.call(this, "utf-8 encode");
}
s.utf8encode = function(e) {
return h.nodebuffer ? r.newBufferFrom(e, "utf-8") : function(e) {
var t, r, n, i, s, a = e.length, o = 0;
for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4;
for (t = h.uint8array ? new Uint8Array(o) : new Array(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r);
return t;
}(e);
}, s.utf8decode = function(e) {
return h.nodebuffer ? o.transformTo("nodebuffer", e).toString("utf-8") : function(e) {
var t, r, n, i, s = e.length, a = new Array(2 * s);
for (t = r = 0; t < s;) if ((n = e[t++]) < 128) a[r++] = n;
else if (4 < (i = u[n])) a[r++] = 65533, t += i - 1;
else {
for (n &= 2 === i ? 31 : 3 === i ? 15 : 7; 1 < i && t < s;) n = n << 6 | 63 & e[t++], i--;
1 < i ? a[r++] = 65533 : n < 65536 ? a[r++] = n : (n -= 65536, a[r++] = 55296 | n >> 10 & 1023, a[r++] = 56320 | 1023 & n);
}
return a.length !== r && (a.subarray ? a = a.subarray(0, r) : a.length = r), o.applyFromCharCode(a);
}(e = o.transformTo(h.uint8array ? "uint8array" : "array", e));
}, o.inherits(a, n), a.prototype.processChunk = function(e) {
var t = o.transformTo(h.uint8array ? "uint8array" : "array", e.data);
if (this.leftOver && this.leftOver.length) {
if (h.uint8array) {
var r = t;
(t = new Uint8Array(r.length + this.leftOver.length)).set(this.leftOver, 0), t.set(r, this.leftOver.length);
} else t = this.leftOver.concat(t);
this.leftOver = null;
}
var n = function(e, t) {
var r;
for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--;
return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t;
}(t), i = t;
n !== t.length && (h.uint8array ? (i = t.subarray(0, n), this.leftOver = t.subarray(n, t.length)) : (i = t.slice(0, n), this.leftOver = t.slice(n, t.length))), this.push({
data: s.utf8decode(i),
meta: e.meta
});
}, a.prototype.flush = function() {
this.leftOver && this.leftOver.length && (this.push({
data: s.utf8decode(this.leftOver),
meta: {}
}), this.leftOver = null);
}, s.Utf8DecodeWorker = a, o.inherits(l, n), l.prototype.processChunk = function(e) {
this.push({
data: s.utf8encode(e.data),
meta: e.meta
});
}, s.Utf8EncodeWorker = l;
}, {
"./nodejsUtils": 14,
"./stream/GenericWorker": 28,
"./support": 30,
"./utils": 32
}],
32: [function(e, t, a) {
"use strict";
var o = e("./support"), h = e("./base64"), r = e("./nodejsUtils"), u = e("./external");
function n(e) {
return e;
}
function l(e, t) {
for (var r = 0; r < e.length; ++r) t[r] = 255 & e.charCodeAt(r);
return t;
}
e("setimmediate"), a.newBlob = function(t, r) {
a.checkSupport("blob");
try {
return new Blob([t], { type: r });
} catch (e) {
try {
var n = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)();
return n.append(t), n.getBlob(r);
} catch (e) {
throw new Error("Bug : can't construct the Blob.");
}
}
};
var i = {
stringifyByChunk: function(e, t, r) {
var n = [], i = 0, s = e.length;
if (s <= r) return String.fromCharCode.apply(null, e);
for (; i < s;) "array" === t || "nodebuffer" === t ? n.push(String.fromCharCode.apply(null, e.slice(i, Math.min(i + r, s)))) : n.push(String.fromCharCode.apply(null, e.subarray(i, Math.min(i + r, s)))), i += r;
return n.join("");
},
stringifyByChar: function(e) {
for (var t = "", r = 0; r < e.length; r++) t += String.fromCharCode(e[r]);
return t;
},
applyCanBeUsed: {
uint8array: function() {
try {
return o.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length;
} catch (e) {
return !1;
}
}(),
nodebuffer: function() {
try {
return o.nodebuffer && 1 === String.fromCharCode.apply(null, r.allocBuffer(1)).length;
} catch (e) {
return !1;
}
}()
}
};
function s(e) {
var t = 65536, r = a.getTypeOf(e), n = !0;
if ("uint8array" === r ? n = i.applyCanBeUsed.uint8array : "nodebuffer" === r && (n = i.applyCanBeUsed.nodebuffer), n) for (; 1 < t;) try {
return i.stringifyByChunk(e, r, t);
} catch (e) {
t = Math.floor(t / 2);
}
return i.stringifyByChar(e);
}
function f(e, t) {
for (var r = 0; r < e.length; r++) t[r] = e[r];
return t;
}
a.applyFromCharCode = s;
var c = {};
c.string = {
string: n,
array: function(e) {
return l(e, new Array(e.length));
},
arraybuffer: function(e) {
return c.string.uint8array(e).buffer;
},
uint8array: function(e) {
return l(e, new Uint8Array(e.length));
},
nodebuffer: function(e) {
return l(e, r.allocBuffer(e.length));
}
}, c.array = {
string: s,
array: n,
arraybuffer: function(e) {
return new Uint8Array(e).buffer;
},
uint8array: function(e) {
return new Uint8Array(e);
},
nodebuffer: function(e) {
return r.newBufferFrom(e);
}
}, c.arraybuffer = {
string: function(e) {
return s(new Uint8Array(e));
},
array: function(e) {
return f(new Uint8Array(e), new Array(e.byteLength));
},
arraybuffer: n,
uint8array: function(e) {
return new Uint8Array(e);
},
nodebuffer: function(e) {
return r.newBufferFrom(new Uint8Array(e));
}
}, c.uint8array = {
string: s,
array: function(e) {
return f(e, new Array(e.length));
},
arraybuffer: function(e) {
return e.buffer;
},
uint8array: n,
nodebuffer: function(e) {
return r.newBufferFrom(e);
}
}, c.nodebuffer = {
string: s,
array: function(e) {
return f(e, new Array(e.length));
},
arraybuffer: function(e) {
return c.nodebuffer.uint8array(e).buffer;
},
uint8array: function(e) {
return f(e, new Uint8Array(e.length));
},
nodebuffer: n
}, a.transformTo = function(e, t) {
if (t = t || "", !e) return t;
a.checkSupport(e);
return c[a.getTypeOf(t)][e](t);
}, a.resolve = function(e) {
for (var t = e.split("/"), r = [], n = 0; n < t.length; n++) {
var i = t[n];
"." === i || "" === i && 0 !== n && n !== t.length - 1 || (".." === i ? r.pop() : r.push(i));
}
return r.join("/");
}, a.getTypeOf = function(e) {
return "string" == typeof e ? "string" : "[object Array]" === Object.prototype.toString.call(e) ? "array" : o.nodebuffer && r.isBuffer(e) ? "nodebuffer" : o.uint8array && e instanceof Uint8Array ? "uint8array" : o.arraybuffer && e instanceof ArrayBuffer ? "arraybuffer" : void 0;
}, a.checkSupport = function(e) {
if (!o[e.toLowerCase()]) throw new Error(e + " is not supported by this platform");
}, a.MAX_VALUE_16BITS = 65535, a.MAX_VALUE_32BITS = -1, a.pretty = function(e) {
var t, r, n = "";
for (r = 0; r < (e || "").length; r++) n += "\\x" + ((t = e.charCodeAt(r)) < 16 ? "0" : "") + t.toString(16).toUpperCase();
return n;
}, a.delay = function(e, t, r) {
setImmediate(function() {
e.apply(r || null, t || []);
});
}, a.inherits = function(e, t) {
function r() {}
r.prototype = t.prototype, e.prototype = new r();
}, a.extend = function() {
var e, t, r = {};
for (e = 0; e < arguments.length; e++) for (t in arguments[e]) Object.prototype.hasOwnProperty.call(arguments[e], t) && void 0 === r[t] && (r[t] = arguments[e][t]);
return r;
}, a.prepareContent = function(r, e, n, i, s) {
return u.Promise.resolve(e).then(function(n) {
return o.blob && (n instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n))) && "undefined" != typeof FileReader ? new u.Promise(function(t, r) {
var e = new FileReader();
e.onload = function(e) {
t(e.target.result);
}, e.onerror = function(e) {
r(e.target.error);
}, e.readAsArrayBuffer(n);
}) : n;
}).then(function(e) {
var t = a.getTypeOf(e);
return t ? ("arraybuffer" === t ? e = a.transformTo("uint8array", e) : "string" === t && (s ? e = h.decode(e) : n && !0 !== i && (e = function(e) {
return l(e, o.uint8array ? new Uint8Array(e.length) : new Array(e.length));
}(e))), e) : u.Promise.reject( new Error("Can't read the data of '" + r + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"));
});
};
}, {
"./base64": 1,
"./external": 6,
"./nodejsUtils": 14,
"./support": 30,
setimmediate: 54
}],
33: [function(e, t, r) {
"use strict";
var n = e("./reader/readerFor"), i = e("./utils"), s = e("./signature"), a = e("./zipEntry"), o = e("./support");
function h(e) {
this.files = [], this.loadOptions = e;
}
h.prototype = {
checkSignature: function(e) {
if (!this.reader.readAndCheckSignature(e)) {
this.reader.index -= 4;
var t = this.reader.readString(4);
throw new Error("Corrupted zip or bug: unexpected signature (" + i.pretty(t) + ", expected " + i.pretty(e) + ")");
}
},
isSignature: function(e, t) {
var r = this.reader.index;
this.reader.setIndex(e);
var n = this.reader.readString(4) === t;
return this.reader.setIndex(r), n;
},
readBlockEndOfCentral: function() {
this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2);
var e = this.reader.readData(this.zipCommentLength), t = o.uint8array ? "uint8array" : "array", r = i.transformTo(t, e);
this.zipComment = this.loadOptions.decodeFileName(r);
},
readBlockZip64EndOfCentral: function() {
this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {};
for (var e, t, r, n = this.zip64EndOfCentralSize - 44; 0 < n;) e = this.reader.readInt(2), t = this.reader.readInt(4), r = this.reader.readData(t), this.zip64ExtensibleData[e] = {
id: e,
length: t,
value: r
};
},
readBlockZip64EndOfCentralLocator: function() {
if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported");
},
readLocalFiles: function() {
var e, t;
for (e = 0; e < this.files.length; e++) t = this.files[e], this.reader.setIndex(t.localHeaderOffset), this.checkSignature(s.LOCAL_FILE_HEADER), t.readLocalPart(this.reader), t.handleUTF8(), t.processAttributes();
},
readCentralDir: function() {
var e;
for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);) (e = new a({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e);
if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
},
readEndOfCentral: function() {
var e = this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);
if (e < 0) throw !this.isSignature(0, s.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory");
this.reader.setIndex(e);
var t = e;
if (this.checkSignature(s.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i.MAX_VALUE_16BITS || this.centralDirRecords === i.MAX_VALUE_16BITS || this.centralDirSize === i.MAX_VALUE_32BITS || this.centralDirOffset === i.MAX_VALUE_32BITS) {
if (this.zip64 = !0, (e = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
if (this.reader.setIndex(e), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral();
}
var r = this.centralDirOffset + this.centralDirSize;
this.zip64 && (r += 20, r += 12 + this.zip64EndOfCentralSize);
var n = t - r;
if (0 < n) this.isSignature(t, s.CENTRAL_FILE_HEADER) || (this.reader.zero = n);
else if (n < 0) throw new Error("Corrupted zip: missing " + Math.abs(n) + " bytes.");
},
prepareReader: function(e) {
this.reader = n(e);
},
load: function(e) {
this.prepareReader(e), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles();
}
}, t.exports = h;
}, {
"./reader/readerFor": 22,
"./signature": 23,
"./support": 30,
"./utils": 32,
"./zipEntry": 34
}],
34: [function(e, t, r) {
"use strict";
var n = e("./reader/readerFor"), s = e("./utils"), i = e("./compressedObject"), a = e("./crc32"), o = e("./utf8"), h = e("./compressions"), u = e("./support");
function l(e, t) {
this.options = e, this.loadOptions = t;
}
l.prototype = {
isEncrypted: function() {
return 1 == (1 & this.bitFlag);
},
useUTF8: function() {
return 2048 == (2048 & this.bitFlag);
},
readLocalPart: function(e) {
var t, r;
if (e.skip(22), this.fileNameLength = e.readInt(2), r = e.readInt(2), this.fileName = e.readData(this.fileNameLength), e.skip(r), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");
if (null === (t = function(e) {
for (var t in h) if (Object.prototype.hasOwnProperty.call(h, t) && h[t].magic === e) return h[t];
return null;
}(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s.pretty(this.compressionMethod) + " unknown (inner file : " + s.transformTo("string", this.fileName) + ")");
this.decompressed = new i(this.compressedSize, this.uncompressedSize, this.crc32, t, e.readData(this.compressedSize));
},
readCentralPart: function(e) {
this.versionMadeBy = e.readInt(2), e.skip(2), this.bitFlag = e.readInt(2), this.compressionMethod = e.readString(2), this.date = e.readDate(), this.crc32 = e.readInt(4), this.compressedSize = e.readInt(4), this.uncompressedSize = e.readInt(4);
var t = e.readInt(2);
if (this.extraFieldsLength = e.readInt(2), this.fileCommentLength = e.readInt(2), this.diskNumberStart = e.readInt(2), this.internalFileAttributes = e.readInt(2), this.externalFileAttributes = e.readInt(4), this.localHeaderOffset = e.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported");
e.skip(t), this.readExtraFields(e), this.parseZIP64ExtraField(e), this.fileComment = e.readData(this.fileCommentLength);
},
processAttributes: function() {
this.unixPermissions = null, this.dosPermissions = null;
var e = this.versionMadeBy >> 8;
this.dir = !!(16 & this.externalFileAttributes), 0 == e && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = !0);
},
parseZIP64ExtraField: function() {
if (this.extraFields[1]) {
var e = n(this.extraFields[1].value);
this.uncompressedSize === s.MAX_VALUE_32BITS && (this.uncompressedSize = e.readInt(8)), this.compressedSize === s.MAX_VALUE_32BITS && (this.compressedSize = e.readInt(8)), this.localHeaderOffset === s.MAX_VALUE_32BITS && (this.localHeaderOffset = e.readInt(8)), this.diskNumberStart === s.MAX_VALUE_32BITS && (this.diskNumberStart = e.readInt(4));
}
},
readExtraFields: function(e) {
var t, r, n, i = e.index + this.extraFieldsLength;
for (this.extraFields || (this.extraFields = {}); e.index + 4 < i;) t = e.readInt(2), r = e.readInt(2), n = e.readData(r), this.extraFields[t] = {
id: t,
length: r,
value: n
};
e.setIndex(i);
},
handleUTF8: function() {
var e = u.uint8array ? "uint8array" : "array";
if (this.useUTF8()) this.fileNameStr = o.utf8decode(this.fileName), this.fileCommentStr = o.utf8decode(this.fileComment);
else {
var t = this.findExtraFieldUnicodePath();
if (null !== t) this.fileNameStr = t;
else {
var r = s.transformTo(e, this.fileName);
this.fileNameStr = this.loadOptions.decodeFileName(r);
}
var n = this.findExtraFieldUnicodeComment();
if (null !== n) this.fileCommentStr = n;
else {
var i = s.transformTo(e, this.fileComment);
this.fileCommentStr = this.loadOptions.decodeFileName(i);
}
}
},
findExtraFieldUnicodePath: function() {
var e = this.extraFields[28789];
if (e) {
var t = n(e.value);
return 1 !== t.readInt(1) ? null : a(this.fileName) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5));
}
return null;
},
findExtraFieldUnicodeComment: function() {
var e = this.extraFields[25461];
if (e) {
var t = n(e.value);
return 1 !== t.readInt(1) ? null : a(this.fileComment) !== t.readInt(4) ? null : o.utf8decode(t.readData(e.length - 5));
}
return null;
}
}, t.exports = l;
}, {
"./compressedObject": 2,
"./compressions": 3,
"./crc32": 4,
"./reader/readerFor": 22,
"./support": 30,
"./utf8": 31,
"./utils": 32
}],
35: [function(e, t, r) {
"use strict";
function n(e, t, r) {
this.name = e, this.dir = r.dir, this.date = r.date, this.comment = r.comment, this.unixPermissions = r.unixPermissions, this.dosPermissions = r.dosPermissions, this._data = t, this._dataBinary = r.binary, this.options = {
compression: r.compression,
compressionOptions: r.compressionOptions
};
}
var s = e("./stream/StreamHelper"), i = e("./stream/DataWorker"), a = e("./utf8"), o = e("./compressedObject"), h = e("./stream/GenericWorker");
n.prototype = {
internalStream: function(e) {
var t = null, r = "string";
try {
if (!e) throw new Error("No output type specified.");
var n = "string" === (r = e.toLowerCase()) || "text" === r;
"binarystring" !== r && "text" !== r || (r = "string"), t = this._decompressWorker();
var i = !this._dataBinary;
i && !n && (t = t.pipe(new a.Utf8EncodeWorker())), !i && n && (t = t.pipe(new a.Utf8DecodeWorker()));
} catch (e) {
(t = new h("error")).error(e);
}
return new s(t, r, "");
},
async: function(e, t) {
return this.internalStream(e).accumulate(t);
},
nodeStream: function(e, t) {
return this.internalStream(e || "nodebuffer").toNodejsStream(t);
},
_compressWorker: function(e, t) {
if (this._data instanceof o && this._data.compression.magic === e.magic) return this._data.getCompressedWorker();
var r = this._decompressWorker();
return this._dataBinary || (r = r.pipe(new a.Utf8EncodeWorker())), o.createWorkerFrom(r, e, t);
},
_decompressWorker: function() {
return this._data instanceof o ? this._data.getContentWorker() : this._data instanceof h ? this._data : new i(this._data);
}
};
for (var u = [
"asText",
"asBinary",
"asNodeBuffer",
"asUint8Array",
"asArrayBuffer"
], l = function() {
throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
}, f = 0; f < u.length; f++) n.prototype[u[f]] = l;
t.exports = n;
}, {
"./compressedObject": 2,
"./stream/DataWorker": 27,
"./stream/GenericWorker": 28,
"./stream/StreamHelper": 29,
"./utf8": 31
}],
36: [function(e, l, t) {
(function(t) {
"use strict";
var r, n, e = t.MutationObserver || t.WebKitMutationObserver;
if (e) {
var i = 0, s = new e(u), a = t.document.createTextNode("");
s.observe(a, { characterData: !0 }), r = function() {
a.data = i = ++i % 2;
};
} else if (t.setImmediate || void 0 === t.MessageChannel) r = "document" in t && "onreadystatechange" in t.document.createElement("script") ? function() {
var e = t.document.createElement("script");
e.onreadystatechange = function() {
u(), e.onreadystatechange = null, e.parentNode.removeChild(e), e = null;
}, t.document.documentElement.appendChild(e);
} : function() {
setTimeout(u, 0);
};
else {
var o = new t.MessageChannel();
o.port1.onmessage = u, r = function() {
o.port2.postMessage(0);
};
}
var h = [];
function u() {
var e, t;
n = !0;
for (var r = h.length; r;) {
for (t = h, h = [], e = -1; ++e < r;) t[e]();
r = h.length;
}
n = !1;
}
l.exports = function(e) {
1 !== h.push(e) || n || r();
};
}).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}],
37: [function(e, t, r) {
"use strict";
var i = e("immediate");
function u() {}
var l = {}, s = ["REJECTED"], a = ["FULFILLED"], n = ["PENDING"];
function o(e) {
if ("function" != typeof e) throw new TypeError("resolver must be a function");
this.state = n, this.queue = [], this.outcome = void 0, e !== u && d(this, e);
}
function h(e, t, r) {
this.promise = e, "function" == typeof t && (this.onFulfilled = t, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r && (this.onRejected = r, this.callRejected = this.otherCallRejected);
}
function f(t, r, n) {
i(function() {
var e;
try {
e = r(n);
} catch (e) {
return l.reject(t, e);
}
e === t ? l.reject(t, new TypeError("Cannot resolve promise with itself")) : l.resolve(t, e);
});
}
function c(e) {
var t = e && e.then;
if (e && ("object" == typeof e || "function" == typeof e) && "function" == typeof t) return function() {
t.apply(e, arguments);
};
}
function d(t, e) {
var r = !1;
function n(e) {
r || (r = !0, l.reject(t, e));
}
function i(e) {
r || (r = !0, l.resolve(t, e));
}
var s = p(function() {
e(i, n);
});
"error" === s.status && n(s.value);
}
function p(e, t) {
var r = {};
try {
r.value = e(t), r.status = "success";
} catch (e) {
r.status = "error", r.value = e;
}
return r;
}
(t.exports = o).prototype.finally = function(t) {
if ("function" != typeof t) return this;
var r = this.constructor;
return this.then(function(e) {
return r.resolve(t()).then(function() {
return e;
});
}, function(e) {
return r.resolve(t()).then(function() {
throw e;
});
});
}, o.prototype.catch = function(e) {
return this.then(null, e);
}, o.prototype.then = function(e, t) {
if ("function" != typeof e && this.state === a || "function" != typeof t && this.state === s) return this;
var r = new this.constructor(u);
this.state !== n ? f(r, this.state === a ? e : t, this.outcome) : this.queue.push(new h(r, e, t));
return r;
}, h.prototype.callFulfilled = function(e) {
l.resolve(this.promise, e);
}, h.prototype.otherCallFulfilled = function(e) {
f(this.promise, this.onFulfilled, e);
}, h.prototype.callRejected = function(e) {
l.reject(this.promise, e);
}, h.prototype.otherCallRejected = function(e) {
f(this.promise, this.onRejected, e);
}, l.resolve = function(e, t) {
var r = p(c, t);
if ("error" === r.status) return l.reject(e, r.value);
var n = r.value;
if (n) d(e, n);
else {
e.state = a, e.outcome = t;
for (var i = -1, s = e.queue.length; ++i < s;) e.queue[i].callFulfilled(t);
}
return e;
}, l.reject = function(e, t) {
e.state = s, e.outcome = t;
for (var r = -1, n = e.queue.length; ++r < n;) e.queue[r].callRejected(t);
return e;
}, o.resolve = function(e) {
if (e instanceof this) return e;
return l.resolve(new this(u), e);
}, o.reject = function(e) {
var t = new this(u);
return l.reject(t, e);
}, o.all = function(e) {
var r = this;
if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject( new TypeError("must be an array"));
var n = e.length, i = !1;
if (!n) return this.resolve([]);
var s = new Array(n), a = 0, t = -1, o = new this(u);
for (; ++t < n;) h(e[t], t);
return o;
function h(e, t) {
r.resolve(e).then(function(e) {
s[t] = e, ++a !== n || i || (i = !0, l.resolve(o, s));
}, function(e) {
i || (i = !0, l.reject(o, e));
});
}
}, o.race = function(e) {
var t = this;
if ("[object Array]" !== Object.prototype.toString.call(e)) return this.reject( new TypeError("must be an array"));
var r = e.length, n = !1;
if (!r) return this.resolve([]);
var i = -1, s = new this(u);
for (; ++i < r;) a = e[i], t.resolve(a).then(function(e) {
n || (n = !0, l.resolve(s, e));
}, function(e) {
n || (n = !0, l.reject(s, e));
});
var a;
return s;
};
}, { immediate: 36 }],
38: [function(e, t, r) {
"use strict";
var n = {};
(0, e("./lib/utils/common").assign)(n, e("./lib/deflate"), e("./lib/inflate"), e("./lib/zlib/constants")), t.exports = n;
}, {
"./lib/deflate": 39,
"./lib/inflate": 40,
"./lib/utils/common": 41,
"./lib/zlib/constants": 44
}],
39: [function(e, t, r) {
"use strict";
var a = e("./zlib/deflate"), o = e("./utils/common"), h = e("./utils/strings"), i = e("./zlib/messages"), s = e("./zlib/zstream"), u = Object.prototype.toString, l = 0, f = -1, c = 0, d = 8;
function p(e) {
if (!(this instanceof p)) return new p(e);
this.options = o.assign({
level: f,
method: d,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: c,
to: ""
}, e || {});
var t = this.options;
t.raw && 0 < t.windowBits ? t.windowBits = -t.windowBits : t.gzip && 0 < t.windowBits && t.windowBits < 16 && (t.windowBits += 16), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new s(), this.strm.avail_out = 0;
var r = a.deflateInit2(this.strm, t.level, t.method, t.windowBits, t.memLevel, t.strategy);
if (r !== l) throw new Error(i[r]);
if (t.header && a.deflateSetHeader(this.strm, t.header), t.dictionary) {
var n;
if (n = "string" == typeof t.dictionary ? h.string2buf(t.dictionary) : "[object ArrayBuffer]" === u.call(t.dictionary) ? new Uint8Array(t.dictionary) : t.dictionary, (r = a.deflateSetDictionary(this.strm, n)) !== l) throw new Error(i[r]);
this._dict_set = !0;
}
}
function n(e, t) {
var r = new p(t);
if (r.push(e, !0), r.err) throw r.msg || i[r.err];
return r.result;
}
p.prototype.push = function(e, t) {
var r, n, i = this.strm, s = this.options.chunkSize;
if (this.ended) return !1;
n = t === ~~t ? t : !0 === t ? 4 : 0, "string" == typeof e ? i.input = h.string2buf(e) : "[object ArrayBuffer]" === u.call(e) ? i.input = new Uint8Array(e) : i.input = e, i.next_in = 0, i.avail_in = i.input.length;
do {
if (0 === i.avail_out && (i.output = new o.Buf8(s), i.next_out = 0, i.avail_out = s), 1 !== (r = a.deflate(i, n)) && r !== l) return this.onEnd(r), !(this.ended = !0);
0 !== i.avail_out && (0 !== i.avail_in || 4 !== n && 2 !== n) || ("string" === this.options.to ? this.onData(h.buf2binstring(o.shrinkBuf(i.output, i.next_out))) : this.onData(o.shrinkBuf(i.output, i.next_out)));
} while ((0 < i.avail_in || 0 === i.avail_out) && 1 !== r);
return 4 === n ? (r = a.deflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === l) : 2 !== n || (this.onEnd(l), !(i.avail_out = 0));
}, p.prototype.onData = function(e) {
this.chunks.push(e);
}, p.prototype.onEnd = function(e) {
e === l && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg;
}, r.Deflate = p, r.deflate = n, r.deflateRaw = function(e, t) {
return (t = t || {}).raw = !0, n(e, t);
}, r.gzip = function(e, t) {
return (t = t || {}).gzip = !0, n(e, t);
};
}, {
"./utils/common": 41,
"./utils/strings": 42,
"./zlib/deflate": 46,
"./zlib/messages": 51,
"./zlib/zstream": 53
}],
40: [function(e, t, r) {
"use strict";
var c = e("./zlib/inflate"), d = e("./utils/common"), p = e("./utils/strings"), m = e("./zlib/constants"), n = e("./zlib/messages"), i = e("./zlib/zstream"), s = e("./zlib/gzheader"), _ = Object.prototype.toString;
function a(e) {
if (!(this instanceof a)) return new a(e);
this.options = d.assign({
chunkSize: 16384,
windowBits: 0,
to: ""
}, e || {});
var t = this.options;
t.raw && 0 <= t.windowBits && t.windowBits < 16 && (t.windowBits = -t.windowBits, 0 === t.windowBits && (t.windowBits = -15)), !(0 <= t.windowBits && t.windowBits < 16) || e && e.windowBits || (t.windowBits += 32), 15 < t.windowBits && t.windowBits < 48 && 0 == (15 & t.windowBits) && (t.windowBits |= 15), this.err = 0, this.msg = "", this.ended = !1, this.chunks = [], this.strm = new i(), this.strm.avail_out = 0;
var r = c.inflateInit2(this.strm, t.windowBits);
if (r !== m.Z_OK) throw new Error(n[r]);
this.header = new s(), c.inflateGetHeader(this.strm, this.header);
}
function o(e, t) {
var r = new a(t);
if (r.push(e, !0), r.err) throw r.msg || n[r.err];
return r.result;
}
a.prototype.push = function(e, t) {
var r, n, i, s, a, o, h = this.strm, u = this.options.chunkSize, l = this.options.dictionary, f = !1;
if (this.ended) return !1;
n = t === ~~t ? t : !0 === t ? m.Z_FINISH : m.Z_NO_FLUSH, "string" == typeof e ? h.input = p.binstring2buf(e) : "[object ArrayBuffer]" === _.call(e) ? h.input = new Uint8Array(e) : h.input = e, h.next_in = 0, h.avail_in = h.input.length;
do {
if (0 === h.avail_out && (h.output = new d.Buf8(u), h.next_out = 0, h.avail_out = u), (r = c.inflate(h, m.Z_NO_FLUSH)) === m.Z_NEED_DICT && l && (o = "string" == typeof l ? p.string2buf(l) : "[object ArrayBuffer]" === _.call(l) ? new Uint8Array(l) : l, r = c.inflateSetDictionary(this.strm, o)), r === m.Z_BUF_ERROR && !0 === f && (r = m.Z_OK, f = !1), r !== m.Z_STREAM_END && r !== m.Z_OK) return this.onEnd(r), !(this.ended = !0);
h.next_out && (0 !== h.avail_out && r !== m.Z_STREAM_END && (0 !== h.avail_in || n !== m.Z_FINISH && n !== m.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i = p.utf8border(h.output, h.next_out), s = h.next_out - i, a = p.buf2string(h.output, i), h.next_out = s, h.avail_out = u - s, s && d.arraySet(h.output, h.output, i, s, 0), this.onData(a)) : this.onData(d.shrinkBuf(h.output, h.next_out)))), 0 === h.avail_in && 0 === h.avail_out && (f = !0);
} while ((0 < h.avail_in || 0 === h.avail_out) && r !== m.Z_STREAM_END);
return r === m.Z_STREAM_END && (n = m.Z_FINISH), n === m.Z_FINISH ? (r = c.inflateEnd(this.strm), this.onEnd(r), this.ended = !0, r === m.Z_OK) : n !== m.Z_SYNC_FLUSH || (this.onEnd(m.Z_OK), !(h.avail_out = 0));
}, a.prototype.onData = function(e) {
this.chunks.push(e);
}, a.prototype.onEnd = function(e) {
e === m.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d.flattenChunks(this.chunks)), this.chunks = [], this.err = e, this.msg = this.strm.msg;
}, r.Inflate = a, r.inflate = o, r.inflateRaw = function(e, t) {
return (t = t || {}).raw = !0, o(e, t);
}, r.ungzip = o;
}, {
"./utils/common": 41,
"./utils/strings": 42,
"./zlib/constants": 44,
"./zlib/gzheader": 47,
"./zlib/inflate": 49,
"./zlib/messages": 51,
"./zlib/zstream": 53
}],
41: [function(e, t, r) {
"use strict";
var n = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
r.assign = function(e) {
for (var t = Array.prototype.slice.call(arguments, 1); t.length;) {
var r = t.shift();
if (r) {
if ("object" != typeof r) throw new TypeError(r + "must be non-object");
for (var n in r) r.hasOwnProperty(n) && (e[n] = r[n]);
}
}
return e;
}, r.shrinkBuf = function(e, t) {
return e.length === t ? e : e.subarray ? e.subarray(0, t) : (e.length = t, e);
};
var i = {
arraySet: function(e, t, r, n, i) {
if (t.subarray && e.subarray) e.set(t.subarray(r, r + n), i);
else for (var s = 0; s < n; s++) e[i + s] = t[r + s];
},
flattenChunks: function(e) {
var t, r, n, i, s, a;
for (t = n = 0, r = e.length; t < r; t++) n += e[t].length;
for (a = new Uint8Array(n), t = i = 0, r = e.length; t < r; t++) s = e[t], a.set(s, i), i += s.length;
return a;
}
}, s = {
arraySet: function(e, t, r, n, i) {
for (var s = 0; s < n; s++) e[i + s] = t[r + s];
},
flattenChunks: function(e) {
return [].concat.apply([], e);
}
};
r.setTyped = function(e) {
e ? (r.Buf8 = Uint8Array, r.Buf16 = Uint16Array, r.Buf32 = Int32Array, r.assign(r, i)) : (r.Buf8 = Array, r.Buf16 = Array, r.Buf32 = Array, r.assign(r, s));
}, r.setTyped(n);
}, {}],
42: [function(e, t, r) {
"use strict";
var h = e("./common"), i = !0, s = !0;
try {
String.fromCharCode.apply(null, [0]);
} catch (e) {
i = !1;
}
try {
String.fromCharCode.apply(null, new Uint8Array(1));
} catch (e) {
s = !1;
}
for (var u = new h.Buf8(256), n = 0; n < 256; n++) u[n] = 252 <= n ? 6 : 248 <= n ? 5 : 240 <= n ? 4 : 224 <= n ? 3 : 192 <= n ? 2 : 1;
function l(e, t) {
if (t < 65537 && (e.subarray && s || !e.subarray && i)) return String.fromCharCode.apply(null, h.shrinkBuf(e, t));
for (var r = "", n = 0; n < t; n++) r += String.fromCharCode(e[n]);
return r;
}
u[254] = u[254] = 1, r.string2buf = function(e) {
var t, r, n, i, s, a = e.length, o = 0;
for (i = 0; i < a; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), o += r < 128 ? 1 : r < 2048 ? 2 : r < 65536 ? 3 : 4;
for (t = new h.Buf8(o), i = s = 0; s < o; i++) 55296 == (64512 & (r = e.charCodeAt(i))) && i + 1 < a && 56320 == (64512 & (n = e.charCodeAt(i + 1))) && (r = 65536 + (r - 55296 << 10) + (n - 56320), i++), r < 128 ? t[s++] = r : (r < 2048 ? t[s++] = 192 | r >>> 6 : (r < 65536 ? t[s++] = 224 | r >>> 12 : (t[s++] = 240 | r >>> 18, t[s++] = 128 | r >>> 12 & 63), t[s++] = 128 | r >>> 6 & 63), t[s++] = 128 | 63 & r);
return t;
}, r.buf2binstring = function(e) {
return l(e, e.length);
}, r.binstring2buf = function(e) {
for (var t = new h.Buf8(e.length), r = 0, n = t.length; r < n; r++) t[r] = e.charCodeAt(r);
return t;
}, r.buf2string = function(e, t) {
var r, n, i, s, a = t || e.length, o = new Array(2 * a);
for (r = n = 0; r < a;) if ((i = e[r++]) < 128) o[n++] = i;
else if (4 < (s = u[i])) o[n++] = 65533, r += s - 1;
else {
for (i &= 2 === s ? 31 : 3 === s ? 15 : 7; 1 < s && r < a;) i = i << 6 | 63 & e[r++], s--;
1 < s ? o[n++] = 65533 : i < 65536 ? o[n++] = i : (i -= 65536, o[n++] = 55296 | i >> 10 & 1023, o[n++] = 56320 | 1023 & i);
}
return l(o, n);
}, r.utf8border = function(e, t) {
var r;
for ((t = t || e.length) > e.length && (t = e.length), r = t - 1; 0 <= r && 128 == (192 & e[r]);) r--;
return r < 0 ? t : 0 === r ? t : r + u[e[r]] > t ? r : t;
};
}, { "./common": 41 }],
43: [function(e, t, r) {
"use strict";
t.exports = function(e, t, r, n) {
for (var i = 65535 & e | 0, s = e >>> 16 & 65535 | 0, a = 0; 0 !== r;) {
for (r -= a = 2e3 < r ? 2e3 : r; s = s + (i = i + t[n++] | 0) | 0, --a;);
i %= 65521, s %= 65521;
}
return i | s << 16 | 0;
};
}, {}],
44: [function(e, t, r) {
"use strict";
t.exports = {
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
Z_BUF_ERROR: -5,
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
Z_BINARY: 0,
Z_TEXT: 1,
Z_UNKNOWN: 2,
Z_DEFLATED: 8
};
}, {}],
45: [function(e, t, r) {
"use strict";
var o = function() {
for (var e, t = [], r = 0; r < 256; r++) {
e = r;
for (var n = 0; n < 8; n++) e = 1 & e ? 3988292384 ^ e >>> 1 : e >>> 1;
t[r] = e;
}
return t;
}();
t.exports = function(e, t, r, n) {
var i = o, s = n + r;
e ^= -1;
for (var a = n; a < s; a++) e = e >>> 8 ^ i[255 & (e ^ t[a])];
return -1 ^ e;
};
}, {}],
46: [function(e, t, r) {
"use strict";
var h, c = e("../utils/common"), u = e("./trees"), d = e("./adler32"), p = e("./crc32"), n = e("./messages"), l = 0, f = 4, m = 0, _ = -2, g = -1, b = 4, i = 2, v = 8, y = 9, s = 286, a = 30, o = 19, w = 2 * s + 1, k = 15, x = 3, S = 258, z = S + x + 1, C = 42, E = 113, A = 1, I = 2, O = 3, B = 4;
function R(e, t) {
return e.msg = n[t], t;
}
function T(e) {
return (e << 1) - (4 < e ? 9 : 0);
}
function D(e) {
for (var t = e.length; 0 <= --t;) e[t] = 0;
}
function F(e) {
var t = e.state, r = t.pending;
r > e.avail_out && (r = e.avail_out), 0 !== r && (c.arraySet(e.output, t.pending_buf, t.pending_out, r, e.next_out), e.next_out += r, t.pending_out += r, e.total_out += r, e.avail_out -= r, t.pending -= r, 0 === t.pending && (t.pending_out = 0));
}
function N(e, t) {
u._tr_flush_block(e, 0 <= e.block_start ? e.block_start : -1, e.strstart - e.block_start, t), e.block_start = e.strstart, F(e.strm);
}
function U(e, t) {
e.pending_buf[e.pending++] = t;
}
function P(e, t) {
e.pending_buf[e.pending++] = t >>> 8 & 255, e.pending_buf[e.pending++] = 255 & t;
}
function L(e, t) {
var r, n, i = e.max_chain_length, s = e.strstart, a = e.prev_length, o = e.nice_match, h = e.strstart > e.w_size - z ? e.strstart - (e.w_size - z) : 0, u = e.window, l = e.w_mask, f = e.prev, c = e.strstart + S, d = u[s + a - 1], p = u[s + a];
e.prev_length >= e.good_match && (i >>= 2), o > e.lookahead && (o = e.lookahead);
do
if (u[(r = t) + a] === p && u[r + a - 1] === d && u[r] === u[s] && u[++r] === u[s + 1]) {
s += 2, r++;
do ;
while (u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && u[++s] === u[++r] && s < c);
if (n = S - (c - s), s = c - S, a < n) {
if (e.match_start = t, o <= (a = n)) break;
d = u[s + a - 1], p = u[s + a];
}
}
while ((t = f[t & l]) > h && 0 != --i);
return a <= e.lookahead ? a : e.lookahead;
}
function j(e) {
var t, r, n, i, s, a, o, h, u, l, f = e.w_size;
do {
if (i = e.window_size - e.lookahead - e.strstart, e.strstart >= f + (f - z)) {
for (c.arraySet(e.window, e.window, f, f, 0), e.match_start -= f, e.strstart -= f, e.block_start -= f, t = r = e.hash_size; n = e.head[--t], e.head[t] = f <= n ? n - f : 0, --r;);
for (t = r = f; n = e.prev[--t], e.prev[t] = f <= n ? n - f : 0, --r;);
i += f;
}
if (0 === e.strm.avail_in) break;
if (a = e.strm, o = e.window, h = e.strstart + e.lookahead, u = i, l = void 0, l = a.avail_in, u < l && (l = u), r = 0 === l ? 0 : (a.avail_in -= l, c.arraySet(o, a.input, a.next_in, l, h), 1 === a.state.wrap ? a.adler = d(a.adler, o, l, h) : 2 === a.state.wrap && (a.adler = p(a.adler, o, l, h)), a.next_in += l, a.total_in += l, l), e.lookahead += r, e.lookahead + e.insert >= x) for (s = e.strstart - e.insert, e.ins_h = e.window[s], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + 1]) & e.hash_mask; e.insert && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[s + x - 1]) & e.hash_mask, e.prev[s & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = s, s++, e.insert--, !(e.lookahead + e.insert < x)););
} while (e.lookahead < z && 0 !== e.strm.avail_in);
}
function Z(e, t) {
for (var r, n;;) {
if (e.lookahead < z) {
if (j(e), e.lookahead < z && t === l) return A;
if (0 === e.lookahead) break;
}
if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 !== r && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r)), e.match_length >= x) if (n = u._tr_tally(e, e.strstart - e.match_start, e.match_length - x), e.lookahead -= e.match_length, e.match_length <= e.max_lazy_match && e.lookahead >= x) {
for (e.match_length--; e.strstart++, e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart, 0 != --e.match_length;);
e.strstart++;
} else e.strstart += e.match_length, e.match_length = 0, e.ins_h = e.window[e.strstart], e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + 1]) & e.hash_mask;
else n = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++;
if (n && (N(e, !1), 0 === e.strm.avail_out)) return A;
}
return e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
}
function W(e, t) {
for (var r, n, i;;) {
if (e.lookahead < z) {
if (j(e), e.lookahead < z && t === l) return A;
if (0 === e.lookahead) break;
}
if (r = 0, e.lookahead >= x && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), e.prev_length = e.match_length, e.prev_match = e.match_start, e.match_length = x - 1, 0 !== r && e.prev_length < e.max_lazy_match && e.strstart - r <= e.w_size - z && (e.match_length = L(e, r), e.match_length <= 5 && (1 === e.strategy || e.match_length === x && 4096 < e.strstart - e.match_start) && (e.match_length = x - 1)), e.prev_length >= x && e.match_length <= e.prev_length) {
for (i = e.strstart + e.lookahead - x, n = u._tr_tally(e, e.strstart - 1 - e.prev_match, e.prev_length - x), e.lookahead -= e.prev_length - 1, e.prev_length -= 2; ++e.strstart <= i && (e.ins_h = (e.ins_h << e.hash_shift ^ e.window[e.strstart + x - 1]) & e.hash_mask, r = e.prev[e.strstart & e.w_mask] = e.head[e.ins_h], e.head[e.ins_h] = e.strstart), 0 != --e.prev_length;);
if (e.match_available = 0, e.match_length = x - 1, e.strstart++, n && (N(e, !1), 0 === e.strm.avail_out)) return A;
} else if (e.match_available) {
if ((n = u._tr_tally(e, 0, e.window[e.strstart - 1])) && N(e, !1), e.strstart++, e.lookahead--, 0 === e.strm.avail_out) return A;
} else e.match_available = 1, e.strstart++, e.lookahead--;
}
return e.match_available && (n = u._tr_tally(e, 0, e.window[e.strstart - 1]), e.match_available = 0), e.insert = e.strstart < x - 1 ? e.strstart : x - 1, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
}
function M(e, t, r, n, i) {
this.good_length = e, this.max_lazy = t, this.nice_length = r, this.max_chain = n, this.func = i;
}
function H() {
this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c.Buf16(2 * w), this.dyn_dtree = new c.Buf16(2 * (2 * a + 1)), this.bl_tree = new c.Buf16(2 * (2 * o + 1)), D(this.dyn_ltree), D(this.dyn_dtree), D(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c.Buf16(k + 1), this.heap = new c.Buf16(2 * s + 1), D(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c.Buf16(2 * s + 1), D(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
}
function G(e) {
var t;
return e && e.state ? (e.total_in = e.total_out = 0, e.data_type = i, (t = e.state).pending = 0, t.pending_out = 0, t.wrap < 0 && (t.wrap = -t.wrap), t.status = t.wrap ? C : E, e.adler = 2 === t.wrap ? 0 : 1, t.last_flush = l, u._tr_init(t), m) : R(e, _);
}
function K(e) {
var t = G(e);
return t === m && function(e) {
e.window_size = 2 * e.w_size, D(e.head), e.max_lazy_match = h[e.level].max_lazy, e.good_match = h[e.level].good_length, e.nice_match = h[e.level].nice_length, e.max_chain_length = h[e.level].max_chain, e.strstart = 0, e.block_start = 0, e.lookahead = 0, e.insert = 0, e.match_length = e.prev_length = x - 1, e.match_available = 0, e.ins_h = 0;
}(e.state), t;
}
function Y(e, t, r, n, i, s) {
if (!e) return _;
var a = 1;
if (t === g && (t = 6), n < 0 ? (a = 0, n = -n) : 15 < n && (a = 2, n -= 16), i < 1 || y < i || r !== v || n < 8 || 15 < n || t < 0 || 9 < t || s < 0 || b < s) return R(e, _);
8 === n && (n = 9);
var o = new H();
return (e.state = o).strm = e, o.wrap = a, o.gzhead = null, o.w_bits = n, o.w_size = 1 << o.w_bits, o.w_mask = o.w_size - 1, o.hash_bits = i + 7, o.hash_size = 1 << o.hash_bits, o.hash_mask = o.hash_size - 1, o.hash_shift = ~~((o.hash_bits + x - 1) / x), o.window = new c.Buf8(2 * o.w_size), o.head = new c.Buf16(o.hash_size), o.prev = new c.Buf16(o.w_size), o.lit_bufsize = 1 << i + 6, o.pending_buf_size = 4 * o.lit_bufsize, o.pending_buf = new c.Buf8(o.pending_buf_size), o.d_buf = 1 * o.lit_bufsize, o.l_buf = 3 * o.lit_bufsize, o.level = t, o.strategy = s, o.method = r, K(e);
}
h = [
new M(0, 0, 0, 0, function(e, t) {
var r = 65535;
for (r > e.pending_buf_size - 5 && (r = e.pending_buf_size - 5);;) {
if (e.lookahead <= 1) {
if (j(e), 0 === e.lookahead && t === l) return A;
if (0 === e.lookahead) break;
}
e.strstart += e.lookahead, e.lookahead = 0;
var n = e.block_start + r;
if ((0 === e.strstart || e.strstart >= n) && (e.lookahead = e.strstart - n, e.strstart = n, N(e, !1), 0 === e.strm.avail_out)) return A;
if (e.strstart - e.block_start >= e.w_size - z && (N(e, !1), 0 === e.strm.avail_out)) return A;
}
return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : (e.strstart > e.block_start && (N(e, !1), e.strm.avail_out), A);
}),
new M(4, 4, 8, 4, Z),
new M(4, 5, 16, 8, Z),
new M(4, 6, 32, 32, Z),
new M(4, 4, 16, 16, W),
new M(8, 16, 32, 32, W),
new M(8, 16, 128, 128, W),
new M(8, 32, 128, 256, W),
new M(32, 128, 258, 1024, W),
new M(32, 258, 258, 4096, W)
], r.deflateInit = function(e, t) {
return Y(e, t, v, 15, 8, 0);
}, r.deflateInit2 = Y, r.deflateReset = K, r.deflateResetKeep = G, r.deflateSetHeader = function(e, t) {
return e && e.state ? 2 !== e.state.wrap ? _ : (e.state.gzhead = t, m) : _;
}, r.deflate = function(e, t) {
var r, n, i, s;
if (!e || !e.state || 5 < t || t < 0) return e ? R(e, _) : _;
if (n = e.state, !e.output || !e.input && 0 !== e.avail_in || 666 === n.status && t !== f) return R(e, 0 === e.avail_out ? -5 : _);
if (n.strm = e, r = n.last_flush, n.last_flush = t, n.status === C) if (2 === n.wrap) e.adler = 0, U(n, 31), U(n, 139), U(n, 8), n.gzhead ? (U(n, (n.gzhead.text ? 1 : 0) + (n.gzhead.hcrc ? 2 : 0) + (n.gzhead.extra ? 4 : 0) + (n.gzhead.name ? 8 : 0) + (n.gzhead.comment ? 16 : 0)), U(n, 255 & n.gzhead.time), U(n, n.gzhead.time >> 8 & 255), U(n, n.gzhead.time >> 16 & 255), U(n, n.gzhead.time >> 24 & 255), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 255 & n.gzhead.os), n.gzhead.extra && n.gzhead.extra.length && (U(n, 255 & n.gzhead.extra.length), U(n, n.gzhead.extra.length >> 8 & 255)), n.gzhead.hcrc && (e.adler = p(e.adler, n.pending_buf, n.pending, 0)), n.gzindex = 0, n.status = 69) : (U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 0), U(n, 9 === n.level ? 2 : 2 <= n.strategy || n.level < 2 ? 4 : 0), U(n, 3), n.status = E);
else {
var a = v + (n.w_bits - 8 << 4) << 8;
a |= (2 <= n.strategy || n.level < 2 ? 0 : n.level < 6 ? 1 : 6 === n.level ? 2 : 3) << 6, 0 !== n.strstart && (a |= 32), a += 31 - a % 31, n.status = E, P(n, a), 0 !== n.strstart && (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), e.adler = 1;
}
if (69 === n.status) if (n.gzhead.extra) {
for (i = n.pending; n.gzindex < (65535 & n.gzhead.extra.length) && (n.pending !== n.pending_buf_size || (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending !== n.pending_buf_size));) U(n, 255 & n.gzhead.extra[n.gzindex]), n.gzindex++;
n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), n.gzindex === n.gzhead.extra.length && (n.gzindex = 0, n.status = 73);
} else n.status = 73;
if (73 === n.status) if (n.gzhead.name) {
i = n.pending;
do {
if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) {
s = 1;
break;
}
s = n.gzindex < n.gzhead.name.length ? 255 & n.gzhead.name.charCodeAt(n.gzindex++) : 0, U(n, s);
} while (0 !== s);
n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.gzindex = 0, n.status = 91);
} else n.status = 91;
if (91 === n.status) if (n.gzhead.comment) {
i = n.pending;
do {
if (n.pending === n.pending_buf_size && (n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), F(e), i = n.pending, n.pending === n.pending_buf_size)) {
s = 1;
break;
}
s = n.gzindex < n.gzhead.comment.length ? 255 & n.gzhead.comment.charCodeAt(n.gzindex++) : 0, U(n, s);
} while (0 !== s);
n.gzhead.hcrc && n.pending > i && (e.adler = p(e.adler, n.pending_buf, n.pending - i, i)), 0 === s && (n.status = 103);
} else n.status = 103;
if (103 === n.status && (n.gzhead.hcrc ? (n.pending + 2 > n.pending_buf_size && F(e), n.pending + 2 <= n.pending_buf_size && (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), e.adler = 0, n.status = E)) : n.status = E), 0 !== n.pending) {
if (F(e), 0 === e.avail_out) return n.last_flush = -1, m;
} else if (0 === e.avail_in && T(t) <= T(r) && t !== f) return R(e, -5);
if (666 === n.status && 0 !== e.avail_in) return R(e, -5);
if (0 !== e.avail_in || 0 !== n.lookahead || t !== l && 666 !== n.status) {
var o = 2 === n.strategy ? function(e, t) {
for (var r;;) {
if (0 === e.lookahead && (j(e), 0 === e.lookahead)) {
if (t === l) return A;
break;
}
if (e.match_length = 0, r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++, r && (N(e, !1), 0 === e.strm.avail_out)) return A;
}
return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
}(n, t) : 3 === n.strategy ? function(e, t) {
for (var r, n, i, s, a = e.window;;) {
if (e.lookahead <= S) {
if (j(e), e.lookahead <= S && t === l) return A;
if (0 === e.lookahead) break;
}
if (e.match_length = 0, e.lookahead >= x && 0 < e.strstart && (n = a[i = e.strstart - 1]) === a[++i] && n === a[++i] && n === a[++i]) {
s = e.strstart + S;
do ;
while (n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && n === a[++i] && i < s);
e.match_length = S - (s - i), e.match_length > e.lookahead && (e.match_length = e.lookahead);
}
if (e.match_length >= x ? (r = u._tr_tally(e, 1, e.match_length - x), e.lookahead -= e.match_length, e.strstart += e.match_length, e.match_length = 0) : (r = u._tr_tally(e, 0, e.window[e.strstart]), e.lookahead--, e.strstart++), r && (N(e, !1), 0 === e.strm.avail_out)) return A;
}
return e.insert = 0, t === f ? (N(e, !0), 0 === e.strm.avail_out ? O : B) : e.last_lit && (N(e, !1), 0 === e.strm.avail_out) ? A : I;
}(n, t) : h[n.level].func(n, t);
if (o !== O && o !== B || (n.status = 666), o === A || o === O) return 0 === e.avail_out && (n.last_flush = -1), m;
if (o === I && (1 === t ? u._tr_align(n) : 5 !== t && (u._tr_stored_block(n, 0, 0, !1), 3 === t && (D(n.head), 0 === n.lookahead && (n.strstart = 0, n.block_start = 0, n.insert = 0))), F(e), 0 === e.avail_out)) return n.last_flush = -1, m;
}
return t !== f ? m : n.wrap <= 0 ? 1 : (2 === n.wrap ? (U(n, 255 & e.adler), U(n, e.adler >> 8 & 255), U(n, e.adler >> 16 & 255), U(n, e.adler >> 24 & 255), U(n, 255 & e.total_in), U(n, e.total_in >> 8 & 255), U(n, e.total_in >> 16 & 255), U(n, e.total_in >> 24 & 255)) : (P(n, e.adler >>> 16), P(n, 65535 & e.adler)), F(e), 0 < n.wrap && (n.wrap = -n.wrap), 0 !== n.pending ? m : 1);
}, r.deflateEnd = function(e) {
var t;
return e && e.state ? (t = e.state.status) !== C && 69 !== t && 73 !== t && 91 !== t && 103 !== t && t !== E && 666 !== t ? R(e, _) : (e.state = null, t === E ? R(e, -3) : m) : _;
}, r.deflateSetDictionary = function(e, t) {
var r, n, i, s, a, o, h, u, l = t.length;
if (!e || !e.state) return _;
if (2 === (s = (r = e.state).wrap) || 1 === s && r.status !== C || r.lookahead) return _;
for (1 === s && (e.adler = d(e.adler, t, l, 0)), r.wrap = 0, l >= r.w_size && (0 === s && (D(r.head), r.strstart = 0, r.block_start = 0, r.insert = 0), u = new c.Buf8(r.w_size), c.arraySet(u, t, l - r.w_size, r.w_size, 0), t = u, l = r.w_size), a = e.avail_in, o = e.next_in, h = e.input, e.avail_in = l, e.next_in = 0, e.input = t, j(r); r.lookahead >= x;) {
for (n = r.strstart, i = r.lookahead - (x - 1); r.ins_h = (r.ins_h << r.hash_shift ^ r.window[n + x - 1]) & r.hash_mask, r.prev[n & r.w_mask] = r.head[r.ins_h], r.head[r.ins_h] = n, n++, --i;);
r.strstart = n, r.lookahead = x - 1, j(r);
}
return r.strstart += r.lookahead, r.block_start = r.strstart, r.insert = r.lookahead, r.lookahead = 0, r.match_length = r.prev_length = x - 1, r.match_available = 0, e.next_in = o, e.input = h, e.avail_in = a, r.wrap = s, m;
}, r.deflateInfo = "pako deflate (from Nodeca project)";
}, {
"../utils/common": 41,
"./adler32": 43,
"./crc32": 45,
"./messages": 51,
"./trees": 52
}],
47: [function(e, t, r) {
"use strict";
t.exports = function() {
this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = !1;
};
}, {}],
48: [function(e, t, r) {
"use strict";
t.exports = function(e, t) {
var r = e.state, n = e.next_in, i, s, a, o, h, u, l, f, c, d, p, m, _, g, b, v, y, w, k, x, S, z = e.input, C;
i = n + (e.avail_in - 5), s = e.next_out, C = e.output, a = s - (t - e.avail_out), o = s + (e.avail_out - 257), h = r.dmax, u = r.wsize, l = r.whave, f = r.wnext, c = r.window, d = r.hold, p = r.bits, m = r.lencode, _ = r.distcode, g = (1 << r.lenbits) - 1, b = (1 << r.distbits) - 1;
e: do {
p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = m[d & g];
t: for (;;) {
if (d >>>= y = v >>> 24, p -= y, 0 === (y = v >>> 16 & 255)) C[s++] = 65535 & v;
else {
if (!(16 & y)) {
if (0 == (64 & y)) {
v = m[(65535 & v) + (d & (1 << y) - 1)];
continue t;
}
if (32 & y) {
r.mode = 12;
break e;
}
e.msg = "invalid literal/length code", r.mode = 30;
break e;
}
w = 65535 & v, (y &= 15) && (p < y && (d += z[n++] << p, p += 8), w += d & (1 << y) - 1, d >>>= y, p -= y), p < 15 && (d += z[n++] << p, p += 8, d += z[n++] << p, p += 8), v = _[d & b];
r: for (;;) {
if (d >>>= y = v >>> 24, p -= y, !(16 & (y = v >>> 16 & 255))) {
if (0 == (64 & y)) {
v = _[(65535 & v) + (d & (1 << y) - 1)];
continue r;
}
e.msg = "invalid distance code", r.mode = 30;
break e;
}
if (k = 65535 & v, p < (y &= 15) && (d += z[n++] << p, (p += 8) < y && (d += z[n++] << p, p += 8)), h < (k += d & (1 << y) - 1)) {
e.msg = "invalid distance too far back", r.mode = 30;
break e;
}
if (d >>>= y, p -= y, (y = s - a) < k) {
if (l < (y = k - y) && r.sane) {
e.msg = "invalid distance too far back", r.mode = 30;
break e;
}
if (S = c, (x = 0) === f) {
if (x += u - y, y < w) {
for (w -= y; C[s++] = c[x++], --y;);
x = s - k, S = C;
}
} else if (f < y) {
if (x += u + f - y, (y -= f) < w) {
for (w -= y; C[s++] = c[x++], --y;);
if (x = 0, f < w) {
for (w -= y = f; C[s++] = c[x++], --y;);
x = s - k, S = C;
}
}
} else if (x += f - y, y < w) {
for (w -= y; C[s++] = c[x++], --y;);
x = s - k, S = C;
}
for (; 2 < w;) C[s++] = S[x++], C[s++] = S[x++], C[s++] = S[x++], w -= 3;
w && (C[s++] = S[x++], 1 < w && (C[s++] = S[x++]));
} else {
for (x = s - k; C[s++] = C[x++], C[s++] = C[x++], C[s++] = C[x++], 2 < (w -= 3););
w && (C[s++] = C[x++], 1 < w && (C[s++] = C[x++]));
}
break;
}
}
break;
}
} while (n < i && s < o);
n -= w = p >> 3, d &= (1 << (p -= w << 3)) - 1, e.next_in = n, e.next_out = s, e.avail_in = n < i ? i - n + 5 : 5 - (n - i), e.avail_out = s < o ? o - s + 257 : 257 - (s - o), r.hold = d, r.bits = p;
};
}, {}],
49: [function(e, t, r) {
"use strict";
var I = e("../utils/common"), O = e("./adler32"), B = e("./crc32"), R = e("./inffast"), T = e("./inftrees"), D = 1, F = 2, N = 0, U = -2, P = 1, n = 852, i = 592;
function L(e) {
return (e >>> 24 & 255) + (e >>> 8 & 65280) + ((65280 & e) << 8) + ((255 & e) << 24);
}
function s() {
this.mode = 0, this.last = !1, this.wrap = 0, this.havedict = !1, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I.Buf16(320), this.work = new I.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
}
function a(e) {
var t;
return e && e.state ? (t = e.state, e.total_in = e.total_out = t.total = 0, e.msg = "", t.wrap && (e.adler = 1 & t.wrap), t.mode = P, t.last = 0, t.havedict = 0, t.dmax = 32768, t.head = null, t.hold = 0, t.bits = 0, t.lencode = t.lendyn = new I.Buf32(n), t.distcode = t.distdyn = new I.Buf32(i), t.sane = 1, t.back = -1, N) : U;
}
function o(e) {
var t;
return e && e.state ? ((t = e.state).wsize = 0, t.whave = 0, t.wnext = 0, a(e)) : U;
}
function h(e, t) {
var r, n;
return e && e.state ? (n = e.state, t < 0 ? (r = 0, t = -t) : (r = 1 + (t >> 4), t < 48 && (t &= 15)), t && (t < 8 || 15 < t) ? U : (null !== n.window && n.wbits !== t && (n.window = null), n.wrap = r, n.wbits = t, o(e))) : U;
}
function u(e, t) {
var r, n;
return e ? (n = new s(), (e.state = n).window = null, (r = h(e, t)) !== N && (e.state = null), r) : U;
}
var l, f, c = !0;
function j(e) {
if (c) {
var t;
for (l = new I.Buf32(512), f = new I.Buf32(32), t = 0; t < 144;) e.lens[t++] = 8;
for (; t < 256;) e.lens[t++] = 9;
for (; t < 280;) e.lens[t++] = 7;
for (; t < 288;) e.lens[t++] = 8;
for (T(D, e.lens, 0, 288, l, 0, e.work, { bits: 9 }), t = 0; t < 32;) e.lens[t++] = 5;
T(F, e.lens, 0, 32, f, 0, e.work, { bits: 5 }), c = !1;
}
e.lencode = l, e.lenbits = 9, e.distcode = f, e.distbits = 5;
}
function Z(e, t, r, n) {
var i, s = e.state;
return null === s.window && (s.wsize = 1 << s.wbits, s.wnext = 0, s.whave = 0, s.window = new I.Buf8(s.wsize)), n >= s.wsize ? (I.arraySet(s.window, t, r - s.wsize, s.wsize, 0), s.wnext = 0, s.whave = s.wsize) : (n < (i = s.wsize - s.wnext) && (i = n), I.arraySet(s.window, t, r - n, i, s.wnext), (n -= i) ? (I.arraySet(s.window, t, r - n, n, 0), s.wnext = n, s.whave = s.wsize) : (s.wnext += i, s.wnext === s.wsize && (s.wnext = 0), s.whave < s.wsize && (s.whave += i))), 0;
}
r.inflateReset = o, r.inflateReset2 = h, r.inflateResetKeep = a, r.inflateInit = function(e) {
return u(e, 15);
}, r.inflateInit2 = u, r.inflate = function(e, t) {
var r, n, i, s, a, o, h, u, l, f, c, d, p, m, _, g, b, v, y, w, k, x, S, z, C = 0, E = new I.Buf8(4), A = [
16,
17,
18,
0,
8,
7,
9,
6,
10,
5,
11,
4,
12,
3,
13,
2,
14,
1,
15
];
if (!e || !e.state || !e.output || !e.input && 0 !== e.avail_in) return U;
12 === (r = e.state).mode && (r.mode = 13), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, f = o, c = h, x = N;
e: for (;;) switch (r.mode) {
case P:
if (0 === r.wrap) {
r.mode = 13;
break;
}
for (; l < 16;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (2 & r.wrap && 35615 === u) {
E[r.check = 0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0), l = u = 0, r.mode = 2;
break;
}
if (r.flags = 0, r.head && (r.head.done = !1), !(1 & r.wrap) || (((255 & u) << 8) + (u >> 8)) % 31) {
e.msg = "incorrect header check", r.mode = 30;
break;
}
if (8 != (15 & u)) {
e.msg = "unknown compression method", r.mode = 30;
break;
}
if (l -= 4, k = 8 + (15 & (u >>>= 4)), 0 === r.wbits) r.wbits = k;
else if (k > r.wbits) {
e.msg = "invalid window size", r.mode = 30;
break;
}
r.dmax = 1 << k, e.adler = r.check = 1, r.mode = 512 & u ? 10 : 12, l = u = 0;
break;
case 2:
for (; l < 16;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (r.flags = u, 8 != (255 & r.flags)) {
e.msg = "unknown compression method", r.mode = 30;
break;
}
if (57344 & r.flags) {
e.msg = "unknown header flags set", r.mode = 30;
break;
}
r.head && (r.head.text = u >> 8 & 1), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 3;
case 3:
for (; l < 32;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.head && (r.head.time = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, E[2] = u >>> 16 & 255, E[3] = u >>> 24 & 255, r.check = B(r.check, E, 4, 0)), l = u = 0, r.mode = 4;
case 4:
for (; l < 16;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.head && (r.head.xflags = 255 & u, r.head.os = u >> 8), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0, r.mode = 5;
case 5:
if (1024 & r.flags) {
for (; l < 16;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.length = u, r.head && (r.head.extra_len = u), 512 & r.flags && (E[0] = 255 & u, E[1] = u >>> 8 & 255, r.check = B(r.check, E, 2, 0)), l = u = 0;
} else r.head && (r.head.extra = null);
r.mode = 6;
case 6:
if (1024 & r.flags && (o < (d = r.length) && (d = o), d && (r.head && (k = r.head.extra_len - r.length, r.head.extra || (r.head.extra = new Array(r.head.extra_len)), I.arraySet(r.head.extra, n, s, d, k)), 512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, r.length -= d), r.length)) break e;
r.length = 0, r.mode = 7;
case 7:
if (2048 & r.flags) {
if (0 === o) break e;
for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.name += String.fromCharCode(k)), k && d < o;);
if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e;
} else r.head && (r.head.name = null);
r.length = 0, r.mode = 8;
case 8:
if (4096 & r.flags) {
if (0 === o) break e;
for (d = 0; k = n[s + d++], r.head && k && r.length < 65536 && (r.head.comment += String.fromCharCode(k)), k && d < o;);
if (512 & r.flags && (r.check = B(r.check, n, d, s)), o -= d, s += d, k) break e;
} else r.head && (r.head.comment = null);
r.mode = 9;
case 9:
if (512 & r.flags) {
for (; l < 16;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (u !== (65535 & r.check)) {
e.msg = "header crc mismatch", r.mode = 30;
break;
}
l = u = 0;
}
r.head && (r.head.hcrc = r.flags >> 9 & 1, r.head.done = !0), e.adler = r.check = 0, r.mode = 12;
break;
case 10:
for (; l < 32;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
e.adler = r.check = L(u), l = u = 0, r.mode = 11;
case 11:
if (0 === r.havedict) return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, 2;
e.adler = r.check = 1, r.mode = 12;
case 12: if (5 === t || 6 === t) break e;
case 13:
if (r.last) {
u >>>= 7 & l, l -= 7 & l, r.mode = 27;
break;
}
for (; l < 3;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
switch (r.last = 1 & u, l -= 1, 3 & (u >>>= 1)) {
case 0:
r.mode = 14;
break;
case 1:
if (j(r), r.mode = 20, 6 !== t) break;
u >>>= 2, l -= 2;
break e;
case 2:
r.mode = 17;
break;
case 3: e.msg = "invalid block type", r.mode = 30;
}
u >>>= 2, l -= 2;
break;
case 14:
for (u >>>= 7 & l, l -= 7 & l; l < 32;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if ((65535 & u) != (u >>> 16 ^ 65535)) {
e.msg = "invalid stored block lengths", r.mode = 30;
break;
}
if (r.length = 65535 & u, l = u = 0, r.mode = 15, 6 === t) break e;
case 15: r.mode = 16;
case 16:
if (d = r.length) {
if (o < d && (d = o), h < d && (d = h), 0 === d) break e;
I.arraySet(i, n, s, d, a), o -= d, s += d, h -= d, a += d, r.length -= d;
break;
}
r.mode = 12;
break;
case 17:
for (; l < 14;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (r.nlen = 257 + (31 & u), u >>>= 5, l -= 5, r.ndist = 1 + (31 & u), u >>>= 5, l -= 5, r.ncode = 4 + (15 & u), u >>>= 4, l -= 4, 286 < r.nlen || 30 < r.ndist) {
e.msg = "too many length or distance symbols", r.mode = 30;
break;
}
r.have = 0, r.mode = 18;
case 18:
for (; r.have < r.ncode;) {
for (; l < 3;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.lens[A[r.have++]] = 7 & u, u >>>= 3, l -= 3;
}
for (; r.have < 19;) r.lens[A[r.have++]] = 0;
if (r.lencode = r.lendyn, r.lenbits = 7, S = { bits: r.lenbits }, x = T(0, r.lens, 0, 19, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) {
e.msg = "invalid code lengths set", r.mode = 30;
break;
}
r.have = 0, r.mode = 19;
case 19:
for (; r.have < r.nlen + r.ndist;) {
for (; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (b < 16) u >>>= _, l -= _, r.lens[r.have++] = b;
else {
if (16 === b) {
for (z = _ + 2; l < z;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (u >>>= _, l -= _, 0 === r.have) {
e.msg = "invalid bit length repeat", r.mode = 30;
break;
}
k = r.lens[r.have - 1], d = 3 + (3 & u), u >>>= 2, l -= 2;
} else if (17 === b) {
for (z = _ + 3; l < z;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
l -= _, k = 0, d = 3 + (7 & (u >>>= _)), u >>>= 3, l -= 3;
} else {
for (z = _ + 7; l < z;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
l -= _, k = 0, d = 11 + (127 & (u >>>= _)), u >>>= 7, l -= 7;
}
if (r.have + d > r.nlen + r.ndist) {
e.msg = "invalid bit length repeat", r.mode = 30;
break;
}
for (; d--;) r.lens[r.have++] = k;
}
}
if (30 === r.mode) break;
if (0 === r.lens[256]) {
e.msg = "invalid code -- missing end-of-block", r.mode = 30;
break;
}
if (r.lenbits = 9, S = { bits: r.lenbits }, x = T(D, r.lens, 0, r.nlen, r.lencode, 0, r.work, S), r.lenbits = S.bits, x) {
e.msg = "invalid literal/lengths set", r.mode = 30;
break;
}
if (r.distbits = 6, r.distcode = r.distdyn, S = { bits: r.distbits }, x = T(F, r.lens, r.nlen, r.ndist, r.distcode, 0, r.work, S), r.distbits = S.bits, x) {
e.msg = "invalid distances set", r.mode = 30;
break;
}
if (r.mode = 20, 6 === t) break e;
case 20: r.mode = 21;
case 21:
if (6 <= o && 258 <= h) {
e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, R(e, c), a = e.next_out, i = e.output, h = e.avail_out, s = e.next_in, n = e.input, o = e.avail_in, u = r.hold, l = r.bits, 12 === r.mode && (r.back = -1);
break;
}
for (r.back = 0; g = (C = r.lencode[u & (1 << r.lenbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (g && 0 == (240 & g)) {
for (v = _, y = g, w = b; g = (C = r.lencode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
u >>>= v, l -= v, r.back += v;
}
if (u >>>= _, l -= _, r.back += _, r.length = b, 0 === g) {
r.mode = 26;
break;
}
if (32 & g) {
r.back = -1, r.mode = 12;
break;
}
if (64 & g) {
e.msg = "invalid literal/length code", r.mode = 30;
break;
}
r.extra = 15 & g, r.mode = 22;
case 22:
if (r.extra) {
for (z = r.extra; l < z;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.length += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra;
}
r.was = r.length, r.mode = 23;
case 23:
for (; g = (C = r.distcode[u & (1 << r.distbits) - 1]) >>> 16 & 255, b = 65535 & C, !((_ = C >>> 24) <= l);) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (0 == (240 & g)) {
for (v = _, y = g, w = b; g = (C = r.distcode[w + ((u & (1 << v + y) - 1) >> v)]) >>> 16 & 255, b = 65535 & C, !(v + (_ = C >>> 24) <= l);) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
u >>>= v, l -= v, r.back += v;
}
if (u >>>= _, l -= _, r.back += _, 64 & g) {
e.msg = "invalid distance code", r.mode = 30;
break;
}
r.offset = b, r.extra = 15 & g, r.mode = 24;
case 24:
if (r.extra) {
for (z = r.extra; l < z;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
r.offset += u & (1 << r.extra) - 1, u >>>= r.extra, l -= r.extra, r.back += r.extra;
}
if (r.offset > r.dmax) {
e.msg = "invalid distance too far back", r.mode = 30;
break;
}
r.mode = 25;
case 25:
if (0 === h) break e;
if (d = c - h, r.offset > d) {
if ((d = r.offset - d) > r.whave && r.sane) {
e.msg = "invalid distance too far back", r.mode = 30;
break;
}
p = d > r.wnext ? (d -= r.wnext, r.wsize - d) : r.wnext - d, d > r.length && (d = r.length), m = r.window;
} else m = i, p = a - r.offset, d = r.length;
for (h < d && (d = h), h -= d, r.length -= d; i[a++] = m[p++], --d;);
0 === r.length && (r.mode = 21);
break;
case 26:
if (0 === h) break e;
i[a++] = r.length, h--, r.mode = 21;
break;
case 27:
if (r.wrap) {
for (; l < 32;) {
if (0 === o) break e;
o--, u |= n[s++] << l, l += 8;
}
if (c -= h, e.total_out += c, r.total += c, c && (e.adler = r.check = r.flags ? B(r.check, i, c, a - c) : O(r.check, i, c, a - c)), c = h, (r.flags ? u : L(u)) !== r.check) {
e.msg = "incorrect data check", r.mode = 30;
break;
}
l = u = 0;
}
r.mode = 28;
case 28:
if (r.wrap && r.flags) {
for (; l < 32;) {
if (0 === o) break e;
o--, u += n[s++] << l, l += 8;
}
if (u !== (4294967295 & r.total)) {
e.msg = "incorrect length check", r.mode = 30;
break;
}
l = u = 0;
}
r.mode = 29;
case 29:
x = 1;
break e;
case 30:
x = -3;
break e;
case 31: return -4;
case 32:
default: return U;
}
return e.next_out = a, e.avail_out = h, e.next_in = s, e.avail_in = o, r.hold = u, r.bits = l, (r.wsize || c !== e.avail_out && r.mode < 30 && (r.mode < 27 || 4 !== t)) && Z(e, e.output, e.next_out, c - e.avail_out) ? (r.mode = 31, -4) : (f -= e.avail_in, c -= e.avail_out, e.total_in += f, e.total_out += c, r.total += c, r.wrap && c && (e.adler = r.check = r.flags ? B(r.check, i, c, e.next_out - c) : O(r.check, i, c, e.next_out - c)), e.data_type = r.bits + (r.last ? 64 : 0) + (12 === r.mode ? 128 : 0) + (20 === r.mode || 15 === r.mode ? 256 : 0), (0 == f && 0 === c || 4 === t) && x === N && (x = -5), x);
}, r.inflateEnd = function(e) {
if (!e || !e.state) return U;
var t = e.state;
return t.window && (t.window = null), e.state = null, N;
}, r.inflateGetHeader = function(e, t) {
var r;
return e && e.state ? 0 == (2 & (r = e.state).wrap) ? U : ((r.head = t).done = !1, N) : U;
}, r.inflateSetDictionary = function(e, t) {
var r, n = t.length;
return e && e.state ? 0 !== (r = e.state).wrap && 11 !== r.mode ? U : 11 === r.mode && O(1, t, n, 0) !== r.check ? -3 : Z(e, t, n, n) ? (r.mode = 31, -4) : (r.havedict = 1, N) : U;
}, r.inflateInfo = "pako inflate (from Nodeca project)";
}, {
"../utils/common": 41,
"./adler32": 43,
"./crc32": 45,
"./inffast": 48,
"./inftrees": 50
}],
50: [function(e, t, r) {
"use strict";
var D = e("../utils/common"), F = [
3,
4,
5,
6,
7,
8,
9,
10,
11,
13,
15,
17,
19,
23,
27,
31,
35,
43,
51,
59,
67,
83,
99,
115,
131,
163,
195,
227,
258,
0,
0
], N = [
16,
16,
16,
16,
16,
16,
16,
16,
17,
17,
17,
17,
18,
18,
18,
18,
19,
19,
19,
19,
20,
20,
20,
20,
21,
21,
21,
21,
16,
72,
78
], U = [
1,
2,
3,
4,
5,
7,
9,
13,
17,
25,
33,
49,
65,
97,
129,
193,
257,
385,
513,
769,
1025,
1537,
2049,
3073,
4097,
6145,
8193,
12289,
16385,
24577,
0,
0
], P = [
16,
16,
16,
16,
17,
17,
18,
18,
19,
19,
20,
20,
21,
21,
22,
22,
23,
23,
24,
24,
25,
25,
26,
26,
27,
27,
28,
28,
29,
29,
64,
64
];
t.exports = function(e, t, r, n, i, s, a, o) {
var h, u, l, f, c, d, p, m, _, g = o.bits, b = 0, v = 0, y = 0, w = 0, k = 0, x = 0, S = 0, z = 0, C = 0, E = 0, A = null, I = 0, O = new D.Buf16(16), B = new D.Buf16(16), R = null, T = 0;
for (b = 0; b <= 15; b++) O[b] = 0;
for (v = 0; v < n; v++) O[t[r + v]]++;
for (k = g, w = 15; 1 <= w && 0 === O[w]; w--);
if (w < k && (k = w), 0 === w) return i[s++] = 20971520, i[s++] = 20971520, o.bits = 1, 0;
for (y = 1; y < w && 0 === O[y]; y++);
for (k < y && (k = y), b = z = 1; b <= 15; b++) if (z <<= 1, (z -= O[b]) < 0) return -1;
if (0 < z && (0 === e || 1 !== w)) return -1;
for (B[1] = 0, b = 1; b < 15; b++) B[b + 1] = B[b] + O[b];
for (v = 0; v < n; v++) 0 !== t[r + v] && (a[B[t[r + v]]++] = v);
if (d = 0 === e ? (A = R = a, 19) : 1 === e ? (A = F, I -= 257, R = N, T -= 257, 256) : (A = U, R = P, -1), b = y, c = s, S = v = E = 0, l = -1, f = (C = 1 << (x = k)) - 1, 1 === e && 852 < C || 2 === e && 592 < C) return 1;
for (;;) {
for (p = b - S, _ = a[v] < d ? (m = 0, a[v]) : a[v] > d ? (m = R[T + a[v]], A[I + a[v]]) : (m = 96, 0), h = 1 << b - S, y = u = 1 << x; i[c + (E >> S) + (u -= h)] = p << 24 | m << 16 | _ | 0, 0 !== u;);
for (h = 1 << b - 1; E & h;) h >>= 1;
if (0 !== h ? (E &= h - 1, E += h) : E = 0, v++, 0 == --O[b]) {
if (b === w) break;
b = t[r + a[v]];
}
if (k < b && (E & f) !== l) {
for (0 === S && (S = k), c += y, z = 1 << (x = b - S); x + S < w && !((z -= O[x + S]) <= 0);) x++, z <<= 1;
if (C += 1 << x, 1 === e && 852 < C || 2 === e && 592 < C) return 1;
i[l = E & f] = k << 24 | x << 16 | c - s | 0;
}
}
return 0 !== E && (i[c + E] = b - S << 24 | 4194304), o.bits = k, 0;
};
}, { "../utils/common": 41 }],
51: [function(e, t, r) {
"use strict";
t.exports = {
2: "need dictionary",
1: "stream end",
0: "",
"-1": "file error",
"-2": "stream error",
"-3": "data error",
"-4": "insufficient memory",
"-5": "buffer error",
"-6": "incompatible version"
};
}, {}],
52: [function(e, t, r) {
"use strict";
var i = e("../utils/common"), o = 0, h = 1;
function n(e) {
for (var t = e.length; 0 <= --t;) e[t] = 0;
}
var s = 0, a = 29, u = 256, l = u + 1 + a, f = 30, c = 19, _ = 2 * l + 1, g = 15, d = 16, p = 7, m = 256, b = 16, v = 17, y = 18, w = [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
2,
2,
2,
2,
3,
3,
3,
3,
4,
4,
4,
4,
5,
5,
5,
5,
0
], k = [
0,
0,
0,
0,
1,
1,
2,
2,
3,
3,
4,
4,
5,
5,
6,
6,
7,
7,
8,
8,
9,
9,
10,
10,
11,
11,
12,
12,
13,
13
], x = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2,
3,
7
], S = [
16,
17,
18,
0,
8,
7,
9,
6,
10,
5,
11,
4,
12,
3,
13,
2,
14,
1,
15
], z = new Array(2 * (l + 2));
n(z);
var C = new Array(2 * f);
n(C);
var E = new Array(512);
n(E);
var A = new Array(256);
n(A);
var I = new Array(a);
n(I);
var O, B, R, T = new Array(f);
function D(e, t, r, n, i) {
this.static_tree = e, this.extra_bits = t, this.extra_base = r, this.elems = n, this.max_length = i, this.has_stree = e && e.length;
}
function F(e, t) {
this.dyn_tree = e, this.max_code = 0, this.stat_desc = t;
}
function N(e) {
return e < 256 ? E[e] : E[256 + (e >>> 7)];
}
function U(e, t) {
e.pending_buf[e.pending++] = 255 & t, e.pending_buf[e.pending++] = t >>> 8 & 255;
}
function P(e, t, r) {
e.bi_valid > d - r ? (e.bi_buf |= t << e.bi_valid & 65535, U(e, e.bi_buf), e.bi_buf = t >> d - e.bi_valid, e.bi_valid += r - d) : (e.bi_buf |= t << e.bi_valid & 65535, e.bi_valid += r);
}
function L(e, t, r) {
P(e, r[2 * t], r[2 * t + 1]);
}
function j(e, t) {
for (var r = 0; r |= 1 & e, e >>>= 1, r <<= 1, 0 < --t;);
return r >>> 1;
}
function Z(e, t, r) {
var n, i, s = new Array(g + 1), a = 0;
for (n = 1; n <= g; n++) s[n] = a = a + r[n - 1] << 1;
for (i = 0; i <= t; i++) {
var o = e[2 * i + 1];
0 !== o && (e[2 * i] = j(s[o]++, o));
}
}
function W(e) {
var t;
for (t = 0; t < l; t++) e.dyn_ltree[2 * t] = 0;
for (t = 0; t < f; t++) e.dyn_dtree[2 * t] = 0;
for (t = 0; t < c; t++) e.bl_tree[2 * t] = 0;
e.dyn_ltree[2 * m] = 1, e.opt_len = e.static_len = 0, e.last_lit = e.matches = 0;
}
function M(e) {
8 < e.bi_valid ? U(e, e.bi_buf) : 0 < e.bi_valid && (e.pending_buf[e.pending++] = e.bi_buf), e.bi_buf = 0, e.bi_valid = 0;
}
function H(e, t, r, n) {
var i = 2 * t, s = 2 * r;
return e[i] < e[s] || e[i] === e[s] && n[t] <= n[r];
}
function G(e, t, r) {
for (var n = e.heap[r], i = r << 1; i <= e.heap_len && (i < e.heap_len && H(t, e.heap[i + 1], e.heap[i], e.depth) && i++, !H(t, n, e.heap[i], e.depth));) e.heap[r] = e.heap[i], r = i, i <<= 1;
e.heap[r] = n;
}
function K(e, t, r) {
var n, i, s, a, o = 0;
if (0 !== e.last_lit) for (; n = e.pending_buf[e.d_buf + 2 * o] << 8 | e.pending_buf[e.d_buf + 2 * o + 1], i = e.pending_buf[e.l_buf + o], o++, 0 === n ? L(e, i, t) : (L(e, (s = A[i]) + u + 1, t), 0 !== (a = w[s]) && P(e, i -= I[s], a), L(e, s = N(--n), r), 0 !== (a = k[s]) && P(e, n -= T[s], a)), o < e.last_lit;);
L(e, m, t);
}
function Y(e, t) {
var r, n, i, s = t.dyn_tree, a = t.stat_desc.static_tree, o = t.stat_desc.has_stree, h = t.stat_desc.elems, u = -1;
for (e.heap_len = 0, e.heap_max = _, r = 0; r < h; r++) 0 !== s[2 * r] ? (e.heap[++e.heap_len] = u = r, e.depth[r] = 0) : s[2 * r + 1] = 0;
for (; e.heap_len < 2;) s[2 * (i = e.heap[++e.heap_len] = u < 2 ? ++u : 0)] = 1, e.depth[i] = 0, e.opt_len--, o && (e.static_len -= a[2 * i + 1]);
for (t.max_code = u, r = e.heap_len >> 1; 1 <= r; r--) G(e, s, r);
for (i = h; r = e.heap[1], e.heap[1] = e.heap[e.heap_len--], G(e, s, 1), n = e.heap[1], e.heap[--e.heap_max] = r, e.heap[--e.heap_max] = n, s[2 * i] = s[2 * r] + s[2 * n], e.depth[i] = (e.depth[r] >= e.depth[n] ? e.depth[r] : e.depth[n]) + 1, s[2 * r + 1] = s[2 * n + 1] = i, e.heap[1] = i++, G(e, s, 1), 2 <= e.heap_len;);
e.heap[--e.heap_max] = e.heap[1], function(e, t) {
var r, n, i, s, a, o, h = t.dyn_tree, u = t.max_code, l = t.stat_desc.static_tree, f = t.stat_desc.has_stree, c = t.stat_desc.extra_bits, d = t.stat_desc.extra_base, p = t.stat_desc.max_length, m = 0;
for (s = 0; s <= g; s++) e.bl_count[s] = 0;
for (h[2 * e.heap[e.heap_max] + 1] = 0, r = e.heap_max + 1; r < _; r++) p < (s = h[2 * h[2 * (n = e.heap[r]) + 1] + 1] + 1) && (s = p, m++), h[2 * n + 1] = s, u < n || (e.bl_count[s]++, a = 0, d <= n && (a = c[n - d]), o = h[2 * n], e.opt_len += o * (s + a), f && (e.static_len += o * (l[2 * n + 1] + a)));
if (0 !== m) {
do {
for (s = p - 1; 0 === e.bl_count[s];) s--;
e.bl_count[s]--, e.bl_count[s + 1] += 2, e.bl_count[p]--, m -= 2;
} while (0 < m);
for (s = p; 0 !== s; s--) for (n = e.bl_count[s]; 0 !== n;) u < (i = e.heap[--r]) || (h[2 * i + 1] !== s && (e.opt_len += (s - h[2 * i + 1]) * h[2 * i], h[2 * i + 1] = s), n--);
}
}(e, t), Z(s, u, e.bl_count);
}
function X(e, t, r) {
var n, i, s = -1, a = t[1], o = 0, h = 7, u = 4;
for (0 === a && (h = 138, u = 3), t[2 * (r + 1) + 1] = 65535, n = 0; n <= r; n++) i = a, a = t[2 * (n + 1) + 1], ++o < h && i === a || (o < u ? e.bl_tree[2 * i] += o : 0 !== i ? (i !== s && e.bl_tree[2 * i]++, e.bl_tree[2 * b]++) : o <= 10 ? e.bl_tree[2 * v]++ : e.bl_tree[2 * y]++, s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4));
}
function V(e, t, r) {
var n, i, s = -1, a = t[1], o = 0, h = 7, u = 4;
for (0 === a && (h = 138, u = 3), n = 0; n <= r; n++) if (i = a, a = t[2 * (n + 1) + 1], !(++o < h && i === a)) {
if (o < u) for (; L(e, i, e.bl_tree), 0 != --o;);
else 0 !== i ? (i !== s && (L(e, i, e.bl_tree), o--), L(e, b, e.bl_tree), P(e, o - 3, 2)) : o <= 10 ? (L(e, v, e.bl_tree), P(e, o - 3, 3)) : (L(e, y, e.bl_tree), P(e, o - 11, 7));
s = i, u = (o = 0) === a ? (h = 138, 3) : i === a ? (h = 6, 3) : (h = 7, 4);
}
}
n(T);
var q = !1;
function J(e, t, r, n) {
P(e, (s << 1) + (n ? 1 : 0), 3), function(e, t, r, n) {
M(e), n && (U(e, r), U(e, ~r)), i.arraySet(e.pending_buf, e.window, t, r, e.pending), e.pending += r;
}(e, t, r, !0);
}
r._tr_init = function(e) {
q || (function() {
var e, t, r, n, i, s = new Array(g + 1);
for (n = r = 0; n < a - 1; n++) for (I[n] = r, e = 0; e < 1 << w[n]; e++) A[r++] = n;
for (A[r - 1] = n, n = i = 0; n < 16; n++) for (T[n] = i, e = 0; e < 1 << k[n]; e++) E[i++] = n;
for (i >>= 7; n < f; n++) for (T[n] = i << 7, e = 0; e < 1 << k[n] - 7; e++) E[256 + i++] = n;
for (t = 0; t <= g; t++) s[t] = 0;
for (e = 0; e <= 143;) z[2 * e + 1] = 8, e++, s[8]++;
for (; e <= 255;) z[2 * e + 1] = 9, e++, s[9]++;
for (; e <= 279;) z[2 * e + 1] = 7, e++, s[7]++;
for (; e <= 287;) z[2 * e + 1] = 8, e++, s[8]++;
for (Z(z, l + 1, s), e = 0; e < f; e++) C[2 * e + 1] = 5, C[2 * e] = j(e, 5);
O = new D(z, w, u + 1, l, g), B = new D(C, k, 0, f, g), R = new D(new Array(0), x, 0, c, p);
}(), q = !0), e.l_desc = new F(e.dyn_ltree, O), e.d_desc = new F(e.dyn_dtree, B), e.bl_desc = new F(e.bl_tree, R), e.bi_buf = 0, e.bi_valid = 0, W(e);
}, r._tr_stored_block = J, r._tr_flush_block = function(e, t, r, n) {
var i, s, a = 0;
0 < e.level ? (2 === e.strm.data_type && (e.strm.data_type = function(e) {
var t, r = 4093624447;
for (t = 0; t <= 31; t++, r >>>= 1) if (1 & r && 0 !== e.dyn_ltree[2 * t]) return o;
if (0 !== e.dyn_ltree[18] || 0 !== e.dyn_ltree[20] || 0 !== e.dyn_ltree[26]) return h;
for (t = 32; t < u; t++) if (0 !== e.dyn_ltree[2 * t]) return h;
return o;
}(e)), Y(e, e.l_desc), Y(e, e.d_desc), a = function(e) {
var t;
for (X(e, e.dyn_ltree, e.l_desc.max_code), X(e, e.dyn_dtree, e.d_desc.max_code), Y(e, e.bl_desc), t = c - 1; 3 <= t && 0 === e.bl_tree[2 * S[t] + 1]; t--);
return e.opt_len += 3 * (t + 1) + 5 + 5 + 4, t;
}(e), i = e.opt_len + 3 + 7 >>> 3, (s = e.static_len + 3 + 7 >>> 3) <= i && (i = s)) : i = s = r + 5, r + 4 <= i && -1 !== t ? J(e, t, r, n) : 4 === e.strategy || s === i ? (P(e, 2 + (n ? 1 : 0), 3), K(e, z, C)) : (P(e, 4 + (n ? 1 : 0), 3), function(e, t, r, n) {
var i;
for (P(e, t - 257, 5), P(e, r - 1, 5), P(e, n - 4, 4), i = 0; i < n; i++) P(e, e.bl_tree[2 * S[i] + 1], 3);
V(e, e.dyn_ltree, t - 1), V(e, e.dyn_dtree, r - 1);
}(e, e.l_desc.max_code + 1, e.d_desc.max_code + 1, a + 1), K(e, e.dyn_ltree, e.dyn_dtree)), W(e), n && M(e);
}, r._tr_tally = function(e, t, r) {
return e.pending_buf[e.d_buf + 2 * e.last_lit] = t >>> 8 & 255, e.pending_buf[e.d_buf + 2 * e.last_lit + 1] = 255 & t, e.pending_buf[e.l_buf + e.last_lit] = 255 & r, e.last_lit++, 0 === t ? e.dyn_ltree[2 * r]++ : (e.matches++, t--, e.dyn_ltree[2 * (A[r] + u + 1)]++, e.dyn_dtree[2 * N(t)]++), e.last_lit === e.lit_bufsize - 1;
}, r._tr_align = function(e) {
P(e, 2, 3), L(e, m, z), function(e) {
16 === e.bi_valid ? (U(e, e.bi_buf), e.bi_buf = 0, e.bi_valid = 0) : 8 <= e.bi_valid && (e.pending_buf[e.pending++] = 255 & e.bi_buf, e.bi_buf >>= 8, e.bi_valid -= 8);
}(e);
};
}, { "../utils/common": 41 }],
53: [function(e, t, r) {
"use strict";
t.exports = function() {
this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
};
}, {}],
54: [function(e, t, r) {
(function(e) {
(function(r, n) {
"use strict";
if (!r.setImmediate) {
var i, s, t, a, o = 1, h = {}, u = !1, l = r.document, e = Object.getPrototypeOf && Object.getPrototypeOf(r);
e = e && e.setTimeout ? e : r, i = "[object process]" === {}.toString.call(r.process) ? function(e) {
process.nextTick(function() {
c(e);
});
} : function() {
if (r.postMessage && !r.importScripts) {
var e = !0, t = r.onmessage;
return r.onmessage = function() {
e = !1;
}, r.postMessage("", "*"), r.onmessage = t, e;
}
}() ? (a = "setImmediate$" + Math.random() + "$", r.addEventListener ? r.addEventListener("message", d, !1) : r.attachEvent("onmessage", d), function(e) {
r.postMessage(a + e, "*");
}) : r.MessageChannel ? ((t = new MessageChannel()).port1.onmessage = function(e) {
c(e.data);
}, function(e) {
t.port2.postMessage(e);
}) : l && "onreadystatechange" in l.createElement("script") ? (s = l.documentElement, function(e) {
var t = l.createElement("script");
t.onreadystatechange = function() {
c(e), t.onreadystatechange = null, s.removeChild(t), t = null;
}, s.appendChild(t);
}) : function(e) {
setTimeout(c, 0, e);
}, e.setImmediate = function(e) {
"function" != typeof e && (e = new Function("" + e));
for (var t = new Array(arguments.length - 1), r = 0; r < t.length; r++) t[r] = arguments[r + 1];
return h[o] = {
callback: e,
args: t
}, i(o), o++;
}, e.clearImmediate = f;
}
function f(e) {
delete h[e];
}
function c(e) {
if (u) setTimeout(c, 0, e);
else {
var t = h[e];
if (t) {
u = !0;
try {
(function(e) {
var t = e.callback, r = e.args;
switch (r.length) {
case 0:
t();
break;
case 1:
t(r[0]);
break;
case 2:
t(r[0], r[1]);
break;
case 3:
t(r[0], r[1], r[2]);
break;
default: t.apply(n, r);
}
})(t);
} finally {
f(e), u = !1;
}
}
}
}
function d(e) {
e.source === r && "string" == typeof e.data && 0 === e.data.indexOf(a) && c(+e.data.slice(a.length));
}
})("undefined" == typeof self ? void 0 === e ? this : e : self);
}).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}]
}, {}, [10])(10);
});
}));
var require_FileSaver_min = __commonJSMin(((exports, module) => {
(function(a, b) {
if ("function" == typeof define && define.amd) define([], b);
else if ("undefined" != typeof exports) b();
else b(), a.FileSaver = { exports: {} }.exports;
})(exports, function() {
"use strict";
function b(a, b) {
return "undefined" == typeof b ? b = { autoBom: !1 } : "object" != typeof b && (console.warn("Deprecated: Expected third argument to be a object"), b = { autoBom: !b }), b.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type) ? new Blob(["", a], { type: a.type }) : a;
}
function c(a, b, c) {
var d = new XMLHttpRequest();
d.open("GET", a), d.responseType = "blob", d.onload = function() {
g(d.response, b, c);
}, d.onerror = function() {
console.error("could not download file");
}, d.send();
}
function d(a) {
var b = new XMLHttpRequest();
b.open("HEAD", a, !1);
try {
b.send();
} catch (a) {}
return 200 <= b.status && 299 >= b.status;
}
function e(a) {
try {
a.dispatchEvent(new MouseEvent("click"));
} catch (c) {
var b = document.createEvent("MouseEvents");
b.initMouseEvent("click", !0, !0, window, 0, 0, 0, 80, 20, !1, !1, !1, !1, 0, null), a.dispatchEvent(b);
}
}
var f = "object" == typeof window && window.window === window ? window : "object" == typeof self && self.self === self ? self : "object" == typeof global && global.global === global ? global : void 0, a = f.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent), g = f.saveAs || ("object" != typeof window || window !== f ? function() {} : "download" in HTMLAnchorElement.prototype && !a ? function(b, g, h) {
var i = f.URL || f.webkitURL, j = document.createElement("a");
g = g || b.name || "download", j.download = g, j.rel = "noopener", "string" == typeof b ? (j.href = b, j.origin === location.origin ? e(j) : d(j.href) ? c(b, g, h) : e(j, j.target = "_blank")) : (j.href = i.createObjectURL(b), setTimeout(function() {
i.revokeObjectURL(j.href);
}, 4e4), setTimeout(function() {
e(j);
}, 0));
} : "msSaveOrOpenBlob" in navigator ? function(f, g, h) {
if (g = g || f.name || "download", "string" != typeof f) navigator.msSaveOrOpenBlob(b(f, h), g);
else if (d(f)) c(f, g, h);
else {
var i = document.createElement("a");
i.href = f, i.target = "_blank", setTimeout(function() {
e(i);
});
}
} : function(b, d, e, g) {
if (g = g || open("", "_blank"), g && (g.document.title = g.document.body.innerText = "downloading..."), "string" == typeof b) return c(b, d, e);
var h = "application/octet-stream" === b.type, i = /constructor/i.test(f.HTMLElement) || f.safari, j = /CriOS\/[\d]+/.test(navigator.userAgent);
if ((j || h && i || a) && "undefined" != typeof FileReader) {
var k = new FileReader();
k.onloadend = function() {
var a = k.result;
a = j ? a : a.replace(/^data:[^;]*;/, "data:attachment/file;"), g ? g.location.href = a : location = a, g = null;
}, k.readAsDataURL(b);
} else {
var l = f.URL || f.webkitURL, m = l.createObjectURL(b);
g ? g.location = m : location.href = m, g = null, setTimeout(function() {
l.revokeObjectURL(m);
}, 4e4);
}
});
f.saveAs = g.saveAs = g, "undefined" != typeof module && (module.exports = g);
});
}));
var import_localforage = __toESM(require_localforage(), 1);
var import_jszip_min = __toESM(require_jszip_min(), 1);
var import_FileSaver_min = require_FileSaver_min();
var localStorage$1 = import_localforage.default.createInstance({ name: "localforage" });
var snapshotStorage = import_localforage.default.createInstance({ name: "snapshot" });
var screenshotStorage = import_localforage.default.createInstance({ name: "screenshot" });
var hanashiroStorage = import_localforage.default.createInstance({ name: "Hanashiro" });
var simplyActivityIds = async (snapshotId) => {
const snapshotInfo = await snapshotStorage.getItem(snapshotId);
const activityId = snapshotInfo?.activityId;
if (activityId) {
const appId = snapshotInfo.appId;
if (activityId.startsWith(appId) && activityId[appId.length] === ".") return activityId.replace(appId, "");
else return false;
} else return false;
};
var editNode = async (snapshotId, nodeId, options) => {
try {
const snapshotInfo = await snapshotStorage.getItem(snapshotId);
const nodes = snapshotInfo.nodes;
const nodeAttr = nodes[nodeId].attr;
options.forEach((option) => nodeAttr[option.target] = option.value);
nodes[nodeId].attr = nodeAttr;
snapshotInfo.nodes = nodes;
await snapshotStorage.setItem(snapshotId, snapshotInfo);
return true;
} catch {
return false;
}
};
var getScreenInfo = async (snapshotId) => {
const snapshotInfo = await snapshotStorage.getItem(snapshotId);
return {
width: snapshotInfo.screenWidth,
height: snapshotInfo.screenHeight
};
};
var getScreenshot = async (snapshotId) => {
return await screenshotStorage.getItem(snapshotId);
};
var replaceScreenshot = async (snapshotId, image) => {
await screenshotStorage.setItem(snapshotId, image);
};
var getNodeAttr = async (snapshotId, nodeId, target) => {
return (await snapshotStorage.getItem(snapshotId)).nodes[nodeId].attr[target];
};
var downloadSnapshot = async (snapshotId) => {
const snapshotInfo = await snapshotStorage.getItem(snapshotId);
const screenshot = await screenshotStorage.getItem(snapshotId);
const jszip = new import_jszip_min.default();
jszip.file(`snapshot-${snapshotId}.json`, JSON.stringify(snapshotInfo, void 0, 2));
jszip.file(`screenshot-${snapshotId}.png`, screenshot);
jszip.generateAsync({ type: "blob" }).then((snapshotFile) => {
(0, import_FileSaver_min.saveAs)(snapshotFile, `snapshot-${snapshotId}.zip`);
});
};
var setHanashiroSettings = async (item, value) => {
await hanashiroStorage.setItem(item, value);
};
var getHanashiroSettings = async (item) => {
return await hanashiroStorage.getItem(item);
};
var getInspectSettings = async () => {
return await localStorage$1.getItem("settings");
};
var setInspectSettings = async (newSettings) => {
await localStorage$1.setItem("settings", newSettings);
};
Object.defineProperty(window, "Hanashiro", {
value: {},
writable: true
});
var userRulesKeySort = await(getHanashiroSettings("rulesKeySort"));
var rulesKeySort = [
"key",
"preKeys",
"fastQuery",
"matchTime",
"actionMaximum",
"resetMatch",
"priorityTime",
"matchRoot",
"action",
"activityIds",
"position",
"matches",
"exampleUrls",
"snapshotUrls"
];
if (!await(getHanashiroSettings("selectors"))) await(setHanashiroSettings("selectors", []));
if (!await(getHanashiroSettings("rulesKeySort")) || userRulesKeySort.length == 0) await(setHanashiroSettings("rulesKeySort", rulesKeySort));
if (userRulesKeySort.length != rulesKeySort.length) confirm({
headline: "同步最新rulesKey排序",
description: "检测你的rulesKey排序有多余或缺失字段,可能无法使用最新的功能。是否同步?注意:这会丢失你现有的排序设置。",
closeOnEsc: true,
closeOnOverlayClick: true,
confirmText: "同步",
cancelText: "取消",
onConfirm: async () => await setHanashiroSettings("rulesKeySort", rulesKeySort)
});
else for (const rulesKey of userRulesKeySort) {
if (!rulesKeySort.includes(rulesKey)) confirm({
headline: "同步最新rulesKey排序",
description: "检测你的rulesKey排序有多余或缺失字段,可能无法使用最新的功能。是否同步?注意:这会丢失你现有的排序设置。",
closeOnEsc: true,
closeOnOverlayClick: true,
confirmText: "同步",
cancelText: "取消",
onConfirm: async () => await setHanashiroSettings("rulesKeySort", rulesKeySort)
});
break;
}
if (!await(getInspectSettings())) await(setInspectSettings({
autoUploadImport: false,
ignoreUploadWarn: false,
ignoreWasmWarn: false,
maxShowNodeSize: 2e3
}));
if (!await(getHanashiroSettings("count"))) await(setHanashiroSettings("count", {
rejectRules: 0,
loaded: 0
}));
var count = await(getHanashiroSettings("count"));
count.loaded++;
await(setHanashiroSettings("count", count));
if (await(getHanashiroSettings("hideLoadSnackbar")) === false) snackbar({
message: "世界第一公主殿下已经降下魔法~",
autoCloseDelay: 2e3,
placement: "top"
});
var send = (eventName) => {
const event = new Event(eventName);
window.dispatchEvent(event);
};
var receive = (eventName, callback, once) => {
window.addEventListener(eventName, callback, { once });
};
var createBarIcon = (icon, tooltip, onclick) => {
const iconTooltip = document.createElement("mdui-tooltip");
iconTooltip.content = tooltip;
const iconElement = document.createElement("mdui-button-icon");
iconElement.icon = icon;
iconElement.style.height = "36px";
iconElement.style.width = "36px";
iconElement.onclick = onclick;
iconTooltip.append(iconElement);
return iconTooltip;
};
var observeElement_default = (selector, callback, continuous = false) => {
let elementExists = false;
try {
const timer = setInterval(() => {
const element = document.querySelector(selector);
if (element && !elementExists) {
elementExists = true;
callback();
} else if (!element) elementExists = false;
if (element && !continuous) clearInterval(timer);
}, 100);
} catch (e) {
console.log(e);
}
};
var insertBarIcon_default = (icon) => {
document.querySelector("#iconBar").append(icon);
};
Object.defineProperty(window, "HatsuneMiku", {
value: {
event: {
send,
receive
},
utils: {
icon: {
createBarIcon,
insertBarIcon: insertBarIcon_default
},
common: { observeElement: observeElement_default },
storage: {
getHanashiroSettings,
setHanashiroSettings,
getInspectSettings,
setInspectSettings
},
ui: {
snackbar,
confirm,
dialog
}
}
},
writable: true
});
var attrList = [
"id",
"vid",
"text",
"text.length",
"desc",
"desc.length",
"clickable",
"focusable",
"checkable",
"checked",
"editable",
"longClickable",
"visibleToUser",
"left",
"top",
"right",
"bottom",
"width",
"height",
"childCount",
"index"
];
var copyProxy = new Proxy(navigator.clipboard.writeText, { apply: async (target, thisArg, args) => {
const data = args[0];
if (data.startsWith("{") && data.endsWith("}")) {
window.Hanashiro.originRule = args[0];
const result = await new Promise((resolve, reject) => {
try {
receive("modifyEnd", async () => {
const count = await getHanashiroSettings("count");
count.rejectRules++;
await setHanashiroSettings("count", count);
resolve(window.Hanashiro.returnResult);
}, true);
send("copyEvent");
} catch {
reject();
}
});
if (result) {
snackbar({
message: "注入修改成功",
placement: "top"
});
return await Reflect.apply(target, thisArg, [result]);
}
} else if (data.startsWith("name=")) if (await getHanashiroSettings("simplyName") == true) {
const splitedName = data.split("\"")[1].split(".");
const name = splitedName[splitedName.length - 1];
return await Reflect.apply(target, thisArg, [name]);
} else return await Reflect.apply(target, thisArg, [data]);
else if (attrList.filter((attr) => data.startsWith(`${attr}=`)).length != 0) return await Reflect.apply(target, thisArg, [`[${data}]`]);
else if (data.startsWith(window.origin)) {
const selectors = await getHanashiroSettings("selectors");
if (selectors.length != 0) {
const copiedUrl = new URL(data);
if (copiedUrl.searchParams.has("gkd")) {
const selectorBase64 = copiedUrl.searchParams.get("gkd");
prompt({
headline: "备注",
description: "给该选择器的备注,留空就用默认的了哦~",
confirmText: "就决定是你了!",
cancelText: "这个不要保存!",
closeOnEsc: true,
closeOnOverlayClick: true,
onConfirm: async (value) => {
selectors.push({
name: value ? value : selectorBase64,
base64: selectorBase64,
order: 1
});
selectors.sort((a, b) => {
if (a.order > b.order) return -1;
else if (a.order == b.order) return 0;
else return 1;
});
await setHanashiroSettings("selectors", selectors);
}
}).catch();
}
}
return await Reflect.apply(target, thisArg, [data]);
} else return await Reflect.apply(target, thisArg, [data]);
} });
navigator.clipboard.writeText = copyProxy;
var getSnapshotId_default = () => {
return location.pathname.split("/")[2];
};
var getCurrentNodeId_default = () => {
const currentSelectedNode = document.querySelector(".n-tree-node-wrapper .n-tree-node--selected");
if (!currentSelectedNode) return 0;
else return Number(currentSelectedNode.getAttribute("data-node-id"));
};
var calcLength = (reg, str) => {
const length = [];
Array.from(str.matchAll(reg)).forEach(([text]) => length.push(text.length));
return length;
};
var replaceNodeInfo = async (reg = /./g) => {
const snapshotId = getSnapshotId_default();
const nodeId = getCurrentNodeId_default() == -1 ? 0 : getCurrentNodeId_default();
const text = await getNodeAttr(snapshotId, nodeId, "text");
const desc = await getNodeAttr(snapshotId, nodeId, "desc");
let newText = text, newDesc = desc;
if (newText) {
const lengths = calcLength(reg, newText);
for (let i = 0; i < lengths.length; i++) newText = newText.replace(reg, "*".repeat(lengths[i]));
}
if (newDesc) {
const lengths = calcLength(reg, newDesc);
for (let i = 0; i < lengths.length; i++) newText = newDesc.replace(reg, "*".repeat(lengths[i]));
}
editNode(snapshotId, nodeId, [{
target: "text",
value: newText
}, {
target: "desc",
value: newDesc
}]).then((result) => {
if (result) snackbar({
message: "修改成功!你可以选择上传获取导入链接或下载快照分享",
placement: "top"
});
});
};
var replaceNodeInfo_default = () => {
dialog({
headline: "确认要对该节点打码吗?",
description: "进行打码操作会对导入的快照造成无法恢复的修改,如需恢复,需要删除当前快照重新导入。建议你先下载备份!",
actions: [
{ text: "我再想想" },
{
text: "下载快照文件并打码",
onClick: () => {
return new Promise((resolve, reject) => {
snackbar({
message: "开始下载中……下载开始后会自动关闭弹窗",
placement: "top"
});
downloadSnapshot(getSnapshotId_default()).then(() => {
resolve();
prompt({
headline: "请输入一个正则表达式",
description: "已默认使用 g 修饰符,暂不支持其他修饰符!留空则全部打码。",
confirmText: "确认",
cancelText: "取消",
onConfirm: (value) => replaceNodeInfo(!value ? void 0 : new RegExp(value, "g")),
closeOnEsc: true,
closeOnOverlayClick: true
});
}).catch(() => {
snackbar({
message: "下载失败",
placement: "top"
});
reject();
});
});
}
},
{
text: "直接打码",
onClick: () => {
prompt({
headline: "请输入一个正则表达式",
description: "已默认使用 g 修饰符,暂不支持其他修饰符!留空则全部打码。",
confirmText: "确认",
cancelText: "取消",
onConfirm: (value) => replaceNodeInfo(!value ? void 0 : new RegExp(value, "g")),
closeOnEsc: true,
closeOnOverlayClick: true
});
}
}
],
closeOnEsc: true,
closeOnOverlayClick: true
});
};
observeElement_default(".DraggableCard > * > .n-input-group", () => {
if (!document.querySelector("#iconBar")) {
const inputGroup = document.querySelector(".DraggableCard > * > .n-input-group");
const iconBar = document.createElement("div");
iconBar.id = "iconBar";
const UseSelectorIcon = createBarIcon("search", "搜索选择器", () => {
send("openUseSelector");
});
const AddSelectorIcon = createBarIcon("add", "添加选择器", () => {
send("openAddSelector");
});
const ManageSelectorsIcon = createBarIcon("edit", "管理选择器", () => {
send("openManageSelectors");
});
const ChangeScreenshotIcon = createBarIcon("photo", "更换截图", () => {
send("openChangeScreenshot");
});
const SettingsIcon = createBarIcon("settings", "脚本设置", () => {
send("openSettings");
});
const CountIcon = createBarIcon("bar_chart", "统计", () => {
send("openCount");
});
const HelpIcon = createBarIcon("help", "帮助", () => {
send("openHelp");
});
const SponsorIcon = createBarIcon("coffee", "捐赠", () => {
window.open("https://afdian.com/a/Adpro");
});
iconBar.append(UseSelectorIcon, AddSelectorIcon, ManageSelectorsIcon, ChangeScreenshotIcon, SettingsIcon, CountIcon, HelpIcon, SponsorIcon);
inputGroup.insertAdjacentElement("beforebegin", iconBar);
}
}, true);
observeElement_default("#iconBar", () => {
const editNodeIcon = document.createElement("mdui-fab");
editNodeIcon.icon = "edit";
editNodeIcon.variant = "secondary";
editNodeIcon.extended = true;
editNodeIcon.textContent = "替换当前节点信息";
editNodeIcon.style.right = "16px";
editNodeIcon.style.bottom = "120px";
editNodeIcon.setAttribute("fixed", "");
editNodeIcon.onclick = replaceNodeInfo_default;
const positionIcon = document.createElement("mdui-fab");
positionIcon.icon = "open_with";
positionIcon.variant = "secondary";
positionIcon.extended = true;
positionIcon.textContent = "生成坐标";
positionIcon.style.right = "16px";
positionIcon.style.bottom = "60px";
positionIcon.setAttribute("fixed", "");
positionIcon.onclick = () => send("openGeneratePosition");
document.body.append(editNodeIcon, positionIcon);
});
if (await(getHanashiroSettings("hideLoadSnackbar")) === false && document.location.href == `${document.location.origin}/`) try {
navigator.clipboard.readText().then((firstClipboardText) => {
if (firstClipboardText.endsWith(".zip")) {
const dataTransfer = new DataTransfer();
dataTransfer.setData("text", firstClipboardText);
document.body.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dataTransfer }));
}
});
} catch {
snackbar({
message: "未授予剪贴板权限!",
placement: "top"
});
}
var import_dist = __toESM(( __commonJSMin(((exports, module) => {
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global.JSON5 = factory();
})(exports, (function() {
"use strict";
function createCommonjsModule(fn, module$1) {
return module$1 = { exports: {} }, fn(module$1, module$1.exports), module$1.exports;
}
var _global = createCommonjsModule(function(module$2) {
var global = module$2.exports = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self : Function("return this")();
if (typeof __g == "number") __g = global;
});
var _core = createCommonjsModule(function(module$3) {
var core = module$3.exports = { version: "2.6.5" };
if (typeof __e == "number") __e = core;
});
_core.version;
var _isObject = function(it) {
return typeof it === "object" ? it !== null : typeof it === "function";
};
var _anObject = function(it) {
if (!_isObject(it)) throw TypeError(it + " is not an object!");
return it;
};
var _fails = function(exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
var _descriptors = !_fails(function() {
return Object.defineProperty({}, "a", { get: function() {
return 7;
} }).a != 7;
});
var document = _global.document;
var is = _isObject(document) && _isObject(document.createElement);
var _domCreate = function(it) {
return is ? document.createElement(it) : {};
};
var _ie8DomDefine = !_descriptors && !_fails(function() {
return Object.defineProperty(_domCreate("div"), "a", { get: function() {
return 7;
} }).a != 7;
});
var _toPrimitive = function(it, S) {
if (!_isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == "function" && !_isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == "function" && !_isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == "function" && !_isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
var dP = Object.defineProperty;
var _objectDp = { f: _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {
_anObject(O);
P = _toPrimitive(P, true);
_anObject(Attributes);
if (_ie8DomDefine) try {
return dP(O, P, Attributes);
} catch (e) {}
if ("get" in Attributes || "set" in Attributes) throw TypeError("Accessors not supported!");
if ("value" in Attributes) O[P] = Attributes.value;
return O;
} };
var _propertyDesc = function(bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value
};
};
var _hide = _descriptors ? function(object, key, value) {
return _objectDp.f(object, key, _propertyDesc(1, value));
} : function(object, key, value) {
object[key] = value;
return object;
};
var hasOwnProperty = {}.hasOwnProperty;
var _has = function(it, key) {
return hasOwnProperty.call(it, key);
};
var id = 0;
var px = Math.random();
var _uid = function(key) {
return "Symbol(".concat(key === void 0 ? "" : key, ")_", (++id + px).toString(36));
};
var _library = false;
var _functionToString = createCommonjsModule(function(module$4) {
var SHARED = "__core-js_shared__";
var store = _global[SHARED] || (_global[SHARED] = {});
(module$4.exports = function(key, value) {
return store[key] || (store[key] = value !== void 0 ? value : {});
})("versions", []).push({
version: _core.version,
mode: _library ? "pure" : "global",
copyright: "© 2019 Denis Pushkarev (zloirock.ru)"
});
})("native-function-to-string", Function.toString);
var _redefine = createCommonjsModule(function(module$5) {
var SRC = _uid("src");
var TO_STRING = "toString";
var TPL = ("" + _functionToString).split(TO_STRING);
_core.inspectSource = function(it) {
return _functionToString.call(it);
};
(module$5.exports = function(O, key, val, safe) {
var isFunction = typeof val == "function";
if (isFunction) _has(val, "name") || _hide(val, "name", key);
if (O[key] === val) return;
if (isFunction) _has(val, SRC) || _hide(val, SRC, O[key] ? "" + O[key] : TPL.join(String(key)));
if (O === _global) O[key] = val;
else if (!safe) {
delete O[key];
_hide(O, key, val);
} else if (O[key]) O[key] = val;
else _hide(O, key, val);
})(Function.prototype, TO_STRING, function toString() {
return typeof this == "function" && this[SRC] || _functionToString.call(this);
});
});
var _aFunction = function(it) {
if (typeof it != "function") throw TypeError(it + " is not a function!");
return it;
};
var _ctx = function(fn, that, length) {
_aFunction(fn);
if (that === void 0) return fn;
switch (length) {
case 1: return function(a) {
return fn.call(that, a);
};
case 2: return function(a, b) {
return fn.call(that, a, b);
};
case 3: return function(a, b, c) {
return fn.call(that, a, b, c);
};
}
return function() {
return fn.apply(that, arguments);
};
};
var PROTOTYPE = "prototype";
var $export = function(type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE];
var exports$1 = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});
var expProto = exports$1[PROTOTYPE] || (exports$1[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
own = !IS_FORCED && target && target[key] !== void 0;
out = (own ? target : source)[key];
exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == "function" ? _ctx(Function.call, out) : out;
if (target) _redefine(target, key, out, type & $export.U);
if (exports$1[key] != out) _hide(exports$1, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
_global.core = _core;
$export.F = 1;
$export.G = 2;
$export.S = 4;
$export.P = 8;
$export.B = 16;
$export.W = 32;
$export.U = 64;
$export.R = 128;
var _export = $export;
var ceil = Math.ceil;
var floor = Math.floor;
var _toInteger = function(it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
var _defined = function(it) {
if (it == void 0) throw TypeError("Can't call method on " + it);
return it;
};
var _stringAt = function(TO_STRING) {
return function(that, pos) {
var s = String(_defined(that));
var i = _toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? "" : void 0;
a = s.charCodeAt(i);
return a < 55296 || a > 56319 || i + 1 === l || (b = s.charCodeAt(i + 1)) < 56320 || b > 57343 ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 55296 << 10) + (b - 56320) + 65536;
};
};
var $at = _stringAt(false);
_export(_export.P, "String", { codePointAt: function codePointAt(pos) {
return $at(this, pos);
} });
_core.String.codePointAt;
var max = Math.max;
var min = Math.min;
var _toAbsoluteIndex = function(index, length) {
index = _toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
_export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), "String", { fromCodePoint: function fromCodePoint(x) {
var arguments$1 = arguments;
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments$1[i++];
if (_toAbsoluteIndex(code, 1114111) !== code) throw RangeError(code + " is not a valid code point");
res.push(code < 65536 ? fromCharCode(code) : fromCharCode(((code -= 65536) >> 10) + 55296, code % 1024 + 56320));
}
return res.join("");
} });
_core.String.fromCodePoint;
var unicode = {
Space_Separator: /[\u1680\u2000-\u200A\u202F\u205F\u3000]/,
ID_Start: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,
ID_Continue: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
};
var util = {
isSpaceSeparator: function isSpaceSeparator(c) {
return typeof c === "string" && unicode.Space_Separator.test(c);
},
isIdStartChar: function isIdStartChar(c) {
return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "$" || c === "_" || unicode.ID_Start.test(c));
},
isIdContinueChar: function isIdContinueChar(c) {
return typeof c === "string" && (c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c >= "0" && c <= "9" || c === "$" || c === "_" || c === "" || c === "" || unicode.ID_Continue.test(c));
},
isDigit: function isDigit(c) {
return typeof c === "string" && /[0-9]/.test(c);
},
isHexDigit: function isHexDigit(c) {
return typeof c === "string" && /[0-9A-Fa-f]/.test(c);
}
};
var source;
var parseState;
var stack;
var pos;
var line;
var column;
var token;
var key;
var root;
var parse = function parse(text, reviver) {
source = String(text);
parseState = "start";
stack = [];
pos = 0;
line = 1;
column = 0;
token = void 0;
key = void 0;
root = void 0;
do {
token = lex();
parseStates[parseState]();
} while (token.type !== "eof");
if (typeof reviver === "function") return internalize({ "": root }, "", reviver);
return root;
};
function internalize(holder, name, reviver) {
var value = holder[name];
if (value != null && typeof value === "object") if (Array.isArray(value)) for (var i = 0; i < value.length; i++) {
var key = String(i);
var replacement = internalize(value, key, reviver);
if (replacement === void 0) delete value[key];
else Object.defineProperty(value, key, {
value: replacement,
writable: true,
enumerable: true,
configurable: true
});
}
else for (var key$1 in value) {
var replacement$1 = internalize(value, key$1, reviver);
if (replacement$1 === void 0) delete value[key$1];
else Object.defineProperty(value, key$1, {
value: replacement$1,
writable: true,
enumerable: true,
configurable: true
});
}
return reviver.call(holder, name, value);
}
var lexState;
var buffer;
var doubleQuote;
var sign;
var c;
function lex() {
lexState = "default";
buffer = "";
doubleQuote = false;
sign = 1;
for (;;) {
c = peek();
var token = lexStates[lexState]();
if (token) return token;
}
}
function peek() {
if (source[pos]) return String.fromCodePoint(source.codePointAt(pos));
}
function read() {
var c = peek();
if (c === "\n") {
line++;
column = 0;
} else if (c) column += c.length;
else column++;
if (c) pos += c.length;
return c;
}
var lexStates = {
default: function default$1() {
switch (c) {
case " ":
case "\v":
case "\f":
case " ":
case "\xA0":
case "":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
read();
return;
case "/":
read();
lexState = "comment";
return;
case void 0:
read();
return newToken("eof");
}
if (util.isSpaceSeparator(c)) {
read();
return;
}
return lexStates[parseState]();
},
comment: function comment() {
switch (c) {
case "*":
read();
lexState = "multiLineComment";
return;
case "/":
read();
lexState = "singleLineComment";
return;
}
throw invalidChar(read());
},
multiLineComment: function multiLineComment() {
switch (c) {
case "*":
read();
lexState = "multiLineCommentAsterisk";
return;
case void 0: throw invalidChar(read());
}
read();
},
multiLineCommentAsterisk: function multiLineCommentAsterisk() {
switch (c) {
case "*":
read();
return;
case "/":
read();
lexState = "default";
return;
case void 0: throw invalidChar(read());
}
read();
lexState = "multiLineComment";
},
singleLineComment: function singleLineComment() {
switch (c) {
case "\n":
case "\r":
case "\u2028":
case "\u2029":
read();
lexState = "default";
return;
case void 0:
read();
return newToken("eof");
}
read();
},
value: function value() {
switch (c) {
case "{":
case "[": return newToken("punctuator", read());
case "n":
read();
literal("ull");
return newToken("null", null);
case "t":
read();
literal("rue");
return newToken("boolean", true);
case "f":
read();
literal("alse");
return newToken("boolean", false);
case "-":
case "+":
if (read() === "-") sign = -1;
lexState = "sign";
return;
case ".":
buffer = read();
lexState = "decimalPointLeading";
return;
case "0":
buffer = read();
lexState = "zero";
return;
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
buffer = read();
lexState = "decimalInteger";
return;
case "I":
read();
literal("nfinity");
return newToken("numeric", Infinity);
case "N":
read();
literal("aN");
return newToken("numeric", NaN);
case "\"":
case "'":
doubleQuote = read() === "\"";
buffer = "";
lexState = "string";
return;
}
throw invalidChar(read());
},
identifierNameStartEscape: function identifierNameStartEscape() {
if (c !== "u") throw invalidChar(read());
read();
var u = unicodeEscape();
switch (u) {
case "$":
case "_": break;
default:
if (!util.isIdStartChar(u)) throw invalidIdentifier();
break;
}
buffer += u;
lexState = "identifierName";
},
identifierName: function identifierName() {
switch (c) {
case "$":
case "_":
case "":
case "":
buffer += read();
return;
case "\\":
read();
lexState = "identifierNameEscape";
return;
}
if (util.isIdContinueChar(c)) {
buffer += read();
return;
}
return newToken("identifier", buffer);
},
identifierNameEscape: function identifierNameEscape() {
if (c !== "u") throw invalidChar(read());
read();
var u = unicodeEscape();
switch (u) {
case "$":
case "_":
case "":
case "": break;
default:
if (!util.isIdContinueChar(u)) throw invalidIdentifier();
break;
}
buffer += u;
lexState = "identifierName";
},
sign: function sign$1() {
switch (c) {
case ".":
buffer = read();
lexState = "decimalPointLeading";
return;
case "0":
buffer = read();
lexState = "zero";
return;
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
buffer = read();
lexState = "decimalInteger";
return;
case "I":
read();
literal("nfinity");
return newToken("numeric", sign * Infinity);
case "N":
read();
literal("aN");
return newToken("numeric", NaN);
}
throw invalidChar(read());
},
zero: function zero() {
switch (c) {
case ".":
buffer += read();
lexState = "decimalPoint";
return;
case "e":
case "E":
buffer += read();
lexState = "decimalExponent";
return;
case "x":
case "X":
buffer += read();
lexState = "hexadecimal";
return;
}
return newToken("numeric", sign * 0);
},
decimalInteger: function decimalInteger() {
switch (c) {
case ".":
buffer += read();
lexState = "decimalPoint";
return;
case "e":
case "E":
buffer += read();
lexState = "decimalExponent";
return;
}
if (util.isDigit(c)) {
buffer += read();
return;
}
return newToken("numeric", sign * Number(buffer));
},
decimalPointLeading: function decimalPointLeading() {
if (util.isDigit(c)) {
buffer += read();
lexState = "decimalFraction";
return;
}
throw invalidChar(read());
},
decimalPoint: function decimalPoint() {
switch (c) {
case "e":
case "E":
buffer += read();
lexState = "decimalExponent";
return;
}
if (util.isDigit(c)) {
buffer += read();
lexState = "decimalFraction";
return;
}
return newToken("numeric", sign * Number(buffer));
},
decimalFraction: function decimalFraction() {
switch (c) {
case "e":
case "E":
buffer += read();
lexState = "decimalExponent";
return;
}
if (util.isDigit(c)) {
buffer += read();
return;
}
return newToken("numeric", sign * Number(buffer));
},
decimalExponent: function decimalExponent() {
switch (c) {
case "+":
case "-":
buffer += read();
lexState = "decimalExponentSign";
return;
}
if (util.isDigit(c)) {
buffer += read();
lexState = "decimalExponentInteger";
return;
}
throw invalidChar(read());
},
decimalExponentSign: function decimalExponentSign() {
if (util.isDigit(c)) {
buffer += read();
lexState = "decimalExponentInteger";
return;
}
throw invalidChar(read());
},
decimalExponentInteger: function decimalExponentInteger() {
if (util.isDigit(c)) {
buffer += read();
return;
}
return newToken("numeric", sign * Number(buffer));
},
hexadecimal: function hexadecimal() {
if (util.isHexDigit(c)) {
buffer += read();
lexState = "hexadecimalInteger";
return;
}
throw invalidChar(read());
},
hexadecimalInteger: function hexadecimalInteger() {
if (util.isHexDigit(c)) {
buffer += read();
return;
}
return newToken("numeric", sign * Number(buffer));
},
string: function string() {
switch (c) {
case "\\":
read();
buffer += escape();
return;
case "\"":
if (doubleQuote) {
read();
return newToken("string", buffer);
}
buffer += read();
return;
case "'":
if (!doubleQuote) {
read();
return newToken("string", buffer);
}
buffer += read();
return;
case "\n":
case "\r": throw invalidChar(read());
case "\u2028":
case "\u2029":
separatorChar(c);
break;
case void 0: throw invalidChar(read());
}
buffer += read();
},
start: function start() {
switch (c) {
case "{":
case "[": return newToken("punctuator", read());
}
lexState = "value";
},
beforePropertyName: function beforePropertyName() {
switch (c) {
case "$":
case "_":
buffer = read();
lexState = "identifierName";
return;
case "\\":
read();
lexState = "identifierNameStartEscape";
return;
case "}": return newToken("punctuator", read());
case "\"":
case "'":
doubleQuote = read() === "\"";
lexState = "string";
return;
}
if (util.isIdStartChar(c)) {
buffer += read();
lexState = "identifierName";
return;
}
throw invalidChar(read());
},
afterPropertyName: function afterPropertyName() {
if (c === ":") return newToken("punctuator", read());
throw invalidChar(read());
},
beforePropertyValue: function beforePropertyValue() {
lexState = "value";
},
afterPropertyValue: function afterPropertyValue() {
switch (c) {
case ",":
case "}": return newToken("punctuator", read());
}
throw invalidChar(read());
},
beforeArrayValue: function beforeArrayValue() {
if (c === "]") return newToken("punctuator", read());
lexState = "value";
},
afterArrayValue: function afterArrayValue() {
switch (c) {
case ",":
case "]": return newToken("punctuator", read());
}
throw invalidChar(read());
},
end: function end() {
throw invalidChar(read());
}
};
function newToken(type, value) {
return {
type,
value,
line,
column
};
}
function literal(s) {
for (var i = 0, list = s; i < list.length; i += 1) {
var c = list[i];
if (peek() !== c) throw invalidChar(read());
read();
}
}
function escape() {
switch (peek()) {
case "b":
read();
return "\b";
case "f":
read();
return "\f";
case "n":
read();
return "\n";
case "r":
read();
return "\r";
case "t":
read();
return " ";
case "v":
read();
return "\v";
case "0":
read();
if (util.isDigit(peek())) throw invalidChar(read());
return "\0";
case "x":
read();
return hexEscape();
case "u":
read();
return unicodeEscape();
case "\n":
case "\u2028":
case "\u2029":
read();
return "";
case "\r":
read();
if (peek() === "\n") read();
return "";
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9": throw invalidChar(read());
case void 0: throw invalidChar(read());
}
return read();
}
function hexEscape() {
var buffer = "";
var c = peek();
if (!util.isHexDigit(c)) throw invalidChar(read());
buffer += read();
c = peek();
if (!util.isHexDigit(c)) throw invalidChar(read());
buffer += read();
return String.fromCodePoint(parseInt(buffer, 16));
}
function unicodeEscape() {
var buffer = "";
var count = 4;
while (count-- > 0) {
var c = peek();
if (!util.isHexDigit(c)) throw invalidChar(read());
buffer += read();
}
return String.fromCodePoint(parseInt(buffer, 16));
}
var parseStates = {
start: function start() {
if (token.type === "eof") throw invalidEOF();
push();
},
beforePropertyName: function beforePropertyName() {
switch (token.type) {
case "identifier":
case "string":
key = token.value;
parseState = "afterPropertyName";
return;
case "punctuator":
pop();
return;
case "eof": throw invalidEOF();
}
},
afterPropertyName: function afterPropertyName() {
if (token.type === "eof") throw invalidEOF();
parseState = "beforePropertyValue";
},
beforePropertyValue: function beforePropertyValue() {
if (token.type === "eof") throw invalidEOF();
push();
},
beforeArrayValue: function beforeArrayValue() {
if (token.type === "eof") throw invalidEOF();
if (token.type === "punctuator" && token.value === "]") {
pop();
return;
}
push();
},
afterPropertyValue: function afterPropertyValue() {
if (token.type === "eof") throw invalidEOF();
switch (token.value) {
case ",":
parseState = "beforePropertyName";
return;
case "}": pop();
}
},
afterArrayValue: function afterArrayValue() {
if (token.type === "eof") throw invalidEOF();
switch (token.value) {
case ",":
parseState = "beforeArrayValue";
return;
case "]": pop();
}
},
end: function end() {}
};
function push() {
var value;
switch (token.type) {
case "punctuator":
switch (token.value) {
case "{":
value = {};
break;
case "[":
value = [];
break;
}
break;
case "null":
case "boolean":
case "numeric":
case "string":
value = token.value;
break;
}
if (root === void 0) root = value;
else {
var parent = stack[stack.length - 1];
if (Array.isArray(parent)) parent.push(value);
else Object.defineProperty(parent, key, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
if (value !== null && typeof value === "object") {
stack.push(value);
if (Array.isArray(value)) parseState = "beforeArrayValue";
else parseState = "beforePropertyName";
} else {
var current = stack[stack.length - 1];
if (current == null) parseState = "end";
else if (Array.isArray(current)) parseState = "afterArrayValue";
else parseState = "afterPropertyValue";
}
}
function pop() {
stack.pop();
var current = stack[stack.length - 1];
if (current == null) parseState = "end";
else if (Array.isArray(current)) parseState = "afterArrayValue";
else parseState = "afterPropertyValue";
}
function invalidChar(c) {
if (c === void 0) return syntaxError("JSON5: invalid end of input at " + line + ":" + column);
return syntaxError("JSON5: invalid character '" + formatChar(c) + "' at " + line + ":" + column);
}
function invalidEOF() {
return syntaxError("JSON5: invalid end of input at " + line + ":" + column);
}
function invalidIdentifier() {
column -= 5;
return syntaxError("JSON5: invalid identifier character at " + line + ":" + column);
}
function separatorChar(c) {
console.warn("JSON5: '" + formatChar(c) + "' in strings is not valid ECMAScript; consider escaping");
}
function formatChar(c) {
var replacements = {
"'": "\\'",
"\"": "\\\"",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\v": "\\v",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
if (replacements[c]) return replacements[c];
if (c < " ") {
var hexString = c.charCodeAt(0).toString(16);
return "\\x" + ("00" + hexString).substring(hexString.length);
}
return c;
}
function syntaxError(message) {
var err = new SyntaxError(message);
err.lineNumber = line;
err.columnNumber = column;
return err;
}
return {
parse,
stringify: function stringify(value, replacer, space) {
var stack = [];
var indent = "";
var propertyList;
var replacerFunc;
var gap = "";
var quote;
if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
space = replacer.space;
quote = replacer.quote;
replacer = replacer.replacer;
}
if (typeof replacer === "function") replacerFunc = replacer;
else if (Array.isArray(replacer)) {
propertyList = [];
for (var i = 0, list = replacer; i < list.length; i += 1) {
var v = list[i];
var item = void 0;
if (typeof v === "string") item = v;
else if (typeof v === "number" || v instanceof String || v instanceof Number) item = String(v);
if (item !== void 0 && propertyList.indexOf(item) < 0) propertyList.push(item);
}
}
if (space instanceof Number) space = Number(space);
else if (space instanceof String) space = String(space);
if (typeof space === "number") {
if (space > 0) {
space = Math.min(10, Math.floor(space));
gap = " ".substr(0, space);
}
} else if (typeof space === "string") gap = space.substr(0, 10);
return serializeProperty("", { "": value });
function serializeProperty(key, holder) {
var value = holder[key];
if (value != null) {
if (typeof value.toJSON5 === "function") value = value.toJSON5(key);
else if (typeof value.toJSON === "function") value = value.toJSON(key);
}
if (replacerFunc) value = replacerFunc.call(holder, key, value);
if (value instanceof Number) value = Number(value);
else if (value instanceof String) value = String(value);
else if (value instanceof Boolean) value = value.valueOf();
switch (value) {
case null: return "null";
case true: return "true";
case false: return "false";
}
if (typeof value === "string") return quoteString(value, false);
if (typeof value === "number") return String(value);
if (typeof value === "object") return Array.isArray(value) ? serializeArray(value) : serializeObject(value);
}
function quoteString(value) {
var quotes = {
"'": .1,
"\"": .2
};
var replacements = {
"'": "\\'",
"\"": "\\\"",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\v": "\\v",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
var product = "";
for (var i = 0; i < value.length; i++) {
var c = value[i];
switch (c) {
case "'":
case "\"":
quotes[c]++;
product += c;
continue;
case "\0": if (util.isDigit(value[i + 1])) {
product += "\\x00";
continue;
}
}
if (replacements[c]) {
product += replacements[c];
continue;
}
if (c < " ") {
var hexString = c.charCodeAt(0).toString(16);
product += "\\x" + ("00" + hexString).substring(hexString.length);
continue;
}
product += c;
}
var quoteChar = quote || Object.keys(quotes).reduce(function(a, b) {
return quotes[a] < quotes[b] ? a : b;
});
product = product.replace(new RegExp(quoteChar, "g"), replacements[quoteChar]);
return quoteChar + product + quoteChar;
}
function serializeObject(value) {
if (stack.indexOf(value) >= 0) throw TypeError("Converting circular structure to JSON5");
stack.push(value);
var stepback = indent;
indent = indent + gap;
var keys = propertyList || Object.keys(value);
var partial = [];
for (var i = 0, list = keys; i < list.length; i += 1) {
var key = list[i];
var propertyString = serializeProperty(key, value);
if (propertyString !== void 0) {
var member = serializeKey(key) + ":";
if (gap !== "") member += " ";
member += propertyString;
partial.push(member);
}
}
var final;
if (partial.length === 0) final = "{}";
else {
var properties;
if (gap === "") {
properties = partial.join(",");
final = "{" + properties + "}";
} else {
var separator = ",\n" + indent;
properties = partial.join(separator);
final = "{\n" + indent + properties + ",\n" + stepback + "}";
}
}
stack.pop();
indent = stepback;
return final;
}
function serializeKey(key) {
if (key.length === 0) return quoteString(key, true);
var firstChar = String.fromCodePoint(key.codePointAt(0));
if (!util.isIdStartChar(firstChar)) return quoteString(key, true);
for (var i = firstChar.length; i < key.length; i++) if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) return quoteString(key, true);
return key;
}
function serializeArray(value) {
if (stack.indexOf(value) >= 0) throw TypeError("Converting circular structure to JSON5");
stack.push(value);
var stepback = indent;
indent = indent + gap;
var partial = [];
for (var i = 0; i < value.length; i++) {
var propertyString = serializeProperty(String(i), value);
partial.push(propertyString !== void 0 ? propertyString : "null");
}
var final;
if (partial.length === 0) final = "[]";
else if (gap === "") final = "[" + partial.join(",") + "]";
else {
var separator = ",\n" + indent;
var properties$1 = partial.join(separator);
final = "[\n" + indent + properties$1 + ",\n" + stepback + "]";
}
stack.pop();
indent = stepback;
return final;
}
}
};
}));
})))(), 1);
var onChange = (element) => {
if (element.id == "left") if (element.value != "") document.querySelector(".position#right").disabled = true;
else document.querySelector(".position#right").disabled = false;
if (element.id == "right") if (element.value != "") document.querySelector(".position#left").disabled = true;
else document.querySelector(".position#left").disabled = false;
if (element.id == "top") if (element.value != "") document.querySelector(".position#bottom").disabled = true;
else document.querySelector(".position#bottom").disabled = false;
if (element.id == "bottom") if (element.value != "") document.querySelector(".position#top").disabled = true;
else document.querySelector(".position#top").disabled = false;
};
var constructPositionArray = () => {
const left = document.querySelector(".position#left").value;
const right = document.querySelector(".position#right").value;
const top = document.querySelector(".position#top").value;
const bottom = document.querySelector(".position#bottom").value;
if (!left && !right && !top && !bottom) return [];
else return [
top,
left,
right,
bottom
];
};
var iArrayToArray_default = (array = []) => {
return Array().concat(array);
};
var groupsKeyOrder = [
"key",
"name",
"desc",
"matchTime",
"actionMaximum",
"resetMatch",
"priorityTime",
"matchRoot",
"rules"
];
var sort_default = async (groups) => {
const rulesKeyOrder = await getHanashiroSettings("rulesKeySort");
const groupsKeyValue = [];
const rulesKeyValue = [];
groupsKeyOrder.forEach((groupsKey) => {
if (groups[groupsKey] !== void 0) groupsKeyValue.push(groups[groupsKey]);
else groupsKeyValue.push(void 0);
});
rulesKeyOrder.forEach((rulesKey) => {
if (groups.rules[0][rulesKey] !== void 0) rulesKeyValue.push(groups.rules[0][rulesKey]);
else rulesKeyValue.push(void 0);
});
const sortedRules = {};
rulesKeyOrder.forEach((rulesKey, index) => {
sortedRules[rulesKey] = rulesKeyValue[index];
});
return {
key: groupsKeyValue[0],
name: groupsKeyValue[1],
desc: groupsKeyValue[2],
matchTime: groupsKeyValue[3],
actionMaximum: groupsKeyValue[4],
resetMatch: groupsKeyValue[5],
priorityTime: groupsKeyValue[6],
matchRoot: groupsKeyValue[7],
rules: [sortedRules]
};
};
var checkPositionLegality = (position) => {
const { top, left, right, bottom } = position;
if (top) {
if (bottom || !left && !right) {
snackbar({
message: "非法坐标",
placement: "top"
});
return false;
}
}
if (left) {
if (right || !top && !bottom) {
snackbar({
message: "非法坐标",
placement: "top"
});
return false;
}
}
if (right) {
if (left || !top && !bottom) {
snackbar({
message: "非法坐标",
placement: "top"
});
return false;
}
}
if (bottom) {
if (top || !left && !right) {
snackbar({
message: "非法坐标",
placement: "top"
});
return false;
}
}
return true;
};
var finish_default = async () => {
const copyDepth = document.querySelector("#copyDepth").value;
const action = document.querySelector("#action").value;
const ruleName = document.querySelector("#ruleName").value;
const ruleDesc = document.querySelector("#ruleDesc").value;
const category = window.Hanashiro.currentCategory;
const isLimit = document.querySelector("#limit").checked;
const isMatchRoot = document.querySelector("#matchRoot").checked;
const isNoExample = document.querySelector("#noExample").checked;
const preKeys = document.querySelector("#preKeys").value;
const position = constructPositionArray().length != 0 ? constructPositionArray() : false;
const isSimplyActivityIds = await getHanashiroSettings("activityIdsSimply");
const origin = import_dist.default.parse(window.Hanashiro.originRule);
if (ruleName) origin.groups[0].name = ruleName;
else origin.groups[0].name = "";
if (ruleDesc) origin.groups[0].desc = ruleDesc;
else delete origin.groups[0].desc;
if (category) {
if (!ruleName) origin.groups[0].name = category;
else origin.groups[0].name = `${category}-${origin.groups[0].name}`;
if (category == "开屏广告") {
origin.groups[0].priorityTime = 1e4;
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
delete rule.activityIds;
origin.groups[0].rules = [rule];
}
}
if (action) {
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.action = action;
origin.groups[0].rules = [rule];
}
if (isLimit) if (copyDepth == "rules") {
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.actionMaximum = 1;
rule.resetMatch = "app";
rule.matchTime = 1e4;
origin.groups[0].rules = [rule];
} else {
origin.groups[0].actionMaximum = 1;
origin.groups[0].resetMatch = "app";
origin.groups[0].matchTime = 1e4;
}
if (isMatchRoot) if (copyDepth == "rules") {
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.matchRoot = true;
origin.groups[0].rules = [rule];
} else origin.groups[0].matchRoot = true;
if (isNoExample) {
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
delete rule.exampleUrls;
origin.groups[0].rules = [rule];
}
if (preKeys) {
const preKeysArray = preKeys.split(",");
const preKeysNumberArray = [];
preKeysArray.forEach((preKey) => {
preKeysNumberArray.push(Number(preKey));
});
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.preKeys = preKeysNumberArray;
origin.groups[0].rules = [rule];
}
if (position) {
const positionName = [
"top",
"left",
"right",
"bottom"
];
const positionObject = {};
position.forEach((position, index) => {
if (position) positionObject[positionName[index]] = position;
});
if (!checkPositionLegality(positionObject)) return;
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.position = positionObject;
origin.groups[0].rules = [rule];
}
if (isSimplyActivityIds === true) {
const snapshotId = getSnapshotId_default();
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
const result = await simplyActivityIds(snapshotId);
if (result && rule.activityIds) {
rule.activityIds = result;
origin.groups[0].rules = [rule];
}
}
origin.groups[0] = await sort_default(origin.groups[0]);
const stringify = import_dist.default.stringify(origin, null, 2);
if (copyDepth == "ts") {
const text = `import { defineGkdApp } from '@gkd-kit/define';\r\rexport default defineGkdApp(${stringify});\r`;
window.Hanashiro.returnResult = text;
} else if (copyDepth == "app") window.Hanashiro.returnResult = stringify;
else if (copyDepth == "groups") window.Hanashiro.returnResult = import_dist.default.stringify(origin.groups[0], null, 2);
else if (copyDepth == "rules") window.Hanashiro.returnResult = import_dist.default.stringify(iArrayToArray_default(origin.groups[0].rules)[0], null, 2);
send("closePage");
send("modifyEnd");
};
var key_default = () => {
const copyDepth = document.querySelector("#copyDepth").value;
const key = document.querySelector("#key").value;
const origin = import_dist.default.parse(window.Hanashiro.originRule);
if (key) {
if (copyDepth == "rules") {
const rule = iArrayToArray_default(origin.groups[0].rules)[0];
rule.key = Number(key);
origin.groups[0].rules = [rule];
} else origin.groups[0].key = Number(key);
window.Hanashiro.originRule = import_dist.default.stringify(origin, null, 2);
snackbar({
message: "key值修改成功!",
placement: "top"
});
}
};
var renderedCategories_default = async () => {
const categories = await getHanashiroSettings("categories");
const categoriesGroup = document.querySelector("#category");
if (categories) {
let innerHtmlString = "";
categories.forEach((category) => {
innerHtmlString += `
${category.name}`;
});
categoriesGroup.innerHTML = innerHtmlString;
}
};
Object.freeze({ status: "aborted" });
function $constructor(name, initializer, params) {
function init(inst, def) {
if (!inst._zod) Object.defineProperty(inst, "_zod", {
value: {
def,
constr: _,
traits: new Set()
},
enumerable: false
});
if (inst._zod.traits.has(name)) return;
inst._zod.traits.add(name);
initializer(inst, def);
const proto = _.prototype;
const keys = Object.keys(proto);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (!(k in inst)) inst[k] = proto[k].bind(inst);
}
}
const Parent = params?.Parent ?? Object;
class Definition extends Parent {}
Object.defineProperty(Definition, "name", { value: name });
function _(def) {
var _a;
const inst = params?.Parent ? new Definition() : this;
init(inst, def);
(_a = inst._zod).deferred ?? (_a.deferred = []);
for (const fn of inst._zod.deferred) fn();
return inst;
}
Object.defineProperty(_, "init", { value: init });
Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
if (params?.Parent && inst instanceof params.Parent) return true;
return inst?._zod?.traits?.has(name);
} });
Object.defineProperty(_, "name", { value: name });
return _;
}
var $ZodAsyncError = class extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
};
var $ZodEncodeError = class extends Error {
constructor(name) {
super(`Encountered unidirectional transform during encode: ${name}`);
this.name = "ZodEncodeError";
}
};
var globalConfig = {};
function config(newConfig) {
if (newConfig) Object.assign(globalConfig, newConfig);
return globalConfig;
}
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
}
function jsonStringifyReplacer(_, value) {
if (typeof value === "bigint") return value.toString();
return value;
}
function cached(getter) {
return { get value() {
{
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
throw new Error("cached value already set");
} };
}
function nullish(input) {
return input === null || input === void 0;
}
function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepString = step.toString();
let stepDecCount = (stepString.split(".")[1] || "").length;
if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
const match = stepString.match(/\d?e-(\d?)/);
if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
}
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
}
var EVALUATING = Symbol("evaluating");
function defineLazy(object, key, getter) {
let value = void 0;
Object.defineProperty(object, key, {
get() {
if (value === EVALUATING) return;
if (value === void 0) {
value = EVALUATING;
value = getter();
}
return value;
},
set(v) {
Object.defineProperty(object, key, { value: v });
},
configurable: true
});
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
const descriptors = Object.getOwnPropertyDescriptors(def);
Object.assign(mergedDescriptors, descriptors);
}
return Object.defineProperties({}, mergedDescriptors);
}
function esc(str) {
return JSON.stringify(str);
}
function slugify(input) {
return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval = cached(() => {
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
try {
new Function("");
return true;
} catch (_) {
return false;
}
});
function isPlainObject(o) {
if (isObject(o) === false) return false;
const ctor = o.constructor;
if (ctor === void 0) return true;
if (typeof ctor !== "function") return true;
const prot = ctor.prototype;
if (isObject(prot) === false) return false;
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
return true;
}
function shallowClone(o) {
if (isPlainObject(o)) return { ...o };
if (Array.isArray(o)) return [...o];
return o;
}
var propertyKeyTypes = new Set([
"string",
"number",
"symbol"
]);
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent) cl._zod.parent = inst;
return cl;
}
function normalizeParams(_params) {
const params = _params;
if (!params) return {};
if (typeof params === "string") return { error: () => params };
if (params?.message !== void 0) {
if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string") return {
...params,
error: () => params.error
};
return params;
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
});
}
var NUMBER_FORMAT_RANGES = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-34028234663852886e22, 34028234663852886e22],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
function pick(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
return clone(schema, mergeDefs(schema._zod.def, {
get shape() {
const newShape = {};
for (const key in mask) {
if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
newShape[key] = currDef.shape[key];
}
assignProp(this, "shape", newShape);
return newShape;
},
checks: []
}));
}
function omit(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
return clone(schema, mergeDefs(schema._zod.def, {
get shape() {
const newShape = { ...schema._zod.def.shape };
for (const key in mask) {
if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
delete newShape[key];
}
assignProp(this, "shape", newShape);
return newShape;
},
checks: []
}));
}
function extend(schema, shape) {
if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
const checks = schema._zod.def.checks;
if (checks && checks.length > 0) {
const existingShape = schema._zod.def.shape;
for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
return clone(schema, mergeDefs(schema._zod.def, { get shape() {
const _shape = {
...schema._zod.def.shape,
...shape
};
assignProp(this, "shape", _shape);
return _shape;
} }));
}
function safeExtend(schema, shape) {
if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
return clone(schema, mergeDefs(schema._zod.def, { get shape() {
const _shape = {
...schema._zod.def.shape,
...shape
};
assignProp(this, "shape", _shape);
return _shape;
} }));
}
function merge(a, b) {
return clone(a, mergeDefs(a._zod.def, {
get shape() {
const _shape = {
...a._zod.def.shape,
...b._zod.def.shape
};
assignProp(this, "shape", _shape);
return _shape;
},
get catchall() {
return b._zod.def.catchall;
},
checks: []
}));
}
function partial(Class, schema, mask) {
const checks = schema._zod.def.checks;
if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
return clone(schema, mergeDefs(schema._zod.def, {
get shape() {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key in mask) {
if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
}
else for (const key in oldShape) shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
assignProp(this, "shape", shape);
return shape;
},
checks: []
}));
}
function required(Class, schema, mask) {
return clone(schema, mergeDefs(schema._zod.def, { get shape() {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key in mask) {
if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
}
else for (const key in oldShape) shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
assignProp(this, "shape", shape);
return shape;
} }));
}
function aborted(x, startIndex = 0) {
if (x.aborted === true) return true;
for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config) {
const full = {
...iss,
path: iss.path ?? []
};
if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) delete full.input;
return full;
}
function getLengthableOrigin(input) {
if (Array.isArray(input)) return "array";
if (typeof input === "string") return "string";
return "unknown";
}
function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") return {
message: iss,
code: "custom",
input,
inst
};
return { ...iss };
}
var initializer$1 = (inst, def) => {
inst.name = "$ZodError";
Object.defineProperty(inst, "_zod", {
value: inst._zod,
enumerable: false
});
Object.defineProperty(inst, "issues", {
value: def,
enumerable: false
});
inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
Object.defineProperty(inst, "toString", {
value: () => inst.message,
enumerable: false
});
};
var $ZodError = $constructor("$ZodError", initializer$1);
var $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
else if (issue.code === "invalid_key") processError({ issues: issue.issues });
else if (issue.code === "invalid_element") processError({ issues: issue.issues });
else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
};
processError(error);
return fieldErrors;
}
var _parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
const result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) throw new $ZodAsyncError();
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, _params?.callee);
throw e;
}
return result.value;
};
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, params?.callee);
throw e;
}
return result.value;
};
var _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
async: false
} : { async: false };
const result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) throw new $ZodAsyncError();
return result.issues.length ? {
success: false,
error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
var safeParse$1 = _safeParse($ZodRealError);
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
return result.issues.length ? {
success: false,
error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
var safeParseAsync$1 = _safeParseAsync($ZodRealError);
var _encode$1 = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
return _parse(_Err)(schema, value, ctx);
};
var _decode$1 = (_Err) => (schema, value, _ctx) => {
return _parse(_Err)(schema, value, _ctx);
};
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
return _parseAsync(_Err)(schema, value, ctx);
};
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
return _parseAsync(_Err)(schema, value, _ctx);
};
var _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
};
var _safeDecode = (_Err) => (schema, value, _ctx) => {
return _safeParse(_Err)(schema, value, _ctx);
};
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
return _safeParseAsync(_Err)(schema, value, ctx);
};
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _safeParseAsync(_Err)(schema, value, _ctx);
};
var cuid = /^[cC][^\s-]{8,}$/;
var cuid2 = /^[0-9a-z]+$/;
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
var uuid = (version) => {
if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
return new RegExp(_emoji$1, "u");
}
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url = /^[A-Za-z0-9_-]*$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
var date$1 = new RegExp(`^${dateSource}$`);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
}
function time$1(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(args) {
const time = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local) opts.push("");
if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
const timeRegex = `${time}(?:${opts.join("|")})`;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var string$1 = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
var integer = /^-?\d+$/;
var number$1 = /^-?\d+(?:\.\d+)?$/;
var boolean$1 = /^(?:true|false)$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
var $ZodCheck = $constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
var numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date"
};
var $ZodCheckLessThan = $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
else bag.exclusiveMaximum = def.value;
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
payload.issues.push({
origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort
});
};
});
var $ZodCheckGreaterThan = $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
else bag.exclusiveMinimum = def.value;
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
payload.issues.push({
origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort
});
};
});
var $ZodCheckMultipleOf = $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
var _a;
(_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
});
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodCheckNumberFormat = $constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def);
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
bag.minimum = minimum;
bag.maximum = maximum;
if (isInt) bag.pattern = integer;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
continue: false,
input,
inst
});
return;
}
if (!Number.isSafeInteger(input)) {
if (input > 0) payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort
});
else payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort
});
return;
}
}
if (input < minimum) payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort
});
if (input > maximum) payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort
});
};
});
var $ZodCheckMaxLength = $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst) => {
const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input.length <= def.maximum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
var $ZodCheckMinLength = $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst) => {
const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input.length >= def.minimum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
var $ZodCheckLengthEquals = $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.minimum = def.length;
bag.maximum = def.length;
bag.length = def.length;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length === def.length) return;
const origin = getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...tooBig ? {
code: "too_big",
maximum: def.length
} : {
code: "too_small",
minimum: def.length
},
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodCheckStringFormat = $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
if (def.pattern) {
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(def.pattern);
}
});
if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...def.pattern ? { pattern: def.pattern.toString() } : {},
inst,
continue: !def.abort
});
});
else (_b = inst._zod).check ?? (_b.check = () => {});
});
var $ZodCheckRegex = $constructor("$ZodCheckRegex", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort
});
};
});
var $ZodCheckLowerCase = $constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = $constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckIncludes = $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = escapeRegex(def.includes);
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodCheckStartsWith = $constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodCheckEndsWith = $constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodCheckOverwrite = $constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
var Doc = class {
constructor(args = []) {
this.content = [];
this.indent = 0;
if (this) this.args = args;
}
indented(fn) {
this.indent += 1;
fn(this);
this.indent -= 1;
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const lines = arg.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) this.content.push(line);
}
compile() {
const F = Function;
const args = this?.args;
const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
return new F(...args, lines.join("\n"));
}
};
var version = {
major: 4,
minor: 3,
patch: 6
};
var $ZodType = $constructor("$ZodType", (inst, def) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
const checks = [...inst._zod.def.checks ?? []];
if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
if (checks.length === 0) {
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred?.push(() => {
inst._zod.run = inst._zod.parse;
});
} else {
const runChecks = (payload, checks, ctx) => {
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
if (!ch._zod.def.when(payload)) continue;
} else if (isAborted) continue;
const currLen = payload.issues.length;
const _ = ch._zod.check(payload);
if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _;
if (payload.issues.length === currLen) return;
if (!isAborted) isAborted = aborted(payload, currLen);
});
else {
if (payload.issues.length === currLen) continue;
if (!isAborted) isAborted = aborted(payload, currLen);
}
}
if (asyncResult) return asyncResult.then(() => {
return payload;
});
return payload;
};
const handleCanaryResult = (canary, payload, ctx) => {
if (aborted(canary)) {
canary.aborted = true;
return canary;
}
const checkResult = runChecks(payload, checks, ctx);
if (checkResult instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
}
return inst._zod.parse(checkResult, ctx);
};
inst._zod.run = (payload, ctx) => {
if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
if (ctx.direction === "backward") {
const canary = inst._zod.parse({
value: payload.value,
issues: []
}, {
...ctx,
skipChecks: true
});
if (canary instanceof Promise) return canary.then((canary) => {
return handleCanaryResult(canary, payload, ctx);
});
return handleCanaryResult(canary, payload, ctx);
}
const result = inst._zod.parse(payload, ctx);
if (result instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return result.then((result) => runChecks(result, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
defineLazy(inst, "~standard", () => ({
validate: (value) => {
try {
const r = safeParse$1(inst, value);
return r.success ? { value: r.data } : { issues: r.error?.issues };
} catch (_) {
return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
}
},
vendor: "zod",
version: 1
}));
});
var $ZodString = $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
inst._zod.parse = (payload, _) => {
if (def.coerce) try {
payload.value = String(payload.value);
} catch (_) {}
if (typeof payload.value === "string") return payload;
payload.issues.push({
expected: "string",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
var $ZodStringFormat = $constructor("$ZodStringFormat", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
$ZodString.init(inst, def);
});
var $ZodGUID = $constructor("$ZodGUID", (inst, def) => {
def.pattern ?? (def.pattern = guid);
$ZodStringFormat.init(inst, def);
});
var $ZodUUID = $constructor("$ZodUUID", (inst, def) => {
if (def.version) {
const v = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8
}[def.version];
if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
def.pattern ?? (def.pattern = uuid(v));
} else def.pattern ?? (def.pattern = uuid());
$ZodStringFormat.init(inst, def);
});
var $ZodEmail = $constructor("$ZodEmail", (inst, def) => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
var $ZodURL = $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const trimmed = payload.value.trim();
const url = new URL(trimmed);
if (def.hostname) {
def.hostname.lastIndex = 0;
if (!def.hostname.test(url.hostname)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid hostname",
pattern: def.hostname.source,
input: payload.value,
inst,
continue: !def.abort
});
}
if (def.protocol) {
def.protocol.lastIndex = 0;
if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid protocol",
pattern: def.protocol.source,
input: payload.value,
inst,
continue: !def.abort
});
}
if (def.normalize) payload.value = url.href;
else payload.value = trimmed;
return;
} catch (_) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
var $ZodEmoji = $constructor("$ZodEmoji", (inst, def) => {
def.pattern ?? (def.pattern = emoji());
$ZodStringFormat.init(inst, def);
});
var $ZodNanoID = $constructor("$ZodNanoID", (inst, def) => {
def.pattern ?? (def.pattern = nanoid);
$ZodStringFormat.init(inst, def);
});
var $ZodCUID = $constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = cuid);
$ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = $constructor("$ZodCUID2", (inst, def) => {
def.pattern ?? (def.pattern = cuid2);
$ZodStringFormat.init(inst, def);
});
var $ZodULID = $constructor("$ZodULID", (inst, def) => {
def.pattern ?? (def.pattern = ulid);
$ZodStringFormat.init(inst, def);
});
var $ZodXID = $constructor("$ZodXID", (inst, def) => {
def.pattern ?? (def.pattern = xid);
$ZodStringFormat.init(inst, def);
});
var $ZodKSUID = $constructor("$ZodKSUID", (inst, def) => {
def.pattern ?? (def.pattern = ksuid);
$ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = $constructor("$ZodISODateTime", (inst, def) => {
def.pattern ?? (def.pattern = datetime$1(def));
$ZodStringFormat.init(inst, def);
});
var $ZodISODate = $constructor("$ZodISODate", (inst, def) => {
def.pattern ?? (def.pattern = date$1);
$ZodStringFormat.init(inst, def);
});
var $ZodISOTime = $constructor("$ZodISOTime", (inst, def) => {
def.pattern ?? (def.pattern = time$1(def));
$ZodStringFormat.init(inst, def);
});
var $ZodISODuration = $constructor("$ZodISODuration", (inst, def) => {
def.pattern ?? (def.pattern = duration$1);
$ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
inst._zod.bag.format = `ipv6`;
inst._zod.check = (payload) => {
try {
new URL(`http://[${payload.value}]`);
} catch {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
var $ZodCIDRv4 = $constructor("$ZodCIDRv4", (inst, def) => {
def.pattern ?? (def.pattern = cidrv4);
$ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = $constructor("$ZodCIDRv6", (inst, def) => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
const parts = payload.value.split("/");
try {
if (parts.length !== 2) throw new Error();
const [address, prefix] = parts;
if (!prefix) throw new Error();
const prefixNum = Number(prefix);
if (`${prefixNum}` !== prefix) throw new Error();
if (prefixNum < 0 || prefixNum > 128) throw new Error();
new URL(`http://[${address}]`);
} catch {
payload.issues.push({
code: "invalid_format",
format: "cidrv6",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
function isValidBase64(data) {
if (data === "") return true;
if (data.length % 4 !== 0) return false;
try {
atob(data);
return true;
} catch {
return false;
}
}
var $ZodBase64 = $constructor("$ZodBase64", (inst, def) => {
def.pattern ?? (def.pattern = base64);
$ZodStringFormat.init(inst, def);
inst._zod.bag.contentEncoding = "base64";
inst._zod.check = (payload) => {
if (isValidBase64(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64",
input: payload.value,
inst,
continue: !def.abort
});
};
});
function isValidBase64URL(data) {
if (!base64url.test(data)) return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
}
var $ZodBase64URL = $constructor("$ZodBase64URL", (inst, def) => {
def.pattern ?? (def.pattern = base64url);
$ZodStringFormat.init(inst, def);
inst._zod.bag.contentEncoding = "base64url";
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64url",
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodE164 = $constructor("$ZodE164", (inst, def) => {
def.pattern ?? (def.pattern = e164);
$ZodStringFormat.init(inst, def);
});
function isValidJWT(token, algorithm = null) {
try {
const tokensParts = token.split(".");
if (tokensParts.length !== 3) return false;
const [header] = tokensParts;
if (!header) return false;
const parsedHeader = JSON.parse(atob(header));
if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
if (!parsedHeader.alg) return false;
if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
return true;
} catch {
return false;
}
}
var $ZodJWT = $constructor("$ZodJWT", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidJWT(payload.value, def.alg)) return;
payload.issues.push({
code: "invalid_format",
format: "jwt",
input: payload.value,
inst,
continue: !def.abort
});
};
});
var $ZodNumber = $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Number(payload.value);
} catch (_) {}
const input = payload.value;
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
payload.issues.push({
expected: "number",
code: "invalid_type",
input,
inst,
...received ? { received } : {}
});
return payload;
};
});
var $ZodNumberFormat = $constructor("$ZodNumberFormat", (inst, def) => {
$ZodCheckNumberFormat.init(inst, def);
$ZodNumber.init(inst, def);
});
var $ZodBoolean = $constructor("$ZodBoolean", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = boolean$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Boolean(payload.value);
} catch (_) {}
const input = payload.value;
if (typeof input === "boolean") return payload;
payload.issues.push({
expected: "boolean",
code: "invalid_type",
input,
inst
});
return payload;
};
});
var $ZodUnknown = $constructor("$ZodUnknown", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload) => payload;
});
var $ZodNever = $constructor("$ZodNever", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
payload.issues.push({
expected: "never",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
function handleArrayResult(result, final, index) {
if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
final.value[index] = result.value;
}
var $ZodArray = $constructor("$ZodArray", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
payload.issues.push({
expected: "array",
code: "invalid_type",
input,
inst
});
return payload;
}
payload.value = Array(input.length);
const proms = [];
for (let i = 0; i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
value: item,
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
else handleArrayResult(result, payload, i);
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
function handlePropertyResult(result, final, key, input, isOptionalOut) {
if (result.issues.length) {
if (isOptionalOut && !(key in input)) return;
final.issues.push(...prefixIssues(key, result.issues));
}
if (result.value === void 0) {
if (key in input) final.value[key] = void 0;
} else final.value[key] = result.value;
}
function normalizeDef(def) {
const keys = Object.keys(def.shape);
for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
const okeys = optionalKeys(def.shape);
return {
...def,
keys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
const unrecognized = [];
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
const isOptionalOut = _catchall.optout === "optional";
for (const key in input) {
if (keySet.has(key)) continue;
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({
value: input[key],
issues: []
}, ctx);
if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
else handlePropertyResult(r, payload, key, input, isOptionalOut);
}
if (unrecognized.length) payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input,
inst
});
if (!proms.length) return payload;
return Promise.all(proms).then(() => {
return payload;
});
}
var $ZodObject = $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
const sh = def.shape;
Object.defineProperty(def, "shape", { get: () => {
const newSh = { ...sh };
Object.defineProperty(def, "shape", { value: newSh });
return newSh;
} });
}
const _normalized = cached(() => normalizeDef(def));
defineLazy(inst._zod, "propValues", () => {
const shape = def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
propValues[key] ?? (propValues[key] = new Set());
for (const v of field.values) propValues[key].add(v);
}
}
return propValues;
});
const isObject$3 = isObject;
const catchall = def.catchall;
let value;
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$3(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
payload.value = {};
const proms = [];
const shape = value.shape;
for (const key of value.keys) {
const el = shape[key];
const isOptionalOut = el._zod.optout === "optional";
const r = el._zod.run({
value: input[key],
issues: []
}, ctx);
if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
else handlePropertyResult(r, payload, key, input, isOptionalOut);
}
if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
};
});
var $ZodObjectJIT = $constructor("$ZodObjectJIT", (inst, def) => {
$ZodObject.init(inst, def);
const superParse = inst._zod.parse;
const _normalized = cached(() => normalizeDef(def));
const generateFastpass = (shape) => {
const doc = new Doc([
"shape",
"payload",
"ctx"
]);
const normalized = _normalized.value;
const parseStr = (key) => {
const k = esc(key);
return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
};
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
for (const key of normalized.keys) ids[key] = `key_${counter++}`;
doc.write(`const newResult = {};`);
for (const key of normalized.keys) {
const id = ids[key];
const k = esc(key);
const isOptionalOut = shape[key]?._zod?.optout === "optional";
doc.write(`const ${id} = ${parseStr(key)};`);
if (isOptionalOut) doc.write(`
if (${id}.issues.length) {
if (${k} in input) {
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
})));
}
}
if (${id}.value === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
}
} else {
newResult[${k}] = ${id}.value;
}
`);
else doc.write(`
if (${id}.issues.length) {
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
})));
}
if (${id}.value === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
}
} else {
newResult[${k}] = ${id}.value;
}
`);
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
const fn = doc.compile();
return (payload, ctx) => fn(shape, payload, ctx);
};
let fastpass;
const isObject$2 = isObject;
const jit = !globalConfig.jitless;
const fastEnabled = jit && allowsEval.value;
const catchall = def.catchall;
let value;
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$2(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
if (!fastpass) fastpass = generateFastpass(def.shape);
payload = fastpass(payload, ctx);
if (!catchall) return payload;
return handleCatchall([], input, payload, ctx, value, inst);
}
return superParse(payload, ctx);
};
});
function handleUnionResults(results, final, inst, ctx) {
for (const result of results) if (result.issues.length === 0) {
final.value = result.value;
return final;
}
const nonaborted = results.filter((r) => !aborted(r));
if (nonaborted.length === 1) {
final.value = nonaborted[0].value;
return nonaborted[0];
}
final.issues.push({
code: "invalid_union",
input: final.value,
inst,
errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
});
return final;
}
var $ZodUnion = $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "values", () => {
if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
});
defineLazy(inst._zod, "pattern", () => {
if (def.options.every((o) => o._zod.pattern)) {
const patterns = def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
});
const single = def.options.length === 1;
const first = def.options[0]._zod.run;
inst._zod.parse = (payload, ctx) => {
if (single) return first(payload, ctx);
let async = false;
const results = [];
for (const option of def.options) {
const result = option._zod.run({
value: payload.value,
issues: []
}, ctx);
if (result instanceof Promise) {
results.push(result);
async = true;
} else {
if (result.issues.length === 0) return result;
results.push(result);
}
}
if (!async) return handleUnionResults(results, payload, inst, ctx);
return Promise.all(results).then((results) => {
return handleUnionResults(results, payload, inst, ctx);
});
};
});
var $ZodIntersection = $constructor("$ZodIntersection", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
const left = def.left._zod.run({
value: input,
issues: []
}, ctx);
const right = def.right._zod.run({
value: input,
issues: []
}, ctx);
if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
return handleIntersectionResults(payload, left, right);
});
return handleIntersectionResults(payload, left, right);
};
});
function mergeValues(a, b) {
if (a === b) return {
valid: true,
data: a
};
if (a instanceof Date && b instanceof Date && +a === +b) return {
valid: true,
data: a
};
if (isPlainObject(a) && isPlainObject(b)) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
};
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return {
valid: false,
mergeErrorPath: []
};
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
};
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
}
return {
valid: false,
mergeErrorPath: []
};
}
function handleIntersectionResults(result, left, right) {
const unrecKeys = new Map();
let unrecIssue;
for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
unrecIssue ?? (unrecIssue = iss);
for (const k of iss.keys) {
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
unrecKeys.get(k).l = true;
}
} else result.issues.push(iss);
for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
unrecKeys.get(k).r = true;
}
else result.issues.push(iss);
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
if (bothKeys.length && unrecIssue) result.issues.push({
...unrecIssue,
keys: bothKeys
});
if (aborted(result)) return result;
const merged = mergeValues(left.value, right.value);
if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
result.value = merged.data;
return result;
}
var $ZodEnum = $constructor("$ZodEnum", (inst, def) => {
$ZodType.init(inst, def);
const values = getEnumValues(def.entries);
const valuesSet = new Set(values);
inst._zod.values = valuesSet;
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (valuesSet.has(input)) return payload;
payload.issues.push({
code: "invalid_value",
values,
input,
inst
});
return payload;
};
});
var $ZodTransform = $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
const _out = def.transform(payload.value, payload);
if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
payload.value = output;
return payload;
});
if (_out instanceof Promise) throw new $ZodAsyncError();
payload.value = _out;
return payload;
};
});
function handleOptionalResult(result, input) {
if (result.issues.length && input === void 0) return {
issues: [],
value: void 0
};
return result;
}
var $ZodOptional = $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
inst._zod.optout = "optional";
defineLazy(inst._zod, "values", () => {
return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
});
defineLazy(inst._zod, "pattern", () => {
const pattern = def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (def.innerType._zod.optin === "optional") {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
return handleOptionalResult(result, payload.value);
}
if (payload.value === void 0) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodExactOptional = $constructor("$ZodExactOptional", (inst, def) => {
$ZodOptional.init(inst, def);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
inst._zod.parse = (payload, ctx) => {
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodNullable = $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
defineLazy(inst._zod, "pattern", () => {
const pattern = def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
});
defineLazy(inst._zod, "values", () => {
return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodDefault = $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) {
payload.value = def.defaultValue;
return payload;
}
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
return handleDefaultResult(result, def);
};
});
function handleDefaultResult(payload, def) {
if (payload.value === void 0) payload.value = def.defaultValue;
return payload;
}
var $ZodPrefault = $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) payload.value = def.defaultValue;
return def.innerType._zod.run(payload, ctx);
};
});
var $ZodNonOptional = $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "values", () => {
const v = def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
});
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
return handleNonOptionalResult(result, inst);
};
});
function handleNonOptionalResult(payload, inst) {
if (!payload.issues.length && payload.value === void 0) payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: payload.value,
inst
});
return payload;
}
var $ZodCatch = $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => {
payload.value = result.value;
if (result.issues.length) {
payload.value = def.catchValue({
...payload,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
payload.issues = [];
}
return payload;
});
payload.value = result.value;
if (result.issues.length) {
payload.value = def.catchValue({
...payload,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
payload.issues = [];
}
return payload;
};
});
var $ZodPipe = $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "values", () => def.in._zod.values);
defineLazy(inst._zod, "optin", () => def.in._zod.optin);
defineLazy(inst._zod, "optout", () => def.out._zod.optout);
defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
const right = def.out._zod.run(payload, ctx);
if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
return handlePipeResult(right, def.in, ctx);
}
const left = def.in._zod.run(payload, ctx);
if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
return handlePipeResult(left, def.out, ctx);
};
});
function handlePipeResult(left, next, ctx) {
if (left.issues.length) {
left.aborted = true;
return left;
}
return next._zod.run({
value: left.value,
issues: left.issues
}, ctx);
}
var $ZodReadonly = $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then(handleReadonlyResult);
return handleReadonlyResult(result);
};
});
function handleReadonlyResult(payload) {
payload.value = Object.freeze(payload.value);
return payload;
}
var $ZodCustom = $constructor("$ZodCustom", (inst, def) => {
$ZodCheck.init(inst, def);
$ZodType.init(inst, def);
inst._zod.parse = (payload, _) => {
return payload;
};
inst._zod.check = (payload) => {
const input = payload.value;
const r = def.fn(input);
if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
handleRefineResult(r, payload, input, inst);
};
});
function handleRefineResult(result, payload, input, inst) {
if (!result) {
const _iss = {
code: "custom",
input,
inst,
path: [...inst._zod.def.path ?? []],
continue: !inst._zod.def.abort
};
if (inst._zod.def.params) _iss.params = inst._zod.def.params;
payload.issues.push(issue(_iss));
}
}
var _a;
var $ZodRegistry = class {
constructor() {
this._map = new WeakMap();
this._idmap = new Map();
}
add(schema, ..._meta) {
const meta = _meta[0];
this._map.set(schema, meta);
if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
return this;
}
clear() {
this._map = new WeakMap();
this._idmap = new Map();
return this;
}
remove(schema) {
const meta = this._map.get(schema);
if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
this._map.delete(schema);
return this;
}
get(schema) {
const p = schema._zod.parent;
if (p) {
const pm = { ...this.get(p) ?? {} };
delete pm.id;
const f = {
...pm,
...this._map.get(schema)
};
return Object.keys(f).length ? f : void 0;
}
return this._map.get(schema);
}
has(schema) {
return this._map.has(schema);
}
};
function registry() {
return new $ZodRegistry();
}
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
var globalRegistry = globalThis.__zod_globalRegistry;
function _string(Class, params) {
return new Class({
type: "string",
...normalizeParams(params)
});
}
function _email(Class, params) {
return new Class({
type: "string",
format: "email",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _guid(Class, params) {
return new Class({
type: "string",
format: "guid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuid(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuidv4(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v4",
...normalizeParams(params)
});
}
function _uuidv6(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v6",
...normalizeParams(params)
});
}
function _uuidv7(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v7",
...normalizeParams(params)
});
}
function _url(Class, params) {
return new Class({
type: "string",
format: "url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _emoji(Class, params) {
return new Class({
type: "string",
format: "emoji",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _nanoid(Class, params) {
return new Class({
type: "string",
format: "nanoid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid(Class, params) {
return new Class({
type: "string",
format: "cuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid2(Class, params) {
return new Class({
type: "string",
format: "cuid2",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ulid(Class, params) {
return new Class({
type: "string",
format: "ulid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _xid(Class, params) {
return new Class({
type: "string",
format: "xid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ksuid(Class, params) {
return new Class({
type: "string",
format: "ksuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv4(Class, params) {
return new Class({
type: "string",
format: "ipv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv6(Class, params) {
return new Class({
type: "string",
format: "ipv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv4(Class, params) {
return new Class({
type: "string",
format: "cidrv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv6(Class, params) {
return new Class({
type: "string",
format: "cidrv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64(Class, params) {
return new Class({
type: "string",
format: "base64",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64url(Class, params) {
return new Class({
type: "string",
format: "base64url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _e164(Class, params) {
return new Class({
type: "string",
format: "e164",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _jwt(Class, params) {
return new Class({
type: "string",
format: "jwt",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _isoDateTime(Class, params) {
return new Class({
type: "string",
format: "datetime",
check: "string_format",
offset: false,
local: false,
precision: null,
...normalizeParams(params)
});
}
function _isoDate(Class, params) {
return new Class({
type: "string",
format: "date",
check: "string_format",
...normalizeParams(params)
});
}
function _isoTime(Class, params) {
return new Class({
type: "string",
format: "time",
check: "string_format",
precision: null,
...normalizeParams(params)
});
}
function _isoDuration(Class, params) {
return new Class({
type: "string",
format: "duration",
check: "string_format",
...normalizeParams(params)
});
}
function _number(Class, params) {
return new Class({
type: "number",
checks: [],
...normalizeParams(params)
});
}
function _int(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "safeint",
...normalizeParams(params)
});
}
function _boolean(Class, params) {
return new Class({
type: "boolean",
...normalizeParams(params)
});
}
function _unknown(Class) {
return new Class({ type: "unknown" });
}
function _never(Class, params) {
return new Class({
type: "never",
...normalizeParams(params)
});
}
function _lt(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _lte(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _gt(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _gte(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _multipleOf(value, params) {
return new $ZodCheckMultipleOf({
check: "multiple_of",
...normalizeParams(params),
value
});
}
function _maxLength(maximum, params) {
return new $ZodCheckMaxLength({
check: "max_length",
...normalizeParams(params),
maximum
});
}
function _minLength(minimum, params) {
return new $ZodCheckMinLength({
check: "min_length",
...normalizeParams(params),
minimum
});
}
function _length(length, params) {
return new $ZodCheckLengthEquals({
check: "length_equals",
...normalizeParams(params),
length
});
}
function _regex(pattern, params) {
return new $ZodCheckRegex({
check: "string_format",
format: "regex",
...normalizeParams(params),
pattern
});
}
function _lowercase(params) {
return new $ZodCheckLowerCase({
check: "string_format",
format: "lowercase",
...normalizeParams(params)
});
}
function _uppercase(params) {
return new $ZodCheckUpperCase({
check: "string_format",
format: "uppercase",
...normalizeParams(params)
});
}
function _includes(includes, params) {
return new $ZodCheckIncludes({
check: "string_format",
format: "includes",
...normalizeParams(params),
includes
});
}
function _startsWith(prefix, params) {
return new $ZodCheckStartsWith({
check: "string_format",
format: "starts_with",
...normalizeParams(params),
prefix
});
}
function _endsWith(suffix, params) {
return new $ZodCheckEndsWith({
check: "string_format",
format: "ends_with",
...normalizeParams(params),
suffix
});
}
function _overwrite(tx) {
return new $ZodCheckOverwrite({
check: "overwrite",
tx
});
}
function _normalize(form) {
return _overwrite((input) => input.normalize(form));
}
function _trim() {
return _overwrite((input) => input.trim());
}
function _toLowerCase() {
return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
return _overwrite((input) => input.toUpperCase());
}
function _slugify() {
return _overwrite((input) => slugify(input));
}
function _array(Class, element, params) {
return new Class({
type: "array",
element,
...normalizeParams(params)
});
}
function _refine(Class, fn, _params) {
return new Class({
type: "custom",
check: "custom",
fn,
...normalizeParams(_params)
});
}
function _superRefine(fn) {
const ch = _check((payload) => {
payload.addIssue = (issue$2) => {
if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
else {
const _issue = issue$2;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
}
};
return fn(payload.value, payload);
});
return ch;
}
function _check(fn, params) {
const ch = new $ZodCheck({
check: "custom",
...normalizeParams(params)
});
ch._zod.check = fn;
return ch;
}
function initializeContext(params) {
let target = params?.target ?? "draft-2020-12";
if (target === "draft-4") target = "draft-04";
if (target === "draft-7") target = "draft-07";
return {
processors: params.processors ?? {},
metadataRegistry: params?.metadata ?? globalRegistry,
target,
unrepresentable: params?.unrepresentable ?? "throw",
override: params?.override ?? (() => {}),
io: params?.io ?? "output",
counter: 0,
seen: new Map(),
cycles: params?.cycles ?? "ref",
reused: params?.reused ?? "inline",
external: params?.external ?? void 0
};
}
function process$1(schema, ctx, _params = {
path: [],
schemaPath: []
}) {
var _a;
const def = schema._zod.def;
const seen = ctx.seen.get(schema);
if (seen) {
seen.count++;
if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
return seen.schema;
}
const result = {
schema: {},
count: 1,
cycle: void 0,
path: _params.path
};
ctx.seen.set(schema, result);
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) result.schema = overrideSchema;
else {
const params = {
..._params,
schemaPath: [..._params.schemaPath, schema],
path: _params.path
};
if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
else {
const _json = result.schema;
const processor = ctx.processors[def.type];
if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
processor(schema, ctx, _json, params);
}
const parent = schema._zod.parent;
if (parent) {
if (!result.ref) result.ref = parent;
process$1(parent, ctx, params);
ctx.seen.get(parent).isParent = true;
}
}
const meta = ctx.metadataRegistry.get(schema);
if (meta) Object.assign(result.schema, meta);
if (ctx.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
}
if (ctx.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
return ctx.seen.get(schema).schema;
}
function extractDefs(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
const idToSchema = new Map();
for (const entry of ctx.seen.entries()) {
const id = ctx.metadataRegistry.get(entry[0])?.id;
if (id) {
const existing = idToSchema.get(id);
if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
idToSchema.set(id, entry[0]);
}
}
const makeURI = (entry) => {
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
if (ctx.external) {
const externalId = ctx.external.registry.get(entry[0])?.id;
const uriGenerator = ctx.external.uri ?? ((id) => id);
if (externalId) return { ref: uriGenerator(externalId) };
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
entry[1].defId = id;
return {
defId: id,
ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
};
}
if (entry[1] === root) return { ref: "#" };
const defUriPrefix = `#/${defsSegment}/`;
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
return {
defId,
ref: defUriPrefix + defId
};
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) return;
const seen = entry[1];
const { ref, defId } = makeURI(entry);
seen.def = { ...seen.schema };
if (defId) seen.defId = defId;
const schema = seen.schema;
for (const key in schema) delete schema[key];
schema.$ref = ref;
};
if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
}
for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (schema === entry[0]) {
extractToDef(entry);
continue;
}
if (ctx.external) {
const ext = ctx.external.registry.get(entry[0])?.id;
if (schema !== entry[0] && ext) {
extractToDef(entry);
continue;
}
}
if (ctx.metadataRegistry.get(entry[0])?.id) {
extractToDef(entry);
continue;
}
if (seen.cycle) {
extractToDef(entry);
continue;
}
if (seen.count > 1) {
if (ctx.reused === "ref") {
extractToDef(entry);
continue;
}
}
}
}
function finalize(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
const flattenRef = (zodSchema) => {
const seen = ctx.seen.get(zodSchema);
if (seen.ref === null) return;
const schema = seen.def ?? seen.schema;
const _cached = { ...schema };
const ref = seen.ref;
seen.ref = null;
if (ref) {
flattenRef(ref);
const refSeen = ctx.seen.get(ref);
const refSchema = refSeen.schema;
if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
} else Object.assign(schema, refSchema);
Object.assign(schema, _cached);
if (zodSchema._zod.parent === ref) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (!(key in _cached)) delete schema[key];
}
if (refSchema.$ref && refSeen.def) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
}
}
const parent = zodSchema._zod.parent;
if (parent && parent !== ref) {
flattenRef(parent);
const parentSeen = ctx.seen.get(parent);
if (parentSeen?.schema.$ref) {
schema.$ref = parentSeen.schema.$ref;
if (parentSeen.def) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
}
}
}
ctx.override({
zodSchema,
jsonSchema: schema,
path: seen.path ?? []
});
};
for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
const result = {};
if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
else if (ctx.target === "openapi-3.0") {}
if (ctx.external?.uri) {
const id = ctx.external.registry.get(schema)?.id;
if (!id) throw new Error("Schema is missing an `id` property");
result.$id = ctx.external.uri(id);
}
Object.assign(result, root.def ?? root.schema);
const defs = ctx.external?.defs ?? {};
for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) defs[seen.defId] = seen.def;
}
if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
else result.definitions = defs;
try {
const finalized = JSON.parse(JSON.stringify(result));
Object.defineProperty(finalized, "~standard", {
value: {
...schema["~standard"],
jsonSchema: {
input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
}
},
enumerable: false,
writable: false
});
return finalized;
} catch (_err) {
throw new Error("Error converting schema to JSON.");
}
}
function isTransforming(_schema, _ctx) {
const ctx = _ctx ?? { seen: new Set() };
if (ctx.seen.has(_schema)) return false;
ctx.seen.add(_schema);
const def = _schema._zod.def;
if (def.type === "transform") return true;
if (def.type === "array") return isTransforming(def.element, ctx);
if (def.type === "set") return isTransforming(def.valueType, ctx);
if (def.type === "lazy") return isTransforming(def.getter(), ctx);
if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
if (def.type === "pipe") return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
if (def.type === "object") {
for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
return false;
}
if (def.type === "union") {
for (const option of def.options) if (isTransforming(option, ctx)) return true;
return false;
}
if (def.type === "tuple") {
for (const item of def.items) if (isTransforming(item, ctx)) return true;
if (def.rest && isTransforming(def.rest, ctx)) return true;
return false;
}
return false;
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
const ctx = initializeContext({
...params,
processors
});
process$1(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
const { libraryOptions, target } = params ?? {};
const ctx = initializeContext({
...libraryOptions ?? {},
target,
io,
processors
});
process$1(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
var formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: ""
};
var stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
if (typeof minimum === "number") json.minLength = minimum;
if (typeof maximum === "number") json.maxLength = maximum;
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "") delete json.format;
if (format === "time") delete json.format;
}
if (contentEncoding) json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const regexes = [...patterns];
if (regexes.length === 1) json.pattern = regexes[0].source;
else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
pattern: regex.source
}))];
}
};
var numberProcessor = (schema, ctx, _json, _params) => {
const json = _json;
const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
if (typeof format === "string" && format.includes("int")) json.type = "integer";
else json.type = "number";
if (typeof exclusiveMinimum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
} else json.exclusiveMinimum = exclusiveMinimum;
if (typeof minimum === "number") {
json.minimum = minimum;
if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") if (exclusiveMinimum >= minimum) delete json.minimum;
else delete json.exclusiveMinimum;
}
if (typeof exclusiveMaximum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
} else json.exclusiveMaximum = exclusiveMaximum;
if (typeof maximum === "number") {
json.maximum = maximum;
if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") if (exclusiveMaximum <= maximum) delete json.maximum;
else delete json.exclusiveMaximum;
}
if (typeof multipleOf === "number") json.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
var neverProcessor = (_schema, _ctx, json, _params) => {
json.not = {};
};
var unknownProcessor = (_schema, _ctx, _json, _params) => {};
var enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
if (values.every((v) => typeof v === "number")) json.type = "number";
if (values.every((v) => typeof v === "string")) json.type = "string";
json.enum = values;
};
var customProcessor = (_schema, ctx, _json, _params) => {
if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
};
var transformProcessor = (_schema, ctx, _json, _params) => {
if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
};
var arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const { minimum, maximum } = schema._zod.bag;
if (typeof minimum === "number") json.minItems = minimum;
if (typeof maximum === "number") json.maxItems = maximum;
json.type = "array";
json.items = process$1(def.element, ctx, {
...params,
path: [...params.path, "items"]
});
};
var objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
json.type = "object";
json.properties = {};
const shape = def.shape;
for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
...params,
path: [
...params.path,
"properties",
key
]
});
const allKeys = new Set(Object.keys(shape));
const requiredKeys = new Set([...allKeys].filter((key) => {
const v = def.shape[key]._zod;
if (ctx.io === "input") return v.optin === void 0;
else return v.optout === void 0;
}));
if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
else if (!def.catchall) {
if (ctx.io === "output") json.additionalProperties = false;
} else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
};
var unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const isExclusive = def.inclusive === false;
const options = def.options.map((x, i) => process$1(x, ctx, {
...params,
path: [
...params.path,
isExclusive ? "oneOf" : "anyOf",
i
]
}));
if (isExclusive) json.oneOf = options;
else json.anyOf = options;
};
var intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const a = process$1(def.left, ctx, {
...params,
path: [
...params.path,
"allOf",
0
]
});
const b = process$1(def.right, ctx, {
...params,
path: [
...params.path,
"allOf",
1
]
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
};
var nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const inner = process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
json.nullable = true;
} else json.anyOf = [inner, { type: "null" }];
};
var nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
var defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(void 0);
} catch {
throw new Error("Dynamic catch values are not supported in JSON Schema");
}
json.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
process$1(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
};
var optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
process$1(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
var ZodISODateTime = $constructor("ZodISODateTime", (inst, def) => {
$ZodISODateTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function datetime(params) {
return _isoDateTime(ZodISODateTime, params);
}
var ZodISODate = $constructor("ZodISODate", (inst, def) => {
$ZodISODate.init(inst, def);
ZodStringFormat.init(inst, def);
});
function date(params) {
return _isoDate(ZodISODate, params);
}
var ZodISOTime = $constructor("ZodISOTime", (inst, def) => {
$ZodISOTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function time(params) {
return _isoTime(ZodISOTime, params);
}
var ZodISODuration = $constructor("ZodISODuration", (inst, def) => {
$ZodISODuration.init(inst, def);
ZodStringFormat.init(inst, def);
});
function duration(params) {
return _isoDuration(ZodISODuration, params);
}
var initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
Object.defineProperties(inst, {
format: { value: (mapper) => formatError(inst, mapper) },
flatten: { value: (mapper) => flattenError(inst, mapper) },
addIssue: { value: (issue) => {
inst.issues.push(issue);
inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
} },
addIssues: { value: (issues) => {
inst.issues.push(...issues);
inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
} },
isEmpty: { get() {
return inst.issues.length === 0;
} }
});
};
$constructor("ZodError", initializer);
var ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
var parse = _parse(ZodRealError);
var parseAsync = _parseAsync(ZodRealError);
var safeParse = _safeParse(ZodRealError);
var safeParseAsync = _safeParseAsync(ZodRealError);
var encode$1 = _encode$1(ZodRealError);
var decode$1 = _decode$1(ZodRealError);
var encodeAsync = _encodeAsync(ZodRealError);
var decodeAsync = _decodeAsync(ZodRealError);
var safeEncode = _safeEncode(ZodRealError);
var safeDecode = _safeDecode(ZodRealError);
var safeEncodeAsync = _safeEncodeAsync(ZodRealError);
var safeDecodeAsync = _safeDecodeAsync(ZodRealError);
var ZodType = $constructor("ZodType", (inst, def) => {
$ZodType.init(inst, def);
Object.assign(inst["~standard"], { jsonSchema: {
input: createStandardJSONSchemaMethod(inst, "input"),
output: createStandardJSONSchemaMethod(inst, "output")
} });
inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
inst.def = def;
inst.type = def.type;
Object.defineProperty(inst, "_def", { value: def });
inst.check = (...checks) => {
return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
check: ch,
def: { check: "custom" },
onattach: []
} } : ch)] }), { parent: true });
};
inst.with = inst.check;
inst.clone = (def, params) => clone(inst, def, params);
inst.brand = () => inst;
inst.register = ((reg, meta) => {
reg.add(inst, meta);
return inst;
});
inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
inst.spa = inst.safeParseAsync;
inst.encode = (data, params) => encode$1(inst, data, params);
inst.decode = (data, params) => decode$1(inst, data, params);
inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
inst.safeEncode = (data, params) => safeEncode(inst, data, params);
inst.safeDecode = (data, params) => safeDecode(inst, data, params);
inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
inst.refine = (check, params) => inst.check(refine(check, params));
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
inst.overwrite = (fn) => inst.check( _overwrite(fn));
inst.optional = () => optional(inst);
inst.exactOptional = () => exactOptional(inst);
inst.nullable = () => nullable(inst);
inst.nullish = () => optional(nullable(inst));
inst.nonoptional = (params) => nonoptional(inst, params);
inst.array = () => array(inst);
inst.or = (arg) => union([inst, arg]);
inst.and = (arg) => intersection(inst, arg);
inst.transform = (tx) => pipe(inst, transform(tx));
inst.default = (def) => _default(inst, def);
inst.prefault = (def) => prefault(inst, def);
inst.catch = (params) => _catch(inst, params);
inst.pipe = (target) => pipe(inst, target);
inst.readonly = () => readonly(inst);
inst.describe = (description) => {
const cl = inst.clone();
globalRegistry.add(cl, { description });
return cl;
};
Object.defineProperty(inst, "description", {
get() {
return globalRegistry.get(inst)?.description;
},
configurable: true
});
inst.meta = (...args) => {
if (args.length === 0) return globalRegistry.get(inst);
const cl = inst.clone();
globalRegistry.add(cl, args[0]);
return cl;
};
inst.isOptional = () => inst.safeParse(void 0).success;
inst.isNullable = () => inst.safeParse(null).success;
inst.apply = (fn) => fn(inst);
return inst;
});
var _ZodString = $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
const bag = inst._zod.bag;
inst.format = bag.format ?? null;
inst.minLength = bag.minimum ?? null;
inst.maxLength = bag.maximum ?? null;
inst.regex = (...args) => inst.check( _regex(...args));
inst.includes = (...args) => inst.check( _includes(...args));
inst.startsWith = (...args) => inst.check( _startsWith(...args));
inst.endsWith = (...args) => inst.check( _endsWith(...args));
inst.min = (...args) => inst.check( _minLength(...args));
inst.max = (...args) => inst.check( _maxLength(...args));
inst.length = (...args) => inst.check( _length(...args));
inst.nonempty = (...args) => inst.check( _minLength(1, ...args));
inst.lowercase = (params) => inst.check( _lowercase(params));
inst.uppercase = (params) => inst.check( _uppercase(params));
inst.trim = () => inst.check( _trim());
inst.normalize = (...args) => inst.check( _normalize(...args));
inst.toLowerCase = () => inst.check( _toLowerCase());
inst.toUpperCase = () => inst.check( _toUpperCase());
inst.slugify = () => inst.check( _slugify());
});
var ZodString = $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
inst.email = (params) => inst.check( _email(ZodEmail, params));
inst.url = (params) => inst.check( _url(ZodURL, params));
inst.jwt = (params) => inst.check( _jwt(ZodJWT, params));
inst.emoji = (params) => inst.check( _emoji(ZodEmoji, params));
inst.guid = (params) => inst.check( _guid(ZodGUID, params));
inst.uuid = (params) => inst.check( _uuid(ZodUUID, params));
inst.uuidv4 = (params) => inst.check( _uuidv4(ZodUUID, params));
inst.uuidv6 = (params) => inst.check( _uuidv6(ZodUUID, params));
inst.uuidv7 = (params) => inst.check( _uuidv7(ZodUUID, params));
inst.nanoid = (params) => inst.check( _nanoid(ZodNanoID, params));
inst.guid = (params) => inst.check( _guid(ZodGUID, params));
inst.cuid = (params) => inst.check( _cuid(ZodCUID, params));
inst.cuid2 = (params) => inst.check( _cuid2(ZodCUID2, params));
inst.ulid = (params) => inst.check( _ulid(ZodULID, params));
inst.base64 = (params) => inst.check( _base64(ZodBase64, params));
inst.base64url = (params) => inst.check( _base64url(ZodBase64URL, params));
inst.xid = (params) => inst.check( _xid(ZodXID, params));
inst.ksuid = (params) => inst.check( _ksuid(ZodKSUID, params));
inst.ipv4 = (params) => inst.check( _ipv4(ZodIPv4, params));
inst.ipv6 = (params) => inst.check( _ipv6(ZodIPv6, params));
inst.cidrv4 = (params) => inst.check( _cidrv4(ZodCIDRv4, params));
inst.cidrv6 = (params) => inst.check( _cidrv6(ZodCIDRv6, params));
inst.e164 = (params) => inst.check( _e164(ZodE164, params));
inst.datetime = (params) => inst.check(datetime(params));
inst.date = (params) => inst.check(date(params));
inst.time = (params) => inst.check(time(params));
inst.duration = (params) => inst.check(duration(params));
});
function string(params) {
return _string(ZodString, params);
}
var ZodStringFormat = $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
var ZodEmail = $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodGUID = $constructor("ZodGUID", (inst, def) => {
$ZodGUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodUUID = $constructor("ZodUUID", (inst, def) => {
$ZodUUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodURL = $constructor("ZodURL", (inst, def) => {
$ZodURL.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodEmoji = $constructor("ZodEmoji", (inst, def) => {
$ZodEmoji.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodNanoID = $constructor("ZodNanoID", (inst, def) => {
$ZodNanoID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodCUID = $constructor("ZodCUID", (inst, def) => {
$ZodCUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodCUID2 = $constructor("ZodCUID2", (inst, def) => {
$ZodCUID2.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodULID = $constructor("ZodULID", (inst, def) => {
$ZodULID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodXID = $constructor("ZodXID", (inst, def) => {
$ZodXID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodKSUID = $constructor("ZodKSUID", (inst, def) => {
$ZodKSUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodIPv4 = $constructor("ZodIPv4", (inst, def) => {
$ZodIPv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodIPv6 = $constructor("ZodIPv6", (inst, def) => {
$ZodIPv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodCIDRv4 = $constructor("ZodCIDRv4", (inst, def) => {
$ZodCIDRv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodCIDRv6 = $constructor("ZodCIDRv6", (inst, def) => {
$ZodCIDRv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodBase64 = $constructor("ZodBase64", (inst, def) => {
$ZodBase64.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodBase64URL = $constructor("ZodBase64URL", (inst, def) => {
$ZodBase64URL.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodE164 = $constructor("ZodE164", (inst, def) => {
$ZodE164.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodJWT = $constructor("ZodJWT", (inst, def) => {
$ZodJWT.init(inst, def);
ZodStringFormat.init(inst, def);
});
var ZodNumber = $constructor("ZodNumber", (inst, def) => {
$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
inst.gt = (value, params) => inst.check( _gt(value, params));
inst.gte = (value, params) => inst.check( _gte(value, params));
inst.min = (value, params) => inst.check( _gte(value, params));
inst.lt = (value, params) => inst.check( _lt(value, params));
inst.lte = (value, params) => inst.check( _lte(value, params));
inst.max = (value, params) => inst.check( _lte(value, params));
inst.int = (params) => inst.check(int(params));
inst.safe = (params) => inst.check(int(params));
inst.positive = (params) => inst.check( _gt(0, params));
inst.nonnegative = (params) => inst.check( _gte(0, params));
inst.negative = (params) => inst.check( _lt(0, params));
inst.nonpositive = (params) => inst.check( _lte(0, params));
inst.multipleOf = (value, params) => inst.check( _multipleOf(value, params));
inst.step = (value, params) => inst.check( _multipleOf(value, params));
inst.finite = () => inst;
const bag = inst._zod.bag;
inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
inst.isFinite = true;
inst.format = bag.format ?? null;
});
function number(params) {
return _number(ZodNumber, params);
}
var ZodNumberFormat = $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber.init(inst, def);
});
function int(params) {
return _int(ZodNumberFormat, params);
}
var ZodBoolean = $constructor("ZodBoolean", (inst, def) => {
$ZodBoolean.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
});
function boolean(params) {
return _boolean(ZodBoolean, params);
}
var ZodUnknown = $constructor("ZodUnknown", (inst, def) => {
$ZodUnknown.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
});
function unknown() {
return _unknown(ZodUnknown);
}
var ZodNever = $constructor("ZodNever", (inst, def) => {
$ZodNever.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
});
function never(params) {
return _never(ZodNever, params);
}
var ZodArray = $constructor("ZodArray", (inst, def) => {
$ZodArray.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
inst.min = (minLength, params) => inst.check( _minLength(minLength, params));
inst.nonempty = (params) => inst.check( _minLength(1, params));
inst.max = (maxLength, params) => inst.check( _maxLength(maxLength, params));
inst.length = (len, params) => inst.check( _length(len, params));
inst.unwrap = () => inst.element;
});
function array(element, params) {
return _array(ZodArray, element, params);
}
var ZodObject = $constructor("ZodObject", (inst, def) => {
$ZodObjectJIT.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
defineLazy(inst, "shape", () => {
return def.shape;
});
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
inst.catchall = (catchall) => inst.clone({
...inst._zod.def,
catchall
});
inst.passthrough = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.loose = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.strict = () => inst.clone({
...inst._zod.def,
catchall: never()
});
inst.strip = () => inst.clone({
...inst._zod.def,
catchall: void 0
});
inst.extend = (incoming) => {
return extend(inst, incoming);
};
inst.safeExtend = (incoming) => {
return safeExtend(inst, incoming);
};
inst.merge = (other) => merge(inst, other);
inst.pick = (mask) => pick(inst, mask);
inst.omit = (mask) => omit(inst, mask);
inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
});
function object(shape, params) {
return new ZodObject({
type: "object",
shape: shape ?? {},
...normalizeParams(params)
});
}
var ZodUnion = $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
inst.options = def.options;
});
function union(options, params) {
return new ZodUnion({
type: "union",
options,
...normalizeParams(params)
});
}
var ZodIntersection = $constructor("ZodIntersection", (inst, def) => {
$ZodIntersection.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
});
function intersection(left, right) {
return new ZodIntersection({
type: "intersection",
left,
right
});
}
var ZodEnum = $constructor("ZodEnum", (inst, def) => {
$ZodEnum.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
inst.enum = def.entries;
inst.options = Object.values(def.entries);
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
inst.exclude = (values, params) => {
const newEntries = { ...def.entries };
for (const value of values) if (keys.has(value)) delete newEntries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
});
function _enum(values, params) {
return new ZodEnum({
type: "enum",
entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
...normalizeParams(params)
});
}
var ZodTransform = $constructor("ZodTransform", (inst, def) => {
$ZodTransform.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
inst._zod.parse = (payload, _ctx) => {
if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
payload.addIssue = (issue$1) => {
if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
else {
const _issue = issue$1;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = inst);
payload.issues.push(issue(_issue));
}
};
const output = def.transform(payload.value, payload);
if (output instanceof Promise) return output.then((output) => {
payload.value = output;
return payload;
});
payload.value = output;
return payload;
};
});
function transform(fn) {
return new ZodTransform({
type: "transform",
transform: fn
});
}
var ZodOptional = $constructor("ZodOptional", (inst, def) => {
$ZodOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
return new ZodOptional({
type: "optional",
innerType
});
}
var ZodExactOptional = $constructor("ZodExactOptional", (inst, def) => {
$ZodExactOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
return new ZodExactOptional({
type: "optional",
innerType
});
}
var ZodNullable = $constructor("ZodNullable", (inst, def) => {
$ZodNullable.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
return new ZodNullable({
type: "nullable",
innerType
});
}
var ZodDefault = $constructor("ZodDefault", (inst, def) => {
$ZodDefault.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
return new ZodDefault({
type: "default",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
}
});
}
var ZodPrefault = $constructor("ZodPrefault", (inst, def) => {
$ZodPrefault.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
return new ZodPrefault({
type: "prefault",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
}
});
}
var ZodNonOptional = $constructor("ZodNonOptional", (inst, def) => {
$ZodNonOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
return new ZodNonOptional({
type: "nonoptional",
innerType,
...normalizeParams(params)
});
}
var ZodCatch = $constructor("ZodCatch", (inst, def) => {
$ZodCatch.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
return new ZodCatch({
type: "catch",
innerType,
catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
});
}
var ZodPipe = $constructor("ZodPipe", (inst, def) => {
$ZodPipe.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
inst.in = def.in;
inst.out = def.out;
});
function pipe(in_, out) {
return new ZodPipe({
type: "pipe",
in: in_,
out
});
}
var ZodReadonly = $constructor("ZodReadonly", (inst, def) => {
$ZodReadonly.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
return new ZodReadonly({
type: "readonly",
innerType
});
}
var ZodCustom = $constructor("ZodCustom", (inst, def) => {
$ZodCustom.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
});
function refine(fn, _params = {}) {
return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
return _superRefine(fn);
}
var PositionZod = object({
left: optional(string().or(number())),
top: optional(string().or(number())),
right: optional(string().or(number())),
bottom: optional(string().or(number()))
});
var Main_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
async finish() {
await finish_default();
},
key() {
key_default();
},
onPositionChange(event) {
onChange(event.target);
},
readPosition() {
prompt({
headline: "坐标快捷填入",
description: "请输入从生成坐标处获得的坐标",
closeOnEsc: true,
closeOnOverlayClick: true,
validator: (value) => {
try {
PositionZod.parse(import_dist.default.parse(value).position);
} catch {
snackbar({
message: "格式错误,请检查格式!",
placement: "top"
});
return false;
}
return true;
},
textFieldOptions: {
label: "position对象",
placeholder: "请填入{ position }对象",
rows: 8
},
onConfirm: (value) => {
const position = import_dist.default.parse(value).position;
if (position.left) {
document.querySelector("#left").value = String(position.left);
onChange(document.querySelector("#left"));
} else if (position.right) {
document.querySelector("#right").value = String(position.right);
onChange(document.querySelector("#right"));
}
if (position.top) {
document.querySelector("#top").value = String(position.top);
onChange(document.querySelector("#top"));
} else if (position.bottom) {
document.querySelector("#bottom").value = String(position.bottom);
onChange(document.querySelector("#bottom"));
}
}
});
},
closeDialog() {
send("closePage");
}
},
data() {
return { originRule: import_dist.default.parse(window.Hanashiro.originRule) };
},
async mounted() {
window.Hanashiro.currentCategory = "";
await renderedCategories_default();
document.querySelector("#category").addEventListener("change", (e) => {
window.Hanashiro.currentCategory = e.target.value;
});
document.querySelector("#page").open = true;
}
});
var _plugin_vue_export_helper_default = (sfc, props) => {
const target = sfc.__vccOpts || sfc;
for (const [key, val] of props) target[key] = val;
return target;
};
var _hoisted_1 = ["placeholder"];
function _sfc_render$8(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)("mdui-dialog", {
id: "page",
headline: "配置",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[7] || (_cache[7] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [
_cache[16] || (_cache[16] = (0, vue.createStaticVNode)("选择复制深度:ts层app层groups层rules层
选择分类:
插入action类型:clickCenterbacklongClick
插入限制字段:插入matchTime、resetMatch和actionMaximum
插入matchRoot:插入matchRoot
去除exampleUrls:
", 6)),
(0, vue.createElementVNode)("div", null, [_cache[8] || (_cache[8] = (0, vue.createElementVNode)("span", null, "修改key值为:", -1)), (0, vue.createElementVNode)("mdui-text-field", {
id: "key",
variant: "filled",
type: "number",
label: "key",
placeholder: "填写一个数字",
helper: "rules模式修改ruleKey,其余修改groupKey。请提前选好模式,失焦保存!",
onChange: _cache[0] || (_cache[0] = (...args) => _ctx.key && _ctx.key(...args))
}, null, 32)]),
_cache[17] || (_cache[17] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "修改preKeys值为:"), (0, vue.createElementVNode)("mdui-text-field", {
id: "preKeys",
variant: "filled",
label: "preKeys",
placeholder: "填写多个以英文逗号分隔的数字",
helper: "失焦保存"
})], -1)),
(0, vue.createElementVNode)("div", null, [
_cache[9] || (_cache[9] = (0, vue.createElementVNode)("span", null, "坐标:", -1)),
_cache[10] || (_cache[10] = (0, vue.createElementVNode)("mdui-chip", { variant: "input" }, "左", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
class: "position",
id: "left",
onChange: _cache[1] || (_cache[1] = (...args) => _ctx.onPositionChange && _ctx.onPositionChange(...args))
}, null, 32),
_cache[11] || (_cache[11] = (0, vue.createElementVNode)("mdui-chip", { variant: "input" }, "右", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
class: "position",
id: "right",
onChange: _cache[2] || (_cache[2] = (...args) => _ctx.onPositionChange && _ctx.onPositionChange(...args))
}, null, 32),
_cache[12] || (_cache[12] = (0, vue.createElementVNode)("mdui-chip", { variant: "input" }, "上", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
class: "position",
id: "top",
onChange: _cache[3] || (_cache[3] = (...args) => _ctx.onPositionChange && _ctx.onPositionChange(...args))
}, null, 32),
_cache[13] || (_cache[13] = (0, vue.createElementVNode)("mdui-chip", { variant: "input" }, "下", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
class: "position",
id: "bottom",
onChange: _cache[4] || (_cache[4] = (...args) => _ctx.onPositionChange && _ctx.onPositionChange(...args))
}, null, 32),
(0, vue.createElementVNode)("mdui-button", {
variant: "tonal",
class: "position",
onClick: _cache[5] || (_cache[5] = (...args) => _ctx.readPosition && _ctx.readPosition(...args))
}, "快捷填入"),
_cache[14] || (_cache[14] = (0, vue.createElementVNode)("span", { class: "introduction" }, "快捷填入可将从获取坐标功能中获取的position字段一键填入", -1))
]),
(0, vue.createElementVNode)("div", null, [_cache[15] || (_cache[15] = (0, vue.createElementVNode)("span", null, "规则组名称:", -1)), (0, vue.createElementVNode)("mdui-text-field", {
id: "ruleName",
variant: "filled",
label: "名称",
placeholder: _ctx.originRule.groups[0].name
}, null, 8, _hoisted_1)]),
_cache[18] || (_cache[18] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "规则组描述:"), (0, vue.createElementVNode)("mdui-text-field", {
id: "ruleDesc",
variant: "filled",
label: "描述",
placeholder: "没有描述不填"
})], -1)),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[6] || (_cache[6] = (...args) => _ctx.finish && _ctx.finish(...args))
}, "确定")])
], 32);
}
var Main_default = _plugin_vue_export_helper_default(Main_vue_vue_type_script_lang_default, [["render", _sfc_render$8]]);
var RawCategoryZod = object({
key: number().int(),
name: string(),
enable: boolean().optional()
});
var settings_default = async () => {
const categories = document.querySelector("#categories").value;
const rulesKeySort = document.querySelector("#rulesKeySort").value;
const maxShowSize = document.querySelector("#maxShowSize").value;
const isHideLoadSnackbar = document.querySelector("#hideLoadSnackbar").checked;
const isSimplyName = document.querySelector("#simplyName").checked;
const isAutoAddSelector = document.querySelector("#autoAddSelector").checked;
const isActivityIdsSimply = document.querySelector("#activityIdsSimply").checked;
const isReadClipboard = document.querySelector("#readClipboard").checked;
const inspectSettings = await getInspectSettings();
let isCategoriesLegal = true;
try {
import_dist.default.parse(categories ? categories : "[]").forEach((category) => {
RawCategoryZod.parse(category);
});
} catch {
isCategoriesLegal = false;
snackbar({
message: "分类格式错误!分类设置已跳过!",
placement: "top"
});
}
if (isCategoriesLegal) await setHanashiroSettings("categories", import_dist.default.parse(categories ? categories : "[]"));
await setHanashiroSettings("rulesKeySort", import_dist.default.parse(rulesKeySort ? rulesKeySort : "[]"));
await setHanashiroSettings("hideLoadSnackbar", isHideLoadSnackbar);
await setHanashiroSettings("simplyName", isSimplyName);
await setHanashiroSettings("autoAddSelector", isAutoAddSelector);
await setHanashiroSettings("activityIdsSimply", isActivityIdsSimply);
await setHanashiroSettings("readClipboard", isReadClipboard);
inspectSettings.maxShowNodeSize = Number(maxShowSize);
await setInspectSettings(inspectSettings);
send("closePage");
};
var setValue$1 = async (settings) => {
try {
let isCategoriesLegal = true;
try {
settings.categories.forEach((category) => RawCategoryZod.parse(category));
} catch {
isCategoriesLegal = false;
snackbar({
message: "分类格式错误,已跳过分类设置!",
placement: "top"
});
}
await setHanashiroSettings("activityIdsSimply", settings.activityIdsSimply);
await setHanashiroSettings("autoAddSelector", settings.autoAddSelector);
if (isCategoriesLegal) await setHanashiroSettings("categories", settings.categories);
await setHanashiroSettings("hideLoadSnackbar", settings.hideLoadSnackbar);
await setHanashiroSettings("rulesKeySort", settings.rulesKeySort);
await setHanashiroSettings("simplyName", settings.simplyName);
await setHanashiroSettings("readClipboard", settings.readClipboard);
} catch {
snackbar({
message: "应用设置失败",
placement: "top"
});
return;
}
};
var getRemoteSettings = async (url) => {
let remoteSettings;
try {
remoteSettings = import_dist.default.parse(await (await fetch(url)).text());
} catch {
snackbar({
message: "请求失败!",
placement: "top"
});
return;
}
await setValue$1(remoteSettings);
snackbar({
message: "设置应用成功!重新打开页面即可看见更改",
placement: "top"
});
};
var showFilePicker$1 = () => document.querySelector("input#localImport").click();
var getLocalSettings = async () => {
const fileList = document.querySelector("input#localImport").files;
if (!fileList) return;
const file = fileList[0];
await setValue$1(import_dist.default.parse(await file.text()));
snackbar({
message: "设置应用成功!重新打开页面即可看见更改",
placement: "top"
});
};
var import_default$1 = () => {
dialog({
headline: "选择导入渠道",
description: "选择从本地导入或者远程导入",
closeOnEsc: true,
closeOnOverlayClick: true,
actions: [{
text: "本地导入",
onClick: showFilePicker$1
}, {
text: "远程导入",
onClick: () => {
prompt({
headline: "远程设置文件链接",
description: "请输入远程设置文件的链接以导入",
closeOnEsc: true,
closeOnOverlayClick: true,
confirmText: "导入",
cancelText: "取消",
onConfirm: async (value) => {
if (!value) {
snackbar({
message: "请输入链接!",
placement: "top"
});
return new Promise((_, reject) => reject(false));
} else await getRemoteSettings(value);
}
});
}
}]
});
};
var export_default$1 = async () => {
const activityIdsSimply = await getHanashiroSettings("activityIdsSimply");
const autoAddSelector = await getHanashiroSettings("autoAddSelector");
const categories = await getHanashiroSettings("categories");
const hideLoadSnackbar = await getHanashiroSettings("hideLoadSnackbar");
const rulesKeySort = await getHanashiroSettings("rulesKeySort");
const simplyName = await getHanashiroSettings("simplyName");
const readClipboard = await getHanashiroSettings("readClipboard");
const settings = {
activityIdsSimply: activityIdsSimply ? activityIdsSimply : false,
autoAddSelector: autoAddSelector ? autoAddSelector : false,
categories: categories ? categories : [],
hideLoadSnackbar: hideLoadSnackbar ? hideLoadSnackbar : false,
rulesKeySort,
simplyName: simplyName ? simplyName : false,
readClipboard: readClipboard ? readClipboard : false
};
(0, import_FileSaver_min.saveAs)(new Blob([JSON.stringify(settings, void 0, 2)]), "settings.json5");
};
var Settings_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
settings() {
settings_default();
},
async exportSettings() {
await export_default$1();
},
importSettings() {
import_default$1();
},
async getLocalSettingsFile() {
await getLocalSettings();
},
closeDialog() {
send("closePage");
}
},
async mounted() {
if (await getHanashiroSettings("categories")) document.querySelector("#categories").value = import_dist.default.stringify(await getHanashiroSettings("categories"));
if (await getHanashiroSettings("rulesKeySort")) document.querySelector("#rulesKeySort").value = import_dist.default.stringify(await getHanashiroSettings("rulesKeySort"));
if (await getInspectSettings()) document.querySelector("#maxShowSize").value = String((await getInspectSettings()).maxShowNodeSize);
if (await getHanashiroSettings("hideLoadSnackbar") == true) document.querySelector("#hideLoadSnackbar").checked = true;
if (await getHanashiroSettings("simplyName") == true) document.querySelector("#simplyName").checked = true;
if (await getHanashiroSettings("activityIdsSimply") == true) document.querySelector("#activityIdsSimply").checked = true;
if (await getHanashiroSettings("readClipboard") == true) document.querySelector("#readClipboard").checked = true;
document.querySelector("#page").open = true;
}
});
function _sfc_render$7(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)(vue.Fragment, null, [(0, vue.createElementVNode)("mdui-dialog", {
id: "page",
headline: "设置",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[3] || (_cache[3] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
variant: "tonal",
onClick: _cache[0] || (_cache[0] = (...args) => _ctx.exportSettings && _ctx.exportSettings(...args))
}, "导出"), (0, vue.createElementVNode)("mdui-button", {
variant: "tonal",
onClick: _cache[1] || (_cache[1] = (...args) => _ctx.importSettings && _ctx.importSettings(...args))
}, "导入")]),
_cache[5] || (_cache[5] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "分类设置:"), (0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "categories",
label: "分类",
placeholder: "填入合法的分类",
rows: "10"
})], -1)),
_cache[6] || (_cache[6] = (0, vue.createElementVNode)("div", null, [
(0, vue.createElementVNode)("span", null, "字段排序设置:"),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "rulesKeySort",
label: "字段排序",
placeholder: "目前仅支持rules内字段",
rows: "10"
}),
(0, vue.createElementVNode)("span", { class: "introduction" }, " 接受一个字符串数组,目前支持的字段有: key,preKeys,fastQuery,matchTime,actionMaximum,resetMatch,priorityTime matchRoot,action,activityIds,position,matches,exampleUrls,snapshotUrls ")
], -1)),
_cache[7] || (_cache[7] = (0, vue.createElementVNode)("div", null, [
(0, vue.createElementVNode)("span", null, "节点阈值:"),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "maxShowSize",
type: "number",
label: "节点阈值",
placeholder: "填入数字"
}),
(0, vue.createElementVNode)("span", { class: "introduction" }, "最大节点展示数量,超出的节点将被丢弃")
], -1)),
_cache[8] || (_cache[8] = (0, vue.createStaticVNode)("隐藏加载成功提示:每次脚本加载时会弹出一个snackbar,此选项可选择是否弹出
name属性复制优化:在复制name属性时,会自动优化复制的内容。如复制 android.widget.TextView 时会优化为 TextView
选择器分享自动添加快捷搜索:在分享选择器时,自动添加到快捷搜索列表中
activityIds规则复制优化:在复制规则代码时,若activityIds满足简写条件时,使用简写
自动读取剪贴板:当进入网页审查工具首页时,自动读取剪贴板。如果存在以.zip结尾的链接时,自动粘贴以唤起快捷导入窗口。火狐内核不可用。
", 5)),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[2] || (_cache[2] = (...args) => _ctx.settings && _ctx.settings(...args))
}, "确定")])
], 32), (0, vue.createElementVNode)("input", {
type: "file",
id: "localImport",
accept: ".json,.json5",
onChange: _cache[4] || (_cache[4] = (...args) => _ctx.getLocalSettingsFile && _ctx.getLocalSettingsFile(...args))
}, null, 32)], 64);
}
var Settings_default = _plugin_vue_export_helper_default(Settings_vue_vue_type_script_lang_default, [["render", _sfc_render$7]]);
var Help_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: { closeDialog() {
send("closePage");
} },
mounted() {
document.querySelector("#page").open = true;
}
});
function _sfc_render$6(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)("mdui-dialog", {
id: "page",
headline: "帮助",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[0] || (_cache[0] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [..._cache[1] || (_cache[1] = [(0, vue.createStaticVNode)("", 1)])], 32);
}
var Help_default = _plugin_vue_export_helper_default(Help_vue_vue_type_script_lang_default, [["render", _sfc_render$6]]);
var generateSelectors$1 = async () => {
const selectors = await getHanashiroSettings("selectors");
const selectorsGroup = document.querySelector("#selectors");
let innerHtmlString = "";
selectors.forEach(({ name, base64 }, index) => {
innerHtmlString += `${name}`;
});
selectorsGroup.innerHTML = innerHtmlString;
document.querySelectorAll("#selector").forEach((radio) => {
radio.addEventListener("click", (e) => {
window.Hanashiro.currentUseSelectorIndex = Number(e.target.getAttribute("data-index"));
});
});
};
var search = async () => {
const selectors = await getHanashiroSettings("selectors");
const target = new URL(window.location.href);
target.searchParams.set("gkd", selectors[window.Hanashiro.currentUseSelectorIndex].base64);
window.location.href = target.toString();
};
var UseSelector_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
async search() {
await search();
},
closeDialog() {
send("closePage");
}
},
async mounted() {
await generateSelectors$1();
document.querySelector("#page").open = true;
}
});
function _sfc_render$5(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)("mdui-dialog", {
id: "page",
headline: "使用选择器",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[1] || (_cache[1] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [_cache[2] || (_cache[2] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "选择选择器:"), (0, vue.createElementVNode)("mdui-radio-group", { id: "selectors" })], -1)), (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[0] || (_cache[0] = (...args) => _ctx.search && _ctx.search(...args))
}, "搜索")])], 32);
}
var UseSelector_default = _plugin_vue_export_helper_default(UseSelector_vue_vue_type_script_lang_default, [["render", _sfc_render$5]]);
var _hasBuffer = typeof Buffer === "function";
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
var b64chs = Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=");
var b64tab = ((a) => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
var _fromCC = String.fromCharCode.bind(String);
var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_");
var _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, "");
var btoaPolyfill = (bin) => {
let u32, c0, c1, c2, asc = "";
const pad = bin.length % 3;
for (let i = 0; i < bin.length;) {
if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255) throw new TypeError("invalid character found");
u32 = c0 << 16 | c1 << 8 | c2;
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
var _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
const maxargs = 4096;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
return _btoa(strs.join(""));
};
var cb_utob = (c) => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
} else {
var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320);
return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = (u) => u.replace(re_utob, cb_utob);
var _encode = _hasBuffer ? (s) => Buffer.from(s, "utf8").toString("base64") : _TE ? (s) => _fromUint8Array(_TE.encode(s)) : (s) => _btoa(utob(s));
var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
var encodeURI = (src) => encode(src, true);
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var offset = ((7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3)) - 65536;
return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320);
case 3: return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
default: return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
}
};
var btou = (b) => b.replace(re_btou, cb_btou);
var atobPolyfill = (asc) => {
asc = asc.replace(/\s+/g, "");
if (!b64re.test(asc)) throw new TypeError("malformed base64.");
asc += "==".slice(2 - (asc.length & 3));
let u24, r1, r2;
let binArray = [];
for (let i = 0; i < asc.length;) {
u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
if (r1 === 64) binArray.push(_fromCC(u24 >> 16 & 255));
else if (r2 === 64) binArray.push(_fromCC(u24 >> 16 & 255, u24 >> 8 & 255));
else binArray.push(_fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255));
}
return binArray.join("");
};
var _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
var _toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0)));
var _decode = _hasBuffer ? (a) => Buffer.from(a, "base64").toString("utf8") : _TD ? (a) => _TD.decode(_toUint8Array(a)) : (a) => btou(_atob(a));
var _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/"));
var decode = (src) => _decode(_unURI(src));
var AddSelector_default = (0, vue.defineComponent)({ mounted() {
prompt({
headline: "请输入选择器备注",
description: "对该选择器的备注,方便辨认",
confirmText: "就决定是你了!",
cancelText: "算了",
closeOnEsc: true,
closeOnOverlayClick: true,
onConfirm: (name) => {
if (!name) {
snackbar({
message: "请不要留空哦~",
placement: "top"
});
return false;
} else prompt({
headline: "请输入选择器",
description: "输入选择器",
confirmText: "好了~",
cancelText: "算了",
closeOnEsc: true,
closeOnOverlayClick: true,
onConfirm: async (selector) => {
if (!selector) {
snackbar({
message: "请不要留空哦~",
placement: "top"
});
return new Promise((_, reject) => reject(false));
} else {
const savedSelectors = await getHanashiroSettings("selectors");
savedSelectors.push({
name,
base64: encodeURI(selector),
order: 1
});
savedSelectors.sort((a, b) => {
if (a.order > b.order) return -1;
else if (a.order == b.order) return 0;
else return 1;
});
await setHanashiroSettings("selectors", savedSelectors);
send("closePage");
}
},
onCancel: () => send("closePage")
}).catch();
},
onCancel: () => send("closePage")
}).catch();
} });
var generateSelectors = async () => {
const selectors = await getHanashiroSettings("selectors");
const selectorsGroup = document.querySelector("#selectors");
let innerHtmlString = "";
selectors.sort((a, b) => {
if (a.order > b.order) return -1;
else if (a.order == b.order) return 0;
else return 1;
});
selectors.forEach(({ name, base64, order }, index) => {
innerHtmlString += `${name}`;
});
selectorsGroup.innerHTML = innerHtmlString;
document.querySelectorAll("#selectorRadio").forEach((radio) => {
radio.addEventListener("click", (e) => {
const nameTextField = document.querySelector("#name");
const selectorTextField = document.querySelector("#selector");
const orderTextField = document.querySelector("#order");
nameTextField.value = e.target.innerText;
selectorTextField.value = decode(e.target.value);
orderTextField.value = e.target.getAttribute("data-order");
window.Hanashiro.currentSelector = {
index: Number(e.target.getAttribute("data-index")),
name: e.target.innerText,
base64: e.target.value
};
});
});
};
var editSelector = async () => {
const selectors = await getHanashiroSettings("selectors");
const nameTextField = document.querySelector("#name");
const selectorTextField = document.querySelector("#selector");
const orderTextField = document.querySelector("#order");
if (selectorTextField.value) selectors[window.Hanashiro.currentSelector.index] = {
name: nameTextField.value,
base64: encodeURI(selectorTextField.value),
order: Number(orderTextField.value == "" ? 1 : orderTextField.value)
};
else selectors.splice(window.Hanashiro.currentSelector.index, 1);
await setHanashiroSettings("selectors", selectors);
snackbar({
message: "修改成功!",
placement: "top"
});
};
var setValue = async (selectors) => {
try {
if (window.Hanashiro.selectorsImportWay == 0) await setHanashiroSettings("selectors", selectors);
else await setHanashiroSettings("selectors", (await getHanashiroSettings("selectors")).concat(selectors));
} catch {
snackbar({
message: "应用设置失败",
placement: "top"
});
return;
}
};
var getRemoteSelectors = async (url) => {
let remoteSelectors;
try {
remoteSelectors = import_dist.default.parse(await (await fetch(url)).text());
} catch {
snackbar({
message: "请求失败!",
placement: "top"
});
return;
}
await setValue(remoteSelectors);
snackbar({
message: "设置应用成功!重新打开页面即可看见更改",
placement: "top"
});
};
var showFilePicker = () => document.querySelector("input#localImport").click();
var getLocalSelectors = async () => {
const fileList = document.querySelector("input#localImport").files;
if (!fileList) return;
const file = fileList[0];
await setValue(import_dist.default.parse(await file.text()));
snackbar({
message: "设置应用成功!重新打开页面即可看见更改",
placement: "top"
});
};
var import_default = () => {
dialog({
headline: "选择导入方式",
description: "选择覆盖导入或者添加导入",
closeOnEsc: true,
closeOnOverlayClick: true,
queue: "selectors",
actions: [{
text: "覆盖导入",
onClick: () => {
window.Hanashiro.selectorsImportWay = 0;
}
}, {
text: "添加导入",
onClick: () => {
window.Hanashiro.selectorsImportWay = 1;
}
}]
});
dialog({
headline: "选择导入渠道",
description: "选择从本地导入或者远程导入",
closeOnEsc: true,
closeOnOverlayClick: true,
queue: "selectors",
actions: [{
text: "本地导入",
onClick: showFilePicker
}, {
text: "远程导入",
onClick: () => {
prompt({
headline: "远程设置文件链接",
description: "请输入远程设置文件的链接以导入",
closeOnEsc: true,
closeOnOverlayClick: true,
confirmText: "导入",
cancelText: "取消",
onConfirm: async (value) => {
if (!value) {
snackbar({
message: "请输入链接!",
placement: "top"
});
return new Promise((_, reject) => reject(false));
} else await getRemoteSelectors(value);
}
});
}
}]
});
};
var export_default = async () => {
const selectors = await getHanashiroSettings("selectors");
(0, import_FileSaver_min.saveAs)(new Blob([JSON.stringify(selectors, void 0, 2)]), "selectors.json");
};
var ManageSelectors_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
async editSelector() {
await editSelector();
},
async close() {
const selectors = await getHanashiroSettings("selectors");
selectors.sort((a, b) => {
if (a.order > b.order) return -1;
else if (a.order == b.order) return 0;
else return 1;
});
await setHanashiroSettings("selectors", selectors);
send("closePage");
},
async exportSelectors() {
await export_default();
},
importSelectors() {
import_default();
},
async getLocalSelectorsFile() {
await getLocalSelectors();
}
},
async mounted() {
await generateSelectors();
document.querySelector("#page").open = true;
}
});
function _sfc_render$4(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)(vue.Fragment, null, [(0, vue.createElementVNode)("mdui-dialog", {
id: "page",
headline: "管理选择器",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[6] || (_cache[6] = (...args) => _ctx.close && _ctx.close(...args))
}, [
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
variant: "tonal",
onClick: _cache[0] || (_cache[0] = (...args) => _ctx.exportSelectors && _ctx.exportSelectors(...args))
}, "导出"), (0, vue.createElementVNode)("mdui-button", {
variant: "tonal",
onClick: _cache[1] || (_cache[1] = (...args) => _ctx.importSelectors && _ctx.importSelectors(...args))
}, "导入")]),
_cache[14] || (_cache[14] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "选择选择器:"), (0, vue.createElementVNode)("mdui-radio-group", { id: "selectors" })], -1)),
(0, vue.createElementVNode)("div", null, [
_cache[8] || (_cache[8] = (0, vue.createElementVNode)("span", null, "备注:", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "name",
label: "备注",
onChange: _cache[2] || (_cache[2] = (...args) => _ctx.editSelector && _ctx.editSelector(...args))
}, null, 32),
_cache[9] || (_cache[9] = (0, vue.createElementVNode)("span", { class: "introduction" }, "失焦保存", -1))
]),
(0, vue.createElementVNode)("div", null, [
_cache[10] || (_cache[10] = (0, vue.createElementVNode)("span", null, "选择器:", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "selector",
label: "选择器",
onChange: _cache[3] || (_cache[3] = (...args) => _ctx.editSelector && _ctx.editSelector(...args))
}, null, 32),
_cache[11] || (_cache[11] = (0, vue.createElementVNode)("span", { class: "introduction" }, "留空删除。失焦保存", -1))
]),
(0, vue.createElementVNode)("div", null, [
_cache[12] || (_cache[12] = (0, vue.createElementVNode)("span", null, "排序优先值:", -1)),
(0, vue.createElementVNode)("mdui-text-field", {
variant: "filled",
id: "order",
label: "排序优先值",
type: "number",
onChange: _cache[4] || (_cache[4] = (...args) => _ctx.editSelector && _ctx.editSelector(...args))
}, null, 32),
_cache[13] || (_cache[13] = (0, vue.createElementVNode)("span", { class: "introduction" }, "数字越大,排序越前。失焦保存", -1))
]),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[5] || (_cache[5] = (...args) => _ctx.close && _ctx.close(...args))
}, "关闭")])
], 32), (0, vue.createElementVNode)("input", {
type: "file",
id: "localImport",
accept: ".json,.json5",
onChange: _cache[7] || (_cache[7] = (...args) => _ctx.getLocalSelectorsFile && _ctx.getLocalSelectorsFile(...args))
}, null, 32)], 64);
}
var ManageSelectors_default = _plugin_vue_export_helper_default(ManageSelectors_vue_vue_type_script_lang_default, [["render", _sfc_render$4]]);
var ChangeScreenshot_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
async getImg() {
const imageArrayBuffer = await document.querySelector("#img").files[0].arrayBuffer();
await replaceScreenshot(getSnapshotId_default(), imageArrayBuffer);
snackbar({
message: "更换截图成功!刷新页面即可看见更改",
placement: "top"
});
send("closePage");
},
cancel() {
send("closePage");
}
},
async mounted() {
document.querySelector("#img").click();
}
});
function _sfc_render$3(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)("input", {
type: "file",
id: "img",
accept: ".png",
onChange: _cache[0] || (_cache[0] = (...args) => _ctx.getImg && _ctx.getImg(...args)),
onCancel: _cache[1] || (_cache[1] = (...args) => _ctx.cancel && _ctx.cancel(...args))
}, null, 32);
}
var ChangeScreenshot_default = _plugin_vue_export_helper_default(ChangeScreenshot_vue_vue_type_script_lang_default, [["render", _sfc_render$3]]);
var arrayBufferToImage_default = (arrayBuffer) => {
const arrayBufferView = new Uint8Array(arrayBuffer);
const blob = new Blob([arrayBufferView], { type: "image/png" });
const src = (window.URL || window.webkitURL).createObjectURL(blob);
const img = document.createElement("img");
img.src = src;
return img;
};
var getInfo = async () => {
const canvas = document.querySelector("#canvas");
const snapshotId = getSnapshotId_default();
const screenshot = await getScreenshot(snapshotId);
const nodeId = getCurrentNodeId_default();
return [
canvas,
(await getScreenInfo(getSnapshotId_default())).width,
(await getScreenInfo(getSnapshotId_default())).height,
await getNodeAttr(snapshotId, nodeId, "left"),
await getNodeAttr(snapshotId, nodeId, "top"),
await getNodeAttr(snapshotId, nodeId, "width"),
await getNodeAttr(snapshotId, nodeId, "height"),
arrayBufferToImage_default(screenshot)
];
};
var partialView = (canvas, screenWidth, screenHeight, left, top, width, height, fullImg) => {
window.Hanashiro.currentPositionView = "partial";
const ctx = canvas.getContext("2d");
const tampCanvas = document.createElement("canvas");
const tampCtx = tampCanvas.getContext("2d");
canvas.width = width;
canvas.height = height;
tampCanvas.width = screenWidth;
tampCanvas.height = screenHeight;
tampCtx.drawImage(fullImg, 0, 0, screenWidth, screenHeight);
const imgData = tampCtx.getImageData(left, top, width, height);
ctx.putImageData(imgData, 0, 0);
};
var globalView = (canvas, screenWidth, screenHeight, fullImg) => {
window.Hanashiro.currentPositionView = "global";
const ctx = canvas.getContext("2d");
canvas.width = screenWidth;
canvas.height = screenHeight;
ctx.drawImage(fullImg, 0, 0, screenWidth, screenHeight);
};
var generatePosition_default = async () => {
const [canvas, screenWidth, screenHeight, left, top, width, height, fullImg] = await getInfo();
fullImg.onload = () => partialView(canvas, screenWidth, screenHeight, left, top, width, height, fullImg);
canvas.onclick = (e) => {
let x = e.offsetX, y = e.offsetY;
if (window.Hanashiro.currentPositionView == "global") {
x -= left;
y -= top;
}
const absolutePosition = {
left: left + x,
top: top + y
};
const relativePosition = {
left: `width * ${String((x / width).toFixed(4))}`,
top: `width * ${String((y / width).toFixed(4))}`
};
window.Hanashiro.nodePosition = {
absolute: absolutePosition,
relative: relativePosition
};
const result = document.querySelector("#result");
result.open = true;
};
};
var GeneratePosition_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: {
closeDialog() {
send("closePage");
},
closeResult() {
const result = document.querySelector("#result");
result.open = false;
},
async partialView() {
const [canvas, screenWidth, screenHeight, left, top, width, height, fullImg] = await getInfo();
fullImg.onload = () => partialView(canvas, screenWidth, screenHeight, left, top, width, height, fullImg);
},
async globalView() {
const [canvas, screenWidth, screenHeight, _left, _top, _width, _height, fullImg] = await getInfo();
fullImg.onload = () => globalView(canvas, screenWidth, screenHeight, fullImg);
},
getNewPosition() {
const absolute = window.Hanashiro.nodePosition.absolute;
const relative = window.Hanashiro.nodePosition.relative;
document.querySelector("#absolute").value = import_dist.default.stringify({ position: absolute }, void 0, 2);
document.querySelector("#relative").value = import_dist.default.stringify({ position: relative }, void 0, 2);
}
},
async mounted() {
await generatePosition_default();
document.querySelector("#page").open = true;
}
});
function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)(vue.Fragment, null, [(0, vue.createElementVNode)("mdui-dialog", {
id: "page",
headline: "选择点击坐标",
fullscreen: "",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[3] || (_cache[3] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [
_cache[6] || (_cache[6] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("canvas", { id: "canvas" })], -1)),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button-icon", {
icon: "open_in_full",
onClick: _cache[0] || (_cache[0] = (...args) => _ctx.globalView && _ctx.globalView(...args))
}), (0, vue.createElementVNode)("mdui-button-icon", {
icon: "close_fullscreen",
onClick: _cache[1] || (_cache[1] = (...args) => _ctx.partialView && _ctx.partialView(...args))
})]),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[2] || (_cache[2] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, "关闭")])
], 32), (0, vue.createElementVNode)("mdui-dialog", {
id: "result",
headline: "计算结果",
"close-on-esc": "",
"close-on-overlay-click": "",
onOpen: _cache[5] || (_cache[5] = (...args) => _ctx.getNewPosition && _ctx.getNewPosition(...args))
}, [
_cache[7] || (_cache[7] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "绝对坐标:"), (0, vue.createElementVNode)("mdui-text-field", {
id: "absolute",
variant: "filled",
label: "绝对坐标",
rows: "8"
})], -1)),
_cache[8] || (_cache[8] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, "相对坐标:"), (0, vue.createElementVNode)("mdui-text-field", {
id: "relative",
variant: "filled",
label: "相对坐标",
rows: "8"
})], -1)),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[4] || (_cache[4] = (...args) => _ctx.closeResult && _ctx.closeResult(...args))
}, "关闭")])
], 32)], 64);
}
var GeneratePosition_default = _plugin_vue_export_helper_default(GeneratePosition_vue_vue_type_script_lang_default, [["render", _sfc_render$2]]);
var Count_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
methods: { closeDialog() {
send("closePage");
} },
async mounted() {
const count = await getHanashiroSettings("count");
document.querySelector("#rejectRules").textContent = String(count?.rejectRules);
document.querySelector("#loaded").textContent = String(count?.loaded);
document.querySelector("#page").open = true;
}
});
function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createElementBlock)("mdui-dialog", {
id: "page",
headline: "统计",
"close-on-overlay-click": "",
"close-on-esc": "",
onClosed: _cache[1] || (_cache[1] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, [
_cache[2] || (_cache[2] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("h2", null, "本功能完全在本地进行,所有数据在本地储存!")], -1)),
_cache[3] || (_cache[3] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, [
(0, vue.createTextVNode)("注入规则 "),
(0, vue.createElementVNode)("span", { id: "rejectRules" }),
(0, vue.createTextVNode)(" 条")
])], -1)),
_cache[4] || (_cache[4] = (0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("span", null, [
(0, vue.createTextVNode)("脚本加载 "),
(0, vue.createElementVNode)("span", { id: "loaded" }),
(0, vue.createTextVNode)(" 次")
])], -1)),
(0, vue.createElementVNode)("div", null, [(0, vue.createElementVNode)("mdui-button", {
slot: "action",
variant: "tonal",
onClick: _cache[0] || (_cache[0] = (...args) => _ctx.closeDialog && _ctx.closeDialog(...args))
}, "关闭")])
], 32);
}
var App_vue_vue_type_script_lang_default = (0, vue.defineComponent)({
components: {
Main: Main_default,
Settings: Settings_default,
Help: Help_default,
UseSelector: UseSelector_default,
AddSelector: AddSelector_default,
ManageSelectors: ManageSelectors_default,
ChangeScreenshot: ChangeScreenshot_default,
GeneratePosition: GeneratePosition_default,
Count: _plugin_vue_export_helper_default(Count_vue_vue_type_script_lang_default, [["render", _sfc_render$1]])
},
data() {
return { currentComponent: "" };
},
created() {
receive("copyEvent", () => {
this.currentComponent = "Main";
});
receive("openSettings", () => {
this.currentComponent = "Settings";
});
receive("openHelp", () => {
this.currentComponent = "Help";
});
receive("openUseSelector", () => {
this.currentComponent = "UseSelector";
});
receive("openAddSelector", () => {
this.currentComponent = "AddSelector";
});
receive("openManageSelectors", () => {
this.currentComponent = "ManageSelectors";
});
receive("openChangeScreenshot", () => {
this.currentComponent = "ChangeScreenshot";
});
receive("openGeneratePosition", () => {
this.currentComponent = "GeneratePosition";
});
receive("openCount", () => {
this.currentComponent = "Count";
});
receive("closePage", () => {
this.currentComponent = "";
});
},
mounted() {
setColorScheme("#39C5BB");
}
});
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
return (0, vue.openBlock)(), (0, vue.createBlock)((0, vue.resolveDynamicComponent)(_ctx.currentComponent));
}
(0, vue.createApp)( _plugin_vue_export_helper_default(App_vue_vue_type_script_lang_default, [["render", _sfc_render]])).mount((() => {
const app = document.createElement("div");
document.body.append(app);
return app;
})());
})(Vue);