From a593087fd340cfa9d18281b8c47530ec10a1070e Mon Sep 17 00:00:00 2001 From: huchenlei Date: Fri, 30 Aug 2024 10:38:28 -0400 Subject: [PATCH 1/2] Update ComfyUI_frontend to 1.2.40 --- web/assets/index-CaD4RONs.js | 95141 ------------------ web/assets/index-CaD4RONs.js.map | 1 - web/assets/index-DAK31IJJ.css | 4141 - web/assets/index-DjWyclij.css | 149 - web/assets/index-DkvOTKox.js | 6185 -- web/assets/index-DkvOTKox.js.map | 1 - web/assets/primeicons-C6QP2o4f.woff2 | Bin 35148 -> 0 bytes web/assets/primeicons-DMOk5skT.eot | Bin 85156 -> 0 bytes web/assets/primeicons-Dr5RGzOO.svg | 345 - web/assets/primeicons-MpK4pl85.ttf | Bin 84980 -> 0 bytes web/assets/primeicons-WjwUDZjB.woff | Bin 85056 -> 0 bytes web/assets/userSelection-BGzn1LuN.css | 136 - web/assets/userSelection-GRU1gtOt.js | 142 - web/assets/userSelection-GRU1gtOt.js.map | 1 - web/extensions/core/clipspace.js | 2 - web/extensions/core/groupNode.js | 3 - web/extensions/core/groupNodeManage.js | 2 - web/extensions/core/widgetInputs.js | 4 - web/fonts/materialdesignicons-webfont.woff2 | Bin 403216 -> 0 bytes web/index.html | 50 - web/materialdesignicons.min.css | 3 - web/scripts/api.js | 2 - web/scripts/app.js | 4 - web/scripts/changeTracker.js | 2 - web/scripts/defaultGraph.js | 2 - web/scripts/domWidget.js | 2 - web/scripts/logging.js | 2 - web/scripts/metadata/flac.js | 3 - web/scripts/metadata/png.js | 3 - web/scripts/pnginfo.js | 6 - web/scripts/ui.js | 4 - web/scripts/ui/components/asyncDialog.js | 2 - web/scripts/ui/components/button.js | 2 - web/scripts/ui/components/buttonGroup.js | 2 - web/scripts/ui/components/popup.js | 2 - web/scripts/ui/components/splitButton.js | 2 - web/scripts/ui/dialog.js | 2 - web/scripts/ui/draggableList.js | 2 - web/scripts/ui/imagePreview.js | 3 - web/scripts/ui/menu/index.js | 2 - web/scripts/ui/menu/interruptButton.js | 2 - web/scripts/ui/menu/queueButton.js | 2 - web/scripts/ui/menu/queueOptions.js | 2 - web/scripts/ui/menu/workflows.js | 3 - web/scripts/ui/settings.js | 2 - web/scripts/ui/spinner.js | 2 - web/scripts/ui/toggleSwitch.js | 2 - web/scripts/ui/userSelection.js | 2 - web/scripts/ui/utils.js | 3 - web/scripts/utils.js | 8 - web/scripts/widgets.js | 6 - web/scripts/workflows.js | 4 - web/user.css | 1 - 53 files changed, 106394 deletions(-) delete mode 100644 web/assets/index-CaD4RONs.js delete mode 100644 web/assets/index-CaD4RONs.js.map delete mode 100644 web/assets/index-DAK31IJJ.css delete mode 100644 web/assets/index-DjWyclij.css delete mode 100644 web/assets/index-DkvOTKox.js delete mode 100644 web/assets/index-DkvOTKox.js.map delete mode 100644 web/assets/primeicons-C6QP2o4f.woff2 delete mode 100644 web/assets/primeicons-DMOk5skT.eot delete mode 100644 web/assets/primeicons-Dr5RGzOO.svg delete mode 100644 web/assets/primeicons-MpK4pl85.ttf delete mode 100644 web/assets/primeicons-WjwUDZjB.woff delete mode 100644 web/assets/userSelection-BGzn1LuN.css delete mode 100644 web/assets/userSelection-GRU1gtOt.js delete mode 100644 web/assets/userSelection-GRU1gtOt.js.map delete mode 100644 web/extensions/core/clipspace.js delete mode 100644 web/extensions/core/groupNode.js delete mode 100644 web/extensions/core/groupNodeManage.js delete mode 100644 web/extensions/core/widgetInputs.js delete mode 100644 web/fonts/materialdesignicons-webfont.woff2 delete mode 100644 web/index.html delete mode 100644 web/materialdesignicons.min.css delete mode 100644 web/scripts/api.js delete mode 100644 web/scripts/app.js delete mode 100644 web/scripts/changeTracker.js delete mode 100644 web/scripts/defaultGraph.js delete mode 100644 web/scripts/domWidget.js delete mode 100644 web/scripts/logging.js delete mode 100644 web/scripts/metadata/flac.js delete mode 100644 web/scripts/metadata/png.js delete mode 100644 web/scripts/pnginfo.js delete mode 100644 web/scripts/ui.js delete mode 100644 web/scripts/ui/components/asyncDialog.js delete mode 100644 web/scripts/ui/components/button.js delete mode 100644 web/scripts/ui/components/buttonGroup.js delete mode 100644 web/scripts/ui/components/popup.js delete mode 100644 web/scripts/ui/components/splitButton.js delete mode 100644 web/scripts/ui/dialog.js delete mode 100644 web/scripts/ui/draggableList.js delete mode 100644 web/scripts/ui/imagePreview.js delete mode 100644 web/scripts/ui/menu/index.js delete mode 100644 web/scripts/ui/menu/interruptButton.js delete mode 100644 web/scripts/ui/menu/queueButton.js delete mode 100644 web/scripts/ui/menu/queueOptions.js delete mode 100644 web/scripts/ui/menu/workflows.js delete mode 100644 web/scripts/ui/settings.js delete mode 100644 web/scripts/ui/spinner.js delete mode 100644 web/scripts/ui/toggleSwitch.js delete mode 100644 web/scripts/ui/userSelection.js delete mode 100644 web/scripts/ui/utils.js delete mode 100644 web/scripts/utils.js delete mode 100644 web/scripts/widgets.js delete mode 100644 web/scripts/workflows.js delete mode 100644 web/user.css diff --git a/web/assets/index-CaD4RONs.js b/web/assets/index-CaD4RONs.js deleted file mode 100644 index 07f9f3a0774..00000000000 --- a/web/assets/index-CaD4RONs.js +++ /dev/null @@ -1,95141 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DkvOTKox.js","./index-DjWyclij.css","./userSelection-GRU1gtOt.js","./userSelection-BGzn1LuN.css"])))=>i.map(i=>d[i]); -var __defProp2 = Object.defineProperty; -var __defProps2 = Object.defineProperties; -var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors; -var __getOwnPropSymbols2 = Object.getOwnPropertySymbols; -var __hasOwnProp2 = Object.prototype.hasOwnProperty; -var __propIsEnum2 = Object.prototype.propertyIsEnumerable; -var __typeError = (msg) => { - throw TypeError(msg); -}; -var __defNormalProp2 = (obj, key, value3) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value: value3 }) : obj[key] = value3; -var __spreadValues2 = (a, b) => { - for (var prop2 in b || (b = {})) - if (__hasOwnProp2.call(b, prop2)) - __defNormalProp2(a, prop2, b[prop2]); - if (__getOwnPropSymbols2) - for (var prop2 of __getOwnPropSymbols2(b)) { - if (__propIsEnum2.call(b, prop2)) - __defNormalProp2(a, prop2, b[prop2]); - } - return a; -}; -var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b)); -var __name = (target, value3) => __defProp2(target, "name", { value: value3, configurable: true }); -var __objRest2 = (source, exclude) => { - var target = {}; - for (var prop2 in source) - if (__hasOwnProp2.call(source, prop2) && exclude.indexOf(prop2) < 0) - target[prop2] = source[prop2]; - if (source != null && __getOwnPropSymbols2) - for (var prop2 of __getOwnPropSymbols2(source)) { - if (exclude.indexOf(prop2) < 0 && __propIsEnum2.call(source, prop2)) - target[prop2] = source[prop2]; - } - return target; -}; -var __publicField2 = (obj, key, value3) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value3); -var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); -var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); -var __privateAdd = (obj, member, value3) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value3); -var __privateSet = (obj, member, value3, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value3) : member.set(obj, value3), value3); -var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); -var __privateWrapper = (obj, member, setter, getter) => ({ - set _(value3) { - __privateSet(obj, member, value3, setter); - }, - get _() { - return __privateGet(obj, member, getter); - } -}); -var __async = (__this, __arguments, generator) => { - return new Promise((resolve8, reject2) => { - var fulfilled = (value3) => { - try { - step2(generator.next(value3)); - } catch (e) { - reject2(e); - } - }; - var rejected = (value3) => { - try { - step2(generator.throw(value3)); - } catch (e) { - reject2(e); - } - }; - var step2 = (x2) => x2.done ? resolve8(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected); - step2((generator = generator.apply(__this, __arguments)).next()); - }); -}; -var _a, _registered, _ComfyApi_instances, pollQueue_fn, createSocket_fn, postItem_fn, _buttons, _b, _ComfySettingsDialog_instances, dispatchChange_fn, _type, _text, _reverse, _enabled, _console, _over, _popupOpen, _ComfyPopup_instances, hide_fn, show_fn, _escHandler, _clickHandler, _internalQueueSize, _app, _ChangeTracker_instances, setApp_fn, _resolve, _activePromptId, _unsavedCount, _activeWorkflow, _ComfyWorkflowManager_instances, bindExecutionEvents_fn, _name, _path, _pathParts, _isFavorite, _ComfyWorkflow_instances, updatePath_fn, save_fn, _first, _updateProgress, _updateActive, _ComfyWorkflowsMenu_instances, bindEvents_fn, getMenuOptions_fn, getFavoriteMenuOptions_fn, _ComfyWorkflowsContent_instances, expandNode_fn, updateActive_fn, removeActive_fn, getFavoriteIcon_fn, getFavoriteOverIcon_fn, getFavoriteTooltip_fn, getFavoriteButton_fn, getDeleteButton_fn, getInsertButton_fn, getRenameButton_fn, getWorkflowElement_fn, createLeafNode_fn, createNode_fn, _options, _sizeBreak, _lastSizeBreaks, _sizeBreaks, _cachedInnerSize, _cacheTimeout, _c, _d, _queueItems, _processingQueue, _ComfyApp_instances, invokeExtensions_fn, invokeExtensionsAsync_fn, addRestoreWorkflowView_fn, addNodeContextMenuHandler_fn, addNodeKeyHandler_fn, addDrawBackgroundHandler_fn, addDropHandler_fn, addPasteHandler_fn, addCopyHandler_fn, addProcessMouseHandler_fn, addProcessKeyHandler_fn, addDrawGroupsHandler_fn, addDrawNodeHandler_fn, addApiUpdateHandlers_fn, addKeyboardHandler_fn, addConfigureHandler_fn, addAfterConfigureHandler_fn, loadExtensions_fn, migrateSettings_fn, setUser_fn, formatPromptError_fn, formatExecutionError_fn; -(/* @__PURE__ */ __name(function polyfill() { - const relList = document.createElement("link").relList; - if (relList && relList.supports && relList.supports("modulepreload")) { - return; - } - for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { - processPreload(link); - } - new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type !== "childList") { - continue; - } - for (const node3 of mutation.addedNodes) { - if (node3.tagName === "LINK" && node3.rel === "modulepreload") - processPreload(node3); - } - } - }).observe(document, { childList: true, subtree: true }); - function getFetchOpts(link) { - const fetchOpts = {}; - if (link.integrity) fetchOpts.integrity = link.integrity; - if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy; - if (link.crossOrigin === "use-credentials") - fetchOpts.credentials = "include"; - else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; - else fetchOpts.credentials = "same-origin"; - return fetchOpts; - } - __name(getFetchOpts, "getFetchOpts"); - function processPreload(link) { - if (link.ep) - return; - link.ep = true; - const fetchOpts = getFetchOpts(link); - fetch(link.href, fetchOpts); - } - __name(processPreload, "processPreload"); -}, "polyfill"))(); -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function getDefaultExportFromCjs(x2) { - return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; -} -__name(getDefaultExportFromCjs, "getDefaultExportFromCjs"); -function getDefaultExportFromNamespaceIfPresent(n) { - return n && Object.prototype.hasOwnProperty.call(n, "default") ? n["default"] : n; -} -__name(getDefaultExportFromNamespaceIfPresent, "getDefaultExportFromNamespaceIfPresent"); -function getDefaultExportFromNamespaceIfNotNamed(n) { - return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n; -} -__name(getDefaultExportFromNamespaceIfNotNamed, "getDefaultExportFromNamespaceIfNotNamed"); -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var f = n.default; - if (typeof f == "function") { - var a = /* @__PURE__ */ __name(function a2() { - if (this instanceof a2) { - return Reflect.construct(f, arguments, this.constructor); - } - return f.apply(this, arguments); - }, "a"); - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, "__esModule", { value: true }); - Object.keys(n).forEach(function(k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: /* @__PURE__ */ __name(function() { - return n[k]; - }, "get") - }); - }); - return a; -} -__name(getAugmentedNamespace, "getAugmentedNamespace"); -var _Reflect = {}; -/*! ***************************************************************************** -Copyright (C) Microsoft. All rights reserved. -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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -var Reflect$1; -(function(Reflect2) { - (function(factory) { - var root26 = typeof globalThis === "object" ? globalThis : typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis(); - var exporter = makeExporter(Reflect2); - if (typeof root26.Reflect !== "undefined") { - exporter = makeExporter(root26.Reflect, exporter); - } - factory(exporter, root26); - if (typeof root26.Reflect === "undefined") { - root26.Reflect = Reflect2; - } - function makeExporter(target, previous) { - return function(key, value3) { - Object.defineProperty(target, key, { configurable: true, writable: true, value: value3 }); - if (previous) - previous(key, value3); - }; - } - __name(makeExporter, "makeExporter"); - function functionThis() { - try { - return Function("return this;")(); - } catch (_2) { - } - } - __name(functionThis, "functionThis"); - function indirectEvalThis() { - try { - return (void 0, eval)("(function() { return this; })()"); - } catch (_2) { - } - } - __name(indirectEvalThis, "indirectEvalThis"); - function sloppyModeThis() { - return functionThis() || indirectEvalThis(); - } - __name(sloppyModeThis, "sloppyModeThis"); - })(function(exporter, root26) { - var hasOwn2 = Object.prototype.hasOwnProperty; - var supportsSymbol = typeof Symbol === "function"; - var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; - var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; - var supportsCreate = typeof Object.create === "function"; - var supportsProto = { __proto__: [] } instanceof Array; - var downLevel = !supportsCreate && !supportsProto; - var HashMap = { - // create an object in dictionary mode (a.k.a. "slow" mode in v8) - create: supportsCreate ? function() { - return MakeDictionary(/* @__PURE__ */ Object.create(null)); - } : supportsProto ? function() { - return MakeDictionary({ __proto__: null }); - } : function() { - return MakeDictionary({}); - }, - has: downLevel ? function(map2, key) { - return hasOwn2.call(map2, key); - } : function(map2, key) { - return key in map2; - }, - get: downLevel ? function(map2, key) { - return hasOwn2.call(map2, key) ? map2[key] : void 0; - } : function(map2, key) { - return map2[key]; - } - }; - var functionPrototype = Object.getPrototypeOf(Function); - var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); - var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); - var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); - var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : void 0; - var metadataRegistry = GetOrCreateMetadataRegistry(); - var metadataProvider = CreateMetadataProvider(metadataRegistry); - function decorate(decorators, target, propertyKey, attributes) { - if (!IsUndefined(propertyKey)) { - if (!IsArray(decorators)) - throw new TypeError(); - if (!IsObject(target)) - throw new TypeError(); - if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) - throw new TypeError(); - if (IsNull(attributes)) - attributes = void 0; - propertyKey = ToPropertyKey(propertyKey); - return DecorateProperty(decorators, target, propertyKey, attributes); - } else { - if (!IsArray(decorators)) - throw new TypeError(); - if (!IsConstructor(target)) - throw new TypeError(); - return DecorateConstructor(decorators, target); - } - } - __name(decorate, "decorate"); - exporter("decorate", decorate); - function metadata(metadataKey, metadataValue) { - function decorator(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) - throw new TypeError(); - OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); - } - __name(decorator, "decorator"); - return decorator; - } - __name(metadata, "metadata"); - exporter("metadata", metadata); - function defineMetadata(metadataKey, metadataValue, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); - } - __name(defineMetadata, "defineMetadata"); - exporter("defineMetadata", defineMetadata); - function hasMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryHasMetadata(metadataKey, target, propertyKey); - } - __name(hasMetadata, "hasMetadata"); - exporter("hasMetadata", hasMetadata); - function hasOwnMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); - } - __name(hasOwnMetadata, "hasOwnMetadata"); - exporter("hasOwnMetadata", hasOwnMetadata); - function getMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryGetMetadata(metadataKey, target, propertyKey); - } - __name(getMetadata, "getMetadata"); - exporter("getMetadata", getMetadata); - function getOwnMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); - } - __name(getOwnMetadata, "getOwnMetadata"); - exporter("getOwnMetadata", getOwnMetadata); - function getMetadataKeys(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryMetadataKeys(target, propertyKey); - } - __name(getMetadataKeys, "getMetadataKeys"); - exporter("getMetadataKeys", getMetadataKeys); - function getOwnMetadataKeys(target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - return OrdinaryOwnMetadataKeys(target, propertyKey); - } - __name(getOwnMetadataKeys, "getOwnMetadataKeys"); - exporter("getOwnMetadataKeys", getOwnMetadataKeys); - function deleteMetadata(metadataKey, target, propertyKey) { - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - if (!IsObject(target)) - throw new TypeError(); - if (!IsUndefined(propertyKey)) - propertyKey = ToPropertyKey(propertyKey); - var provider = GetMetadataProvider( - target, - propertyKey, - /*Create*/ - false - ); - if (IsUndefined(provider)) - return false; - return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey); - } - __name(deleteMetadata, "deleteMetadata"); - exporter("deleteMetadata", deleteMetadata); - function DecorateConstructor(decorators, target) { - for (var i2 = decorators.length - 1; i2 >= 0; --i2) { - var decorator = decorators[i2]; - var decorated = decorator(target); - if (!IsUndefined(decorated) && !IsNull(decorated)) { - if (!IsConstructor(decorated)) - throw new TypeError(); - target = decorated; - } - } - return target; - } - __name(DecorateConstructor, "DecorateConstructor"); - function DecorateProperty(decorators, target, propertyKey, descriptor) { - for (var i2 = decorators.length - 1; i2 >= 0; --i2) { - var decorator = decorators[i2]; - var decorated = decorator(target, propertyKey, descriptor); - if (!IsUndefined(decorated) && !IsNull(decorated)) { - if (!IsObject(decorated)) - throw new TypeError(); - descriptor = decorated; - } - } - return descriptor; - } - __name(DecorateProperty, "DecorateProperty"); - function OrdinaryHasMetadata(MetadataKey, O, P) { - var hasOwn3 = OrdinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn3) - return true; - var parent = OrdinaryGetPrototypeOf(O); - if (!IsNull(parent)) - return OrdinaryHasMetadata(MetadataKey, parent, P); - return false; - } - __name(OrdinaryHasMetadata, "OrdinaryHasMetadata"); - function OrdinaryHasOwnMetadata(MetadataKey, O, P) { - var provider = GetMetadataProvider( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(provider)) - return false; - return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P)); - } - __name(OrdinaryHasOwnMetadata, "OrdinaryHasOwnMetadata"); - function OrdinaryGetMetadata(MetadataKey, O, P) { - var hasOwn3 = OrdinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn3) - return OrdinaryGetOwnMetadata(MetadataKey, O, P); - var parent = OrdinaryGetPrototypeOf(O); - if (!IsNull(parent)) - return OrdinaryGetMetadata(MetadataKey, parent, P); - return void 0; - } - __name(OrdinaryGetMetadata, "OrdinaryGetMetadata"); - function OrdinaryGetOwnMetadata(MetadataKey, O, P) { - var provider = GetMetadataProvider( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(provider)) - return; - return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P); - } - __name(OrdinaryGetOwnMetadata, "OrdinaryGetOwnMetadata"); - function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { - var provider = GetMetadataProvider( - O, - P, - /*Create*/ - true - ); - provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P); - } - __name(OrdinaryDefineOwnMetadata, "OrdinaryDefineOwnMetadata"); - function OrdinaryMetadataKeys(O, P) { - var ownKeys2 = OrdinaryOwnMetadataKeys(O, P); - var parent = OrdinaryGetPrototypeOf(O); - if (parent === null) - return ownKeys2; - var parentKeys = OrdinaryMetadataKeys(parent, P); - if (parentKeys.length <= 0) - return ownKeys2; - if (ownKeys2.length <= 0) - return parentKeys; - var set2 = new _Set(); - var keys2 = []; - for (var _i = 0, ownKeys_1 = ownKeys2; _i < ownKeys_1.length; _i++) { - var key = ownKeys_1[_i]; - var hasKey = set2.has(key); - if (!hasKey) { - set2.add(key); - keys2.push(key); - } - } - for (var _a2 = 0, parentKeys_1 = parentKeys; _a2 < parentKeys_1.length; _a2++) { - var key = parentKeys_1[_a2]; - var hasKey = set2.has(key); - if (!hasKey) { - set2.add(key); - keys2.push(key); - } - } - return keys2; - } - __name(OrdinaryMetadataKeys, "OrdinaryMetadataKeys"); - function OrdinaryOwnMetadataKeys(O, P) { - var provider = GetMetadataProvider( - O, - P, - /*create*/ - false - ); - if (!provider) { - return []; - } - return provider.OrdinaryOwnMetadataKeys(O, P); - } - __name(OrdinaryOwnMetadataKeys, "OrdinaryOwnMetadataKeys"); - function Type2(x2) { - if (x2 === null) - return 1; - switch (typeof x2) { - case "undefined": - return 0; - case "boolean": - return 2; - case "string": - return 3; - case "symbol": - return 4; - case "number": - return 5; - case "object": - return x2 === null ? 1 : 6; - default: - return 6; - } - } - __name(Type2, "Type"); - function IsUndefined(x2) { - return x2 === void 0; - } - __name(IsUndefined, "IsUndefined"); - function IsNull(x2) { - return x2 === null; - } - __name(IsNull, "IsNull"); - function IsSymbol(x2) { - return typeof x2 === "symbol"; - } - __name(IsSymbol, "IsSymbol"); - function IsObject(x2) { - return typeof x2 === "object" ? x2 !== null : typeof x2 === "function"; - } - __name(IsObject, "IsObject"); - function ToPrimitive(input, PreferredType) { - switch (Type2(input)) { - case 0: - return input; - case 1: - return input; - case 2: - return input; - case 3: - return input; - case 4: - return input; - case 5: - return input; - } - var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default"; - var exoticToPrim = GetMethod(input, toPrimitiveSymbol); - if (exoticToPrim !== void 0) { - var result = exoticToPrim.call(input, hint); - if (IsObject(result)) - throw new TypeError(); - return result; - } - return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); - } - __name(ToPrimitive, "ToPrimitive"); - function OrdinaryToPrimitive(O, hint) { - if (hint === "string") { - var toString_1 = O.toString; - if (IsCallable(toString_1)) { - var result = toString_1.call(O); - if (!IsObject(result)) - return result; - } - var valueOf = O.valueOf; - if (IsCallable(valueOf)) { - var result = valueOf.call(O); - if (!IsObject(result)) - return result; - } - } else { - var valueOf = O.valueOf; - if (IsCallable(valueOf)) { - var result = valueOf.call(O); - if (!IsObject(result)) - return result; - } - var toString_2 = O.toString; - if (IsCallable(toString_2)) { - var result = toString_2.call(O); - if (!IsObject(result)) - return result; - } - } - throw new TypeError(); - } - __name(OrdinaryToPrimitive, "OrdinaryToPrimitive"); - function ToBoolean(argument) { - return !!argument; - } - __name(ToBoolean, "ToBoolean"); - function ToString(argument) { - return "" + argument; - } - __name(ToString, "ToString"); - function ToPropertyKey(argument) { - var key = ToPrimitive( - argument, - 3 - /* String */ - ); - if (IsSymbol(key)) - return key; - return ToString(key); - } - __name(ToPropertyKey, "ToPropertyKey"); - function IsArray(argument) { - return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; - } - __name(IsArray, "IsArray"); - function IsCallable(argument) { - return typeof argument === "function"; - } - __name(IsCallable, "IsCallable"); - function IsConstructor(argument) { - return typeof argument === "function"; - } - __name(IsConstructor, "IsConstructor"); - function IsPropertyKey(argument) { - switch (Type2(argument)) { - case 3: - return true; - case 4: - return true; - default: - return false; - } - } - __name(IsPropertyKey, "IsPropertyKey"); - function SameValueZero(x2, y2) { - return x2 === y2 || x2 !== x2 && y2 !== y2; - } - __name(SameValueZero, "SameValueZero"); - function GetMethod(V, P) { - var func = V[P]; - if (func === void 0 || func === null) - return void 0; - if (!IsCallable(func)) - throw new TypeError(); - return func; - } - __name(GetMethod, "GetMethod"); - function GetIterator(obj) { - var method = GetMethod(obj, iteratorSymbol); - if (!IsCallable(method)) - throw new TypeError(); - var iterator = method.call(obj); - if (!IsObject(iterator)) - throw new TypeError(); - return iterator; - } - __name(GetIterator, "GetIterator"); - function IteratorValue(iterResult) { - return iterResult.value; - } - __name(IteratorValue, "IteratorValue"); - function IteratorStep(iterator) { - var result = iterator.next(); - return result.done ? false : result; - } - __name(IteratorStep, "IteratorStep"); - function IteratorClose(iterator) { - var f = iterator["return"]; - if (f) - f.call(iterator); - } - __name(IteratorClose, "IteratorClose"); - function OrdinaryGetPrototypeOf(O) { - var proto = Object.getPrototypeOf(O); - if (typeof O !== "function" || O === functionPrototype) - return proto; - if (proto !== functionPrototype) - return proto; - var prototype = O.prototype; - var prototypeProto = prototype && Object.getPrototypeOf(prototype); - if (prototypeProto == null || prototypeProto === Object.prototype) - return proto; - var constructor = prototypeProto.constructor; - if (typeof constructor !== "function") - return proto; - if (constructor === O) - return proto; - return constructor; - } - __name(OrdinaryGetPrototypeOf, "OrdinaryGetPrototypeOf"); - function CreateMetadataRegistry() { - var fallback; - if (!IsUndefined(registrySymbol) && typeof root26.Reflect !== "undefined" && !(registrySymbol in root26.Reflect) && typeof root26.Reflect.defineMetadata === "function") { - fallback = CreateFallbackProvider(root26.Reflect); - } - var first; - var second; - var rest; - var targetProviderMap = new _WeakMap(); - var registry = { - registerProvider, - getProvider, - setProvider - }; - return registry; - function registerProvider(provider) { - if (!Object.isExtensible(registry)) { - throw new Error("Cannot add provider to a frozen registry."); - } - switch (true) { - case fallback === provider: - break; - case IsUndefined(first): - first = provider; - break; - case first === provider: - break; - case IsUndefined(second): - second = provider; - break; - case second === provider: - break; - default: - if (rest === void 0) - rest = new _Set(); - rest.add(provider); - break; - } - } - __name(registerProvider, "registerProvider"); - function getProviderNoCache(O, P) { - if (!IsUndefined(first)) { - if (first.isProviderFor(O, P)) - return first; - if (!IsUndefined(second)) { - if (second.isProviderFor(O, P)) - return first; - if (!IsUndefined(rest)) { - var iterator = GetIterator(rest); - while (true) { - var next2 = IteratorStep(iterator); - if (!next2) { - return void 0; - } - var provider = IteratorValue(next2); - if (provider.isProviderFor(O, P)) { - IteratorClose(iterator); - return provider; - } - } - } - } - } - if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) { - return fallback; - } - return void 0; - } - __name(getProviderNoCache, "getProviderNoCache"); - function getProvider(O, P) { - var providerMap = targetProviderMap.get(O); - var provider; - if (!IsUndefined(providerMap)) { - provider = providerMap.get(P); - } - if (!IsUndefined(provider)) { - return provider; - } - provider = getProviderNoCache(O, P); - if (!IsUndefined(provider)) { - if (IsUndefined(providerMap)) { - providerMap = new _Map(); - targetProviderMap.set(O, providerMap); - } - providerMap.set(P, provider); - } - return provider; - } - __name(getProvider, "getProvider"); - function hasProvider(provider) { - if (IsUndefined(provider)) - throw new TypeError(); - return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider); - } - __name(hasProvider, "hasProvider"); - function setProvider(O, P, provider) { - if (!hasProvider(provider)) { - throw new Error("Metadata provider not registered."); - } - var existingProvider = getProvider(O, P); - if (existingProvider !== provider) { - if (!IsUndefined(existingProvider)) { - return false; - } - var providerMap = targetProviderMap.get(O); - if (IsUndefined(providerMap)) { - providerMap = new _Map(); - targetProviderMap.set(O, providerMap); - } - providerMap.set(P, provider); - } - return true; - } - __name(setProvider, "setProvider"); - } - __name(CreateMetadataRegistry, "CreateMetadataRegistry"); - function GetOrCreateMetadataRegistry() { - var metadataRegistry2; - if (!IsUndefined(registrySymbol) && IsObject(root26.Reflect) && Object.isExtensible(root26.Reflect)) { - metadataRegistry2 = root26.Reflect[registrySymbol]; - } - if (IsUndefined(metadataRegistry2)) { - metadataRegistry2 = CreateMetadataRegistry(); - } - if (!IsUndefined(registrySymbol) && IsObject(root26.Reflect) && Object.isExtensible(root26.Reflect)) { - Object.defineProperty(root26.Reflect, registrySymbol, { - enumerable: false, - configurable: false, - writable: false, - value: metadataRegistry2 - }); - } - return metadataRegistry2; - } - __name(GetOrCreateMetadataRegistry, "GetOrCreateMetadataRegistry"); - function CreateMetadataProvider(registry) { - var metadata2 = new _WeakMap(); - var provider = { - isProviderFor: /* @__PURE__ */ __name(function(O, P) { - var targetMetadata = metadata2.get(O); - if (IsUndefined(targetMetadata)) - return false; - return targetMetadata.has(P); - }, "isProviderFor"), - OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata2, - OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata2, - OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata2, - OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys2, - OrdinaryDeleteMetadata - }; - metadataRegistry.registerProvider(provider); - return provider; - function GetOrCreateMetadataMap(O, P, Create) { - var targetMetadata = metadata2.get(O); - var createdTargetMetadata = false; - if (IsUndefined(targetMetadata)) { - if (!Create) - return void 0; - targetMetadata = new _Map(); - metadata2.set(O, targetMetadata); - createdTargetMetadata = true; - } - var metadataMap = targetMetadata.get(P); - if (IsUndefined(metadataMap)) { - if (!Create) - return void 0; - metadataMap = new _Map(); - targetMetadata.set(P, metadataMap); - if (!registry.setProvider(O, P, provider)) { - targetMetadata.delete(P); - if (createdTargetMetadata) { - metadata2.delete(O); - } - throw new Error("Wrong provider for target."); - } - } - return metadataMap; - } - __name(GetOrCreateMetadataMap, "GetOrCreateMetadataMap"); - function OrdinaryHasOwnMetadata2(MetadataKey, O, P) { - var metadataMap = GetOrCreateMetadataMap( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(metadataMap)) - return false; - return ToBoolean(metadataMap.has(MetadataKey)); - } - __name(OrdinaryHasOwnMetadata2, "OrdinaryHasOwnMetadata"); - function OrdinaryGetOwnMetadata2(MetadataKey, O, P) { - var metadataMap = GetOrCreateMetadataMap( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(metadataMap)) - return void 0; - return metadataMap.get(MetadataKey); - } - __name(OrdinaryGetOwnMetadata2, "OrdinaryGetOwnMetadata"); - function OrdinaryDefineOwnMetadata2(MetadataKey, MetadataValue, O, P) { - var metadataMap = GetOrCreateMetadataMap( - O, - P, - /*Create*/ - true - ); - metadataMap.set(MetadataKey, MetadataValue); - } - __name(OrdinaryDefineOwnMetadata2, "OrdinaryDefineOwnMetadata"); - function OrdinaryOwnMetadataKeys2(O, P) { - var keys2 = []; - var metadataMap = GetOrCreateMetadataMap( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(metadataMap)) - return keys2; - var keysObj = metadataMap.keys(); - var iterator = GetIterator(keysObj); - var k = 0; - while (true) { - var next2 = IteratorStep(iterator); - if (!next2) { - keys2.length = k; - return keys2; - } - var nextValue = IteratorValue(next2); - try { - keys2[k] = nextValue; - } catch (e) { - try { - IteratorClose(iterator); - } finally { - throw e; - } - } - k++; - } - } - __name(OrdinaryOwnMetadataKeys2, "OrdinaryOwnMetadataKeys"); - function OrdinaryDeleteMetadata(MetadataKey, O, P) { - var metadataMap = GetOrCreateMetadataMap( - O, - P, - /*Create*/ - false - ); - if (IsUndefined(metadataMap)) - return false; - if (!metadataMap.delete(MetadataKey)) - return false; - if (metadataMap.size === 0) { - var targetMetadata = metadata2.get(O); - if (!IsUndefined(targetMetadata)) { - targetMetadata.delete(P); - if (targetMetadata.size === 0) { - metadata2.delete(targetMetadata); - } - } - } - return true; - } - __name(OrdinaryDeleteMetadata, "OrdinaryDeleteMetadata"); - } - __name(CreateMetadataProvider, "CreateMetadataProvider"); - function CreateFallbackProvider(reflect) { - var defineMetadata2 = reflect.defineMetadata, hasOwnMetadata2 = reflect.hasOwnMetadata, getOwnMetadata2 = reflect.getOwnMetadata, getOwnMetadataKeys2 = reflect.getOwnMetadataKeys, deleteMetadata2 = reflect.deleteMetadata; - var metadataOwner = new _WeakMap(); - var provider = { - isProviderFor: /* @__PURE__ */ __name(function(O, P) { - var metadataPropertySet = metadataOwner.get(O); - if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) { - return true; - } - if (getOwnMetadataKeys2(O, P).length) { - if (IsUndefined(metadataPropertySet)) { - metadataPropertySet = new _Set(); - metadataOwner.set(O, metadataPropertySet); - } - metadataPropertySet.add(P); - return true; - } - return false; - }, "isProviderFor"), - OrdinaryDefineOwnMetadata: defineMetadata2, - OrdinaryHasOwnMetadata: hasOwnMetadata2, - OrdinaryGetOwnMetadata: getOwnMetadata2, - OrdinaryOwnMetadataKeys: getOwnMetadataKeys2, - OrdinaryDeleteMetadata: deleteMetadata2 - }; - return provider; - } - __name(CreateFallbackProvider, "CreateFallbackProvider"); - function GetMetadataProvider(O, P, Create) { - var registeredProvider = metadataRegistry.getProvider(O, P); - if (!IsUndefined(registeredProvider)) { - return registeredProvider; - } - if (Create) { - if (metadataRegistry.setProvider(O, P, metadataProvider)) { - return metadataProvider; - } - throw new Error("Illegal state."); - } - return void 0; - } - __name(GetMetadataProvider, "GetMetadataProvider"); - function CreateMapPolyfill() { - var cacheSentinel = {}; - var arraySentinel = []; - var MapIterator = ( - /** @class */ - function() { - function MapIterator2(keys2, values2, selector) { - this._index = 0; - this._keys = keys2; - this._values = values2; - this._selector = selector; - } - __name(MapIterator2, "MapIterator"); - MapIterator2.prototype["@@iterator"] = function() { - return this; - }; - MapIterator2.prototype[iteratorSymbol] = function() { - return this; - }; - MapIterator2.prototype.next = function() { - var index2 = this._index; - if (index2 >= 0 && index2 < this._keys.length) { - var result = this._selector(this._keys[index2], this._values[index2]); - if (index2 + 1 >= this._keys.length) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } else { - this._index++; - } - return { value: result, done: false }; - } - return { value: void 0, done: true }; - }; - MapIterator2.prototype.throw = function(error) { - if (this._index >= 0) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } - throw error; - }; - MapIterator2.prototype.return = function(value3) { - if (this._index >= 0) { - this._index = -1; - this._keys = arraySentinel; - this._values = arraySentinel; - } - return { value: value3, done: true }; - }; - return MapIterator2; - }() - ); - var Map2 = ( - /** @class */ - function() { - function Map3() { - this._keys = []; - this._values = []; - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - } - __name(Map3, "Map"); - Object.defineProperty(Map3.prototype, "size", { - get: /* @__PURE__ */ __name(function() { - return this._keys.length; - }, "get"), - enumerable: true, - configurable: true - }); - Map3.prototype.has = function(key) { - return this._find( - key, - /*insert*/ - false - ) >= 0; - }; - Map3.prototype.get = function(key) { - var index2 = this._find( - key, - /*insert*/ - false - ); - return index2 >= 0 ? this._values[index2] : void 0; - }; - Map3.prototype.set = function(key, value3) { - var index2 = this._find( - key, - /*insert*/ - true - ); - this._values[index2] = value3; - return this; - }; - Map3.prototype.delete = function(key) { - var index2 = this._find( - key, - /*insert*/ - false - ); - if (index2 >= 0) { - var size2 = this._keys.length; - for (var i2 = index2 + 1; i2 < size2; i2++) { - this._keys[i2 - 1] = this._keys[i2]; - this._values[i2 - 1] = this._values[i2]; - } - this._keys.length--; - this._values.length--; - if (SameValueZero(key, this._cacheKey)) { - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - } - return true; - } - return false; - }; - Map3.prototype.clear = function() { - this._keys.length = 0; - this._values.length = 0; - this._cacheKey = cacheSentinel; - this._cacheIndex = -2; - }; - Map3.prototype.keys = function() { - return new MapIterator(this._keys, this._values, getKey); - }; - Map3.prototype.values = function() { - return new MapIterator(this._keys, this._values, getValue2); - }; - Map3.prototype.entries = function() { - return new MapIterator(this._keys, this._values, getEntry); - }; - Map3.prototype["@@iterator"] = function() { - return this.entries(); - }; - Map3.prototype[iteratorSymbol] = function() { - return this.entries(); - }; - Map3.prototype._find = function(key, insert2) { - if (!SameValueZero(this._cacheKey, key)) { - this._cacheIndex = -1; - for (var i2 = 0; i2 < this._keys.length; i2++) { - if (SameValueZero(this._keys[i2], key)) { - this._cacheIndex = i2; - break; - } - } - } - if (this._cacheIndex < 0 && insert2) { - this._cacheIndex = this._keys.length; - this._keys.push(key); - this._values.push(void 0); - } - return this._cacheIndex; - }; - return Map3; - }() - ); - return Map2; - function getKey(key, _2) { - return key; - } - __name(getKey, "getKey"); - function getValue2(_2, value3) { - return value3; - } - __name(getValue2, "getValue"); - function getEntry(key, value3) { - return [key, value3]; - } - __name(getEntry, "getEntry"); - } - __name(CreateMapPolyfill, "CreateMapPolyfill"); - function CreateSetPolyfill() { - var Set2 = ( - /** @class */ - function() { - function Set3() { - this._map = new _Map(); - } - __name(Set3, "Set"); - Object.defineProperty(Set3.prototype, "size", { - get: /* @__PURE__ */ __name(function() { - return this._map.size; - }, "get"), - enumerable: true, - configurable: true - }); - Set3.prototype.has = function(value3) { - return this._map.has(value3); - }; - Set3.prototype.add = function(value3) { - return this._map.set(value3, value3), this; - }; - Set3.prototype.delete = function(value3) { - return this._map.delete(value3); - }; - Set3.prototype.clear = function() { - this._map.clear(); - }; - Set3.prototype.keys = function() { - return this._map.keys(); - }; - Set3.prototype.values = function() { - return this._map.keys(); - }; - Set3.prototype.entries = function() { - return this._map.entries(); - }; - Set3.prototype["@@iterator"] = function() { - return this.keys(); - }; - Set3.prototype[iteratorSymbol] = function() { - return this.keys(); - }; - return Set3; - }() - ); - return Set2; - } - __name(CreateSetPolyfill, "CreateSetPolyfill"); - function CreateWeakMapPolyfill() { - var UUID_SIZE = 16; - var keys2 = HashMap.create(); - var rootKey = CreateUniqueKey(); - return ( - /** @class */ - function() { - function WeakMap2() { - this._key = CreateUniqueKey(); - } - __name(WeakMap2, "WeakMap"); - WeakMap2.prototype.has = function(target) { - var table = GetOrCreateWeakMapTable( - target, - /*create*/ - false - ); - return table !== void 0 ? HashMap.has(table, this._key) : false; - }; - WeakMap2.prototype.get = function(target) { - var table = GetOrCreateWeakMapTable( - target, - /*create*/ - false - ); - return table !== void 0 ? HashMap.get(table, this._key) : void 0; - }; - WeakMap2.prototype.set = function(target, value3) { - var table = GetOrCreateWeakMapTable( - target, - /*create*/ - true - ); - table[this._key] = value3; - return this; - }; - WeakMap2.prototype.delete = function(target) { - var table = GetOrCreateWeakMapTable( - target, - /*create*/ - false - ); - return table !== void 0 ? delete table[this._key] : false; - }; - WeakMap2.prototype.clear = function() { - this._key = CreateUniqueKey(); - }; - return WeakMap2; - }() - ); - function CreateUniqueKey() { - var key; - do - key = "@@WeakMap@@" + CreateUUID(); - while (HashMap.has(keys2, key)); - keys2[key] = true; - return key; - } - __name(CreateUniqueKey, "CreateUniqueKey"); - function GetOrCreateWeakMapTable(target, create2) { - if (!hasOwn2.call(target, rootKey)) { - if (!create2) - return void 0; - Object.defineProperty(target, rootKey, { value: HashMap.create() }); - } - return target[rootKey]; - } - __name(GetOrCreateWeakMapTable, "GetOrCreateWeakMapTable"); - function FillRandomBytes(buffer2, size2) { - for (var i2 = 0; i2 < size2; ++i2) - buffer2[i2] = Math.random() * 255 | 0; - return buffer2; - } - __name(FillRandomBytes, "FillRandomBytes"); - function GenRandomBytes(size2) { - if (typeof Uint8Array === "function") { - var array = new Uint8Array(size2); - if (typeof crypto !== "undefined") { - crypto.getRandomValues(array); - } else if (typeof msCrypto !== "undefined") { - msCrypto.getRandomValues(array); - } else { - FillRandomBytes(array, size2); - } - return array; - } - return FillRandomBytes(new Array(size2), size2); - } - __name(GenRandomBytes, "GenRandomBytes"); - function CreateUUID() { - var data21 = GenRandomBytes(UUID_SIZE); - data21[6] = data21[6] & 79 | 64; - data21[8] = data21[8] & 191 | 128; - var result = ""; - for (var offset = 0; offset < UUID_SIZE; ++offset) { - var byte = data21[offset]; - if (offset === 4 || offset === 6 || offset === 8) - result += "-"; - if (byte < 16) - result += "0"; - result += byte.toString(16).toLowerCase(); - } - return result; - } - __name(CreateUUID, "CreateUUID"); - } - __name(CreateWeakMapPolyfill, "CreateWeakMapPolyfill"); - function MakeDictionary(obj) { - obj.__ = void 0; - delete obj.__; - return obj; - } - __name(MakeDictionary, "MakeDictionary"); - }); -})(Reflect$1 || (Reflect$1 = {})); -window["__COMFYUI_FRONTEND_VERSION__"] = "1.2.30"; -console.log("ComfyUI Front-end version:", "1.2.30"); -/** -* @vue/shared v3.4.31 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -/*! #__NO_SIDE_EFFECTS__ */ -// @__NO_SIDE_EFFECTS__ -function makeMap(str, expectsLowerCase) { - const set2 = new Set(str.split(",")); - return expectsLowerCase ? (val) => set2.has(val.toLowerCase()) : (val) => set2.has(val); -} -__name(makeMap, "makeMap"); -const EMPTY_OBJ = false ? Object.freeze({}) : {}; -const EMPTY_ARR = false ? Object.freeze([]) : []; -const NOOP = /* @__PURE__ */ __name(() => { -}, "NOOP"); -const NO = /* @__PURE__ */ __name(() => false, "NO"); -const isOn = /* @__PURE__ */ __name((key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter -(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97), "isOn"); -const isModelListener = /* @__PURE__ */ __name((key) => key.startsWith("onUpdate:"), "isModelListener"); -const extend = Object.assign; -const remove$1 = /* @__PURE__ */ __name((arr, el) => { - const i2 = arr.indexOf(el); - if (i2 > -1) { - arr.splice(i2, 1); - } -}, "remove$1"); -const hasOwnProperty$2 = Object.prototype.hasOwnProperty; -const hasOwn$3 = /* @__PURE__ */ __name((val, key) => hasOwnProperty$2.call(val, key), "hasOwn$3"); -const isArray$3 = Array.isArray; -const isMap = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Map]", "isMap"); -const isSet = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Set]", "isSet"); -const isDate$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Date]", "isDate$2"); -const isRegExp$1 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object RegExp]", "isRegExp$1"); -const isFunction$3 = /* @__PURE__ */ __name((val) => typeof val === "function", "isFunction$3"); -const isString$4 = /* @__PURE__ */ __name((val) => typeof val === "string", "isString$4"); -const isSymbol$1 = /* @__PURE__ */ __name((val) => typeof val === "symbol", "isSymbol$1"); -const isObject$5 = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject$5"); -const isPromise$2 = /* @__PURE__ */ __name((val) => { - return (isObject$5(val) || isFunction$3(val)) && isFunction$3(val.then) && isFunction$3(val.catch); -}, "isPromise$2"); -const objectToString$1 = Object.prototype.toString; -const toTypeString$1 = /* @__PURE__ */ __name((value3) => objectToString$1.call(value3), "toTypeString$1"); -const toRawType = /* @__PURE__ */ __name((value3) => { - return toTypeString$1(value3).slice(8, -1); -}, "toRawType"); -const isPlainObject$2 = /* @__PURE__ */ __name((val) => toTypeString$1(val) === "[object Object]", "isPlainObject$2"); -const isIntegerKey = /* @__PURE__ */ __name((key) => isString$4(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key, "isIntegerKey"); -const isReservedProp = /* @__PURE__ */ makeMap( - // the leading comma is intentional so empty string "" is also included - ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" -); -const isBuiltInDirective = /* @__PURE__ */ makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" -); -const cacheStringFunction$1 = /* @__PURE__ */ __name((fn) => { - const cache2 = /* @__PURE__ */ Object.create(null); - return (str) => { - const hit = cache2[str]; - return hit || (cache2[str] = fn(str)); - }; -}, "cacheStringFunction$1"); -const camelizeRE$1 = /-(\w)/g; -const camelize$1 = cacheStringFunction$1((str) => { - return str.replace(camelizeRE$1, (_2, c) => c ? c.toUpperCase() : ""); -}); -const hyphenateRE$1 = /\B([A-Z])/g; -const hyphenate$1 = cacheStringFunction$1( - (str) => str.replace(hyphenateRE$1, "-$1").toLowerCase() -); -const capitalize$1 = cacheStringFunction$1((str) => { - return str.charAt(0).toUpperCase() + str.slice(1); -}); -const toHandlerKey = cacheStringFunction$1((str) => { - const s = str ? `on${capitalize$1(str)}` : ``; - return s; -}); -const hasChanged = /* @__PURE__ */ __name((value3, oldValue) => !Object.is(value3, oldValue), "hasChanged"); -const invokeArrayFns = /* @__PURE__ */ __name((fns, ...arg) => { - for (let i2 = 0; i2 < fns.length; i2++) { - fns[i2](...arg); - } -}, "invokeArrayFns"); -const def = /* @__PURE__ */ __name((obj, key, value3, writable = false) => { - Object.defineProperty(obj, key, { - configurable: true, - enumerable: false, - writable, - value: value3 - }); -}, "def"); -const looseToNumber = /* @__PURE__ */ __name((val) => { - const n = parseFloat(val); - return isNaN(n) ? val : n; -}, "looseToNumber"); -const toNumber = /* @__PURE__ */ __name((val) => { - const n = isString$4(val) ? Number(val) : NaN; - return isNaN(n) ? val : n; -}, "toNumber"); -let _globalThis$1; -const getGlobalThis$1 = /* @__PURE__ */ __name(() => { - return _globalThis$1 || (_globalThis$1 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); -}, "getGlobalThis$1"); -const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/; -function genPropsAccessExp(name) { - return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`; -} -__name(genPropsAccessExp, "genPropsAccessExp"); -const PatchFlags = { - "TEXT": 1, - "1": "TEXT", - "CLASS": 2, - "2": "CLASS", - "STYLE": 4, - "4": "STYLE", - "PROPS": 8, - "8": "PROPS", - "FULL_PROPS": 16, - "16": "FULL_PROPS", - "NEED_HYDRATION": 32, - "32": "NEED_HYDRATION", - "STABLE_FRAGMENT": 64, - "64": "STABLE_FRAGMENT", - "KEYED_FRAGMENT": 128, - "128": "KEYED_FRAGMENT", - "UNKEYED_FRAGMENT": 256, - "256": "UNKEYED_FRAGMENT", - "NEED_PATCH": 512, - "512": "NEED_PATCH", - "DYNAMIC_SLOTS": 1024, - "1024": "DYNAMIC_SLOTS", - "DEV_ROOT_FRAGMENT": 2048, - "2048": "DEV_ROOT_FRAGMENT", - "HOISTED": -1, - "-1": "HOISTED", - "BAIL": -2, - "-2": "BAIL" -}; -const PatchFlagNames = { - [1]: `TEXT`, - [2]: `CLASS`, - [4]: `STYLE`, - [8]: `PROPS`, - [16]: `FULL_PROPS`, - [32]: `NEED_HYDRATION`, - [64]: `STABLE_FRAGMENT`, - [128]: `KEYED_FRAGMENT`, - [256]: `UNKEYED_FRAGMENT`, - [512]: `NEED_PATCH`, - [1024]: `DYNAMIC_SLOTS`, - [2048]: `DEV_ROOT_FRAGMENT`, - [-1]: `HOISTED`, - [-2]: `BAIL` -}; -const ShapeFlags = { - "ELEMENT": 1, - "1": "ELEMENT", - "FUNCTIONAL_COMPONENT": 2, - "2": "FUNCTIONAL_COMPONENT", - "STATEFUL_COMPONENT": 4, - "4": "STATEFUL_COMPONENT", - "TEXT_CHILDREN": 8, - "8": "TEXT_CHILDREN", - "ARRAY_CHILDREN": 16, - "16": "ARRAY_CHILDREN", - "SLOTS_CHILDREN": 32, - "32": "SLOTS_CHILDREN", - "TELEPORT": 64, - "64": "TELEPORT", - "SUSPENSE": 128, - "128": "SUSPENSE", - "COMPONENT_SHOULD_KEEP_ALIVE": 256, - "256": "COMPONENT_SHOULD_KEEP_ALIVE", - "COMPONENT_KEPT_ALIVE": 512, - "512": "COMPONENT_KEPT_ALIVE", - "COMPONENT": 6, - "6": "COMPONENT" -}; -const SlotFlags = { - "STABLE": 1, - "1": "STABLE", - "DYNAMIC": 2, - "2": "DYNAMIC", - "FORWARDED": 3, - "3": "FORWARDED" -}; -const slotFlagsText = { - [1]: "STABLE", - [2]: "DYNAMIC", - [3]: "FORWARDED" -}; -const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; -const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); -const isGloballyWhitelisted = isGloballyAllowed; -const range = 2; -function generateCodeFrame$1(source, start2 = 0, end = source.length) { - start2 = Math.max(0, Math.min(start2, source.length)); - end = Math.max(0, Math.min(end, source.length)); - if (start2 > end) return ""; - let lines = source.split(/(\r?\n)/); - const newlineSequences = lines.filter((_2, idx) => idx % 2 === 1); - lines = lines.filter((_2, idx) => idx % 2 === 0); - let count = 0; - const res = []; - for (let i2 = 0; i2 < lines.length; i2++) { - count += lines[i2].length + (newlineSequences[i2] && newlineSequences[i2].length || 0); - if (count >= start2) { - for (let j = i2 - range; j <= i2 + range || end > count; j++) { - if (j < 0 || j >= lines.length) continue; - const line = j + 1; - res.push( - `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` - ); - const lineLength = lines[j].length; - const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0; - if (j === i2) { - const pad = start2 - (count - (lineLength + newLineSeqLength)); - const length = Math.max( - 1, - end > count ? lineLength - pad : end - start2 - ); - res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); - } else if (j > i2) { - if (end > count) { - const length = Math.max(Math.min(end - count, lineLength), 1); - res.push(` | ` + "^".repeat(length)); - } - count += lineLength + newLineSeqLength; - } - } - break; - } - } - return res.join("\n"); -} -__name(generateCodeFrame$1, "generateCodeFrame$1"); -function normalizeStyle(value3) { - if (isArray$3(value3)) { - const res = {}; - for (let i2 = 0; i2 < value3.length; i2++) { - const item2 = value3[i2]; - const normalized = isString$4(item2) ? parseStringStyle(item2) : normalizeStyle(item2); - if (normalized) { - for (const key in normalized) { - res[key] = normalized[key]; - } - } - } - return res; - } else if (isString$4(value3) || isObject$5(value3)) { - return value3; - } -} -__name(normalizeStyle, "normalizeStyle"); -const listDelimiterRE = /;(?![^(]*\))/g; -const propertyDelimiterRE = /:([^]+)/; -const styleCommentRE = /\/\*[^]*?\*\//g; -function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item2) => { - if (item2) { - const tmp = item2.split(propertyDelimiterRE); - tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); - } - }); - return ret; -} -__name(parseStringStyle, "parseStringStyle"); -function stringifyStyle(styles) { - let ret = ""; - if (!styles || isString$4(styles)) { - return ret; - } - for (const key in styles) { - const value3 = styles[key]; - if (isString$4(value3) || typeof value3 === "number") { - const normalizedKey = key.startsWith(`--`) ? key : hyphenate$1(key); - ret += `${normalizedKey}:${value3};`; - } - } - return ret; -} -__name(stringifyStyle, "stringifyStyle"); -function normalizeClass(value3) { - let res = ""; - if (isString$4(value3)) { - res = value3; - } else if (isArray$3(value3)) { - for (let i2 = 0; i2 < value3.length; i2++) { - const normalized = normalizeClass(value3[i2]); - if (normalized) { - res += normalized + " "; - } - } - } else if (isObject$5(value3)) { - for (const name in value3) { - if (value3[name]) { - res += name + " "; - } - } - } - return res.trim(); -} -__name(normalizeClass, "normalizeClass"); -function normalizeProps(props) { - if (!props) return null; - let { class: klass, style } = props; - if (klass && !isString$4(klass)) { - props.class = normalizeClass(klass); - } - if (style) { - props.style = normalizeStyle(style); - } - return props; -} -__name(normalizeProps, "normalizeProps"); -const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; -const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; -const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; -const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; -const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); -const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); -const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); -const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); -const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; -const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); -const isBooleanAttr = /* @__PURE__ */ makeMap( - specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` -); -function includeBooleanAttr(value3) { - return !!value3 || value3 === ""; -} -__name(includeBooleanAttr, "includeBooleanAttr"); -const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; -const attrValidationCache = {}; -function isSSRSafeAttrName(name) { - if (attrValidationCache.hasOwnProperty(name)) { - return attrValidationCache[name]; - } - const isUnsafe = unsafeAttrCharRE.test(name); - if (isUnsafe) { - console.error(`unsafe attribute name: ${name}`); - } - return attrValidationCache[name] = !isUnsafe; -} -__name(isSSRSafeAttrName, "isSSRSafeAttrName"); -const propsToAttrMap = { - acceptCharset: "accept-charset", - className: "class", - htmlFor: "for", - httpEquiv: "http-equiv" -}; -const isKnownHtmlAttr = /* @__PURE__ */ makeMap( - `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` -); -const isKnownSvgAttr = /* @__PURE__ */ makeMap( - `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` -); -function isRenderableAttrValue(value3) { - if (value3 == null) { - return false; - } - const type = typeof value3; - return type === "string" || type === "number" || type === "boolean"; -} -__name(isRenderableAttrValue, "isRenderableAttrValue"); -const escapeRE = /["'&<>]/; -function escapeHtml$1(string) { - const str = "" + string; - const match = escapeRE.exec(str); - if (!match) { - return str; - } - let html = ""; - let escaped; - let index2; - let lastIndex = 0; - for (index2 = match.index; index2 < str.length; index2++) { - switch (str.charCodeAt(index2)) { - case 34: - escaped = """; - break; - case 38: - escaped = "&"; - break; - case 39: - escaped = "'"; - break; - case 60: - escaped = "<"; - break; - case 62: - escaped = ">"; - break; - default: - continue; - } - if (lastIndex !== index2) { - html += str.slice(lastIndex, index2); - } - lastIndex = index2 + 1; - html += escaped; - } - return lastIndex !== index2 ? html + str.slice(lastIndex, index2) : html; -} -__name(escapeHtml$1, "escapeHtml$1"); -const commentStripRE = /^-?>||--!>| looseEqual(item2, val)); -} -__name(looseIndexOf, "looseIndexOf"); -const isRef$1 = /* @__PURE__ */ __name((val) => { - return !!(val && val.__v_isRef === true); -}, "isRef$1"); -const toDisplayString$1 = /* @__PURE__ */ __name((val) => { - return isString$4(val) ? val : val == null ? "" : isArray$3(val) || isObject$5(val) && (val.toString === objectToString$1 || !isFunction$3(val.toString)) ? isRef$1(val) ? toDisplayString$1(val.value) : JSON.stringify(val, replacer, 2) : String(val); -}, "toDisplayString$1"); -const replacer = /* @__PURE__ */ __name((_key, val) => { - if (isRef$1(val)) { - return replacer(_key, val.value); - } else if (isMap(val)) { - return { - [`Map(${val.size})`]: [...val.entries()].reduce( - (entries, [key, val2], i2) => { - entries[stringifySymbol(key, i2) + " =>"] = val2; - return entries; - }, - {} - ) - }; - } else if (isSet(val)) { - return { - [`Set(${val.size})`]: [...val.values()].map((v2) => stringifySymbol(v2)) - }; - } else if (isSymbol$1(val)) { - return stringifySymbol(val); - } else if (isObject$5(val) && !isArray$3(val) && !isPlainObject$2(val)) { - return String(val); - } - return val; -}, "replacer"); -const stringifySymbol = /* @__PURE__ */ __name((v2, i2 = "") => { - var _a2; - return ( - // Symbol.description in es2019+ so we need to cast here to pass - // the lib: es2016 check - isSymbol$1(v2) ? `Symbol(${(_a2 = v2.description) != null ? _a2 : i2})` : v2 - ); -}, "stringifySymbol"); -/** -* @vue/reactivity v3.4.31 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -function warn$3(msg, ...args) { - console.warn(`[Vue warn] ${msg}`, ...args); -} -__name(warn$3, "warn$3"); -let activeEffectScope; -const _EffectScope = class _EffectScope { - constructor(detached = false) { - this.detached = detached; - this._active = true; - this.effects = []; - this.cleanups = []; - this.parent = activeEffectScope; - if (!detached && activeEffectScope) { - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( - this - ) - 1; - } - } - get active() { - return this._active; - } - run(fn) { - if (this._active) { - const currentEffectScope = activeEffectScope; - try { - activeEffectScope = this; - return fn(); - } finally { - activeEffectScope = currentEffectScope; - } - } else if (false) { - warn$3(`cannot run an inactive effect scope.`); - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - on() { - activeEffectScope = this; - } - /** - * This should only be called on non-detached scopes - * @internal - */ - off() { - activeEffectScope = this.parent; - } - stop(fromParent) { - if (this._active) { - let i2, l; - for (i2 = 0, l = this.effects.length; i2 < l; i2++) { - this.effects[i2].stop(); - } - for (i2 = 0, l = this.cleanups.length; i2 < l; i2++) { - this.cleanups[i2](); - } - if (this.scopes) { - for (i2 = 0, l = this.scopes.length; i2 < l; i2++) { - this.scopes[i2].stop(true); - } - } - if (!this.detached && this.parent && !fromParent) { - const last = this.parent.scopes.pop(); - if (last && last !== this) { - this.parent.scopes[this.index] = last; - last.index = this.index; - } - } - this.parent = void 0; - this._active = false; - } - } -}; -__name(_EffectScope, "EffectScope"); -let EffectScope = _EffectScope; -function effectScope(detached) { - return new EffectScope(detached); -} -__name(effectScope, "effectScope"); -function recordEffectScope(effect2, scope = activeEffectScope) { - if (scope && scope.active) { - scope.effects.push(effect2); - } -} -__name(recordEffectScope, "recordEffectScope"); -function getCurrentScope() { - return activeEffectScope; -} -__name(getCurrentScope, "getCurrentScope"); -function onScopeDispose(fn) { - if (activeEffectScope) { - activeEffectScope.cleanups.push(fn); - } else if (false) { - warn$3( - `onScopeDispose() is called when there is no active effect scope to be associated with.` - ); - } -} -__name(onScopeDispose, "onScopeDispose"); -let activeEffect; -const _ReactiveEffect = class _ReactiveEffect { - constructor(fn, trigger2, scheduler, scope) { - this.fn = fn; - this.trigger = trigger2; - this.scheduler = scheduler; - this.active = true; - this.deps = []; - this._dirtyLevel = 4; - this._trackId = 0; - this._runnings = 0; - this._shouldSchedule = false; - this._depsLength = 0; - recordEffectScope(this, scope); - } - get dirty() { - if (this._dirtyLevel === 2 || this._dirtyLevel === 3) { - this._dirtyLevel = 1; - pauseTracking(); - for (let i2 = 0; i2 < this._depsLength; i2++) { - const dep = this.deps[i2]; - if (dep.computed) { - triggerComputed(dep.computed); - if (this._dirtyLevel >= 4) { - break; - } - } - } - if (this._dirtyLevel === 1) { - this._dirtyLevel = 0; - } - resetTracking(); - } - return this._dirtyLevel >= 4; - } - set dirty(v2) { - this._dirtyLevel = v2 ? 4 : 0; - } - run() { - this._dirtyLevel = 0; - if (!this.active) { - return this.fn(); - } - let lastShouldTrack = shouldTrack; - let lastEffect = activeEffect; - try { - shouldTrack = true; - activeEffect = this; - this._runnings++; - preCleanupEffect(this); - return this.fn(); - } finally { - postCleanupEffect(this); - this._runnings--; - activeEffect = lastEffect; - shouldTrack = lastShouldTrack; - } - } - stop() { - if (this.active) { - preCleanupEffect(this); - postCleanupEffect(this); - this.onStop && this.onStop(); - this.active = false; - } - } -}; -__name(_ReactiveEffect, "ReactiveEffect"); -let ReactiveEffect = _ReactiveEffect; -function triggerComputed(computed2) { - return computed2.value; -} -__name(triggerComputed, "triggerComputed"); -function preCleanupEffect(effect2) { - effect2._trackId++; - effect2._depsLength = 0; -} -__name(preCleanupEffect, "preCleanupEffect"); -function postCleanupEffect(effect2) { - if (effect2.deps.length > effect2._depsLength) { - for (let i2 = effect2._depsLength; i2 < effect2.deps.length; i2++) { - cleanupDepEffect(effect2.deps[i2], effect2); - } - effect2.deps.length = effect2._depsLength; - } -} -__name(postCleanupEffect, "postCleanupEffect"); -function cleanupDepEffect(dep, effect2) { - const trackId = dep.get(effect2); - if (trackId !== void 0 && effect2._trackId !== trackId) { - dep.delete(effect2); - if (dep.size === 0) { - dep.cleanup(); - } - } -} -__name(cleanupDepEffect, "cleanupDepEffect"); -function effect(fn, options3) { - if (fn.effect instanceof ReactiveEffect) { - fn = fn.effect.fn; - } - const _effect = new ReactiveEffect(fn, NOOP, () => { - if (_effect.dirty) { - _effect.run(); - } - }); - if (options3) { - extend(_effect, options3); - if (options3.scope) recordEffectScope(_effect, options3.scope); - } - if (!options3 || !options3.lazy) { - _effect.run(); - } - const runner = _effect.run.bind(_effect); - runner.effect = _effect; - return runner; -} -__name(effect, "effect"); -function stop(runner) { - runner.effect.stop(); -} -__name(stop, "stop"); -let shouldTrack = true; -let pauseScheduleStack = 0; -const trackStack = []; -function pauseTracking() { - trackStack.push(shouldTrack); - shouldTrack = false; -} -__name(pauseTracking, "pauseTracking"); -function enableTracking() { - trackStack.push(shouldTrack); - shouldTrack = true; -} -__name(enableTracking, "enableTracking"); -function resetTracking() { - const last = trackStack.pop(); - shouldTrack = last === void 0 ? true : last; -} -__name(resetTracking, "resetTracking"); -function pauseScheduling() { - pauseScheduleStack++; -} -__name(pauseScheduling, "pauseScheduling"); -function resetScheduling() { - pauseScheduleStack--; - while (!pauseScheduleStack && queueEffectSchedulers.length) { - queueEffectSchedulers.shift()(); - } -} -__name(resetScheduling, "resetScheduling"); -function trackEffect(effect2, dep, debuggerEventExtraInfo) { - var _a2; - if (dep.get(effect2) !== effect2._trackId) { - dep.set(effect2, effect2._trackId); - const oldDep = effect2.deps[effect2._depsLength]; - if (oldDep !== dep) { - if (oldDep) { - cleanupDepEffect(oldDep, effect2); - } - effect2.deps[effect2._depsLength++] = dep; - } else { - effect2._depsLength++; - } - if (false) { - (_a2 = effect2.onTrack) == null ? void 0 : _a2.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); - } - } -} -__name(trackEffect, "trackEffect"); -const queueEffectSchedulers = []; -function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) { - var _a2; - pauseScheduling(); - for (const effect2 of dep.keys()) { - let tracking; - if (effect2._dirtyLevel < dirtyLevel && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { - effect2._shouldSchedule || (effect2._shouldSchedule = effect2._dirtyLevel === 0); - effect2._dirtyLevel = dirtyLevel; - } - if (effect2._shouldSchedule && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { - if (false) { - (_a2 = effect2.onTrigger) == null ? void 0 : _a2.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); - } - effect2.trigger(); - if ((!effect2._runnings || effect2.allowRecurse) && effect2._dirtyLevel !== 2) { - effect2._shouldSchedule = false; - if (effect2.scheduler) { - queueEffectSchedulers.push(effect2.scheduler); - } - } - } - } - resetScheduling(); -} -__name(triggerEffects, "triggerEffects"); -const createDep = /* @__PURE__ */ __name((cleanup, computed2) => { - const dep = /* @__PURE__ */ new Map(); - dep.cleanup = cleanup; - dep.computed = computed2; - return dep; -}, "createDep"); -const targetMap = /* @__PURE__ */ new WeakMap(); -const ITERATE_KEY = Symbol(false ? "iterate" : ""); -const MAP_KEY_ITERATE_KEY = Symbol(false ? "Map key iterate" : ""); -function track(target, type, key) { - if (shouldTrack && activeEffect) { - let depsMap = targetMap.get(target); - if (!depsMap) { - targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); - } - let dep = depsMap.get(key); - if (!dep) { - depsMap.set(key, dep = createDep(() => depsMap.delete(key))); - } - trackEffect( - activeEffect, - dep, - false ? { - target, - type, - key - } : void 0 - ); - } -} -__name(track, "track"); -function trigger(target, type, key, newValue, oldValue, oldTarget) { - const depsMap = targetMap.get(target); - if (!depsMap) { - return; - } - let deps = []; - if (type === "clear") { - deps = [...depsMap.values()]; - } else if (key === "length" && isArray$3(target)) { - const newLength = Number(newValue); - depsMap.forEach((dep, key2) => { - if (key2 === "length" || !isSymbol$1(key2) && key2 >= newLength) { - deps.push(dep); - } - }); - } else { - if (key !== void 0) { - deps.push(depsMap.get(key)); - } - switch (type) { - case "add": - if (!isArray$3(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { - deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } else if (isIntegerKey(key)) { - deps.push(depsMap.get("length")); - } - break; - case "delete": - if (!isArray$3(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { - deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } - break; - case "set": - if (isMap(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - } - break; - } - } - pauseScheduling(); - for (const dep of deps) { - if (dep) { - triggerEffects( - dep, - 4, - false ? { - target, - type, - key, - newValue, - oldValue, - oldTarget - } : void 0 - ); - } - } - resetScheduling(); -} -__name(trigger, "trigger"); -function getDepFromReactive(object, key) { - const depsMap = targetMap.get(object); - return depsMap && depsMap.get(key); -} -__name(getDepFromReactive, "getDepFromReactive"); -const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); -const builtInSymbols = new Set( - /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol$1) -); -const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations(); -function createArrayInstrumentations() { - const instrumentations = {}; - ["includes", "indexOf", "lastIndexOf"].forEach((key) => { - instrumentations[key] = function(...args) { - const arr = toRaw(this); - for (let i2 = 0, l = this.length; i2 < l; i2++) { - track(arr, "get", i2 + ""); - } - const res = arr[key](...args); - if (res === -1 || res === false) { - return arr[key](...args.map(toRaw)); - } else { - return res; - } - }; - }); - ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { - instrumentations[key] = function(...args) { - pauseTracking(); - pauseScheduling(); - const res = toRaw(this)[key].apply(this, args); - resetScheduling(); - resetTracking(); - return res; - }; - }); - return instrumentations; -} -__name(createArrayInstrumentations, "createArrayInstrumentations"); -function hasOwnProperty$1(key) { - if (!isSymbol$1(key)) key = String(key); - const obj = toRaw(this); - track(obj, "has", key); - return obj.hasOwnProperty(key); -} -__name(hasOwnProperty$1, "hasOwnProperty$1"); -const _BaseReactiveHandler = class _BaseReactiveHandler { - constructor(_isReadonly = false, _isShallow = false) { - this._isReadonly = _isReadonly; - this._isShallow = _isShallow; - } - get(target, key, receiver) { - const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return isShallow2; - } else if (key === "__v_raw") { - if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype - // this means the reciever is a user proxy of the reactive proxy - Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { - return target; - } - return; - } - const targetIsArray = isArray$3(target); - if (!isReadonly2) { - if (targetIsArray && hasOwn$3(arrayInstrumentations, key)) { - return Reflect.get(arrayInstrumentations, key, receiver); - } - if (key === "hasOwnProperty") { - return hasOwnProperty$1; - } - } - const res = Reflect.get(target, key, receiver); - if (isSymbol$1(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { - return res; - } - if (!isReadonly2) { - track(target, "get", key); - } - if (isShallow2) { - return res; - } - if (isRef(res)) { - return targetIsArray && isIntegerKey(key) ? res : res.value; - } - if (isObject$5(res)) { - return isReadonly2 ? readonly(res) : reactive(res); - } - return res; - } -}; -__name(_BaseReactiveHandler, "BaseReactiveHandler"); -let BaseReactiveHandler = _BaseReactiveHandler; -const _MutableReactiveHandler = class _MutableReactiveHandler extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(false, isShallow2); - } - set(target, key, value3, receiver) { - let oldValue = target[key]; - if (!this._isShallow) { - const isOldValueReadonly = isReadonly(oldValue); - if (!isShallow(value3) && !isReadonly(value3)) { - oldValue = toRaw(oldValue); - value3 = toRaw(value3); - } - if (!isArray$3(target) && isRef(oldValue) && !isRef(value3)) { - if (isOldValueReadonly) { - return false; - } else { - oldValue.value = value3; - return true; - } - } - } - const hadKey = isArray$3(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn$3(target, key); - const result = Reflect.set(target, key, value3, receiver); - if (target === toRaw(receiver)) { - if (!hadKey) { - trigger(target, "add", key, value3); - } else if (hasChanged(value3, oldValue)) { - trigger(target, "set", key, value3, oldValue); - } - } - return result; - } - deleteProperty(target, key) { - const hadKey = hasOwn$3(target, key); - const oldValue = target[key]; - const result = Reflect.deleteProperty(target, key); - if (result && hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; - } - has(target, key) { - const result = Reflect.has(target, key); - if (!isSymbol$1(key) || !builtInSymbols.has(key)) { - track(target, "has", key); - } - return result; - } - ownKeys(target) { - track( - target, - "iterate", - isArray$3(target) ? "length" : ITERATE_KEY - ); - return Reflect.ownKeys(target); - } -}; -__name(_MutableReactiveHandler, "MutableReactiveHandler"); -let MutableReactiveHandler = _MutableReactiveHandler; -const _ReadonlyReactiveHandler = class _ReadonlyReactiveHandler extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(true, isShallow2); - } - set(target, key) { - if (false) { - warn$3( - `Set operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - } - deleteProperty(target, key) { - if (false) { - warn$3( - `Delete operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - } -}; -__name(_ReadonlyReactiveHandler, "ReadonlyReactiveHandler"); -let ReadonlyReactiveHandler = _ReadonlyReactiveHandler; -const mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); -const readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); -const shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler( - true -); -const shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); -const toShallow = /* @__PURE__ */ __name((value3) => value3, "toShallow"); -const getProto = /* @__PURE__ */ __name((v2) => Reflect.getPrototypeOf(v2), "getProto"); -function get$2(target, key, isReadonly2 = false, isShallow2 = false) { - target = target["__v_raw"]; - const rawTarget = toRaw(target); - const rawKey = toRaw(key); - if (!isReadonly2) { - if (hasChanged(key, rawKey)) { - track(rawTarget, "get", key); - } - track(rawTarget, "get", rawKey); - } - const { has: has2 } = getProto(rawTarget); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; - if (has2.call(rawTarget, key)) { - return wrap(target.get(key)); - } else if (has2.call(rawTarget, rawKey)) { - return wrap(target.get(rawKey)); - } else if (target !== rawTarget) { - target.get(key); - } -} -__name(get$2, "get$2"); -function has(key, isReadonly2 = false) { - const target = this["__v_raw"]; - const rawTarget = toRaw(target); - const rawKey = toRaw(key); - if (!isReadonly2) { - if (hasChanged(key, rawKey)) { - track(rawTarget, "has", key); - } - track(rawTarget, "has", rawKey); - } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); -} -__name(has, "has"); -function size(target, isReadonly2 = false) { - target = target["__v_raw"]; - !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY); - return Reflect.get(target, "size", target); -} -__name(size, "size"); -function add(value3) { - value3 = toRaw(value3); - const target = toRaw(this); - const proto = getProto(target); - const hadKey = proto.has.call(target, value3); - if (!hadKey) { - target.add(value3); - trigger(target, "add", value3, value3); - } - return this; -} -__name(add, "add"); -function set$4(key, value3) { - value3 = toRaw(value3); - const target = toRaw(this); - const { has: has2, get: get2 } = getProto(target); - let hadKey = has2.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has2.call(target, key); - } else if (false) { - checkIdentityKeys(target, has2, key); - } - const oldValue = get2.call(target, key); - target.set(key, value3); - if (!hadKey) { - trigger(target, "add", key, value3); - } else if (hasChanged(value3, oldValue)) { - trigger(target, "set", key, value3, oldValue); - } - return this; -} -__name(set$4, "set$4"); -function deleteEntry(key) { - const target = toRaw(this); - const { has: has2, get: get2 } = getProto(target); - let hadKey = has2.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has2.call(target, key); - } else if (false) { - checkIdentityKeys(target, has2, key); - } - const oldValue = get2 ? get2.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; -} -__name(deleteEntry, "deleteEntry"); -function clear() { - const target = toRaw(this); - const hadItems = target.size !== 0; - const oldTarget = false ? isMap(target) ? new Map(target) : new Set(target) : void 0; - const result = target.clear(); - if (hadItems) { - trigger(target, "clear", void 0, void 0, oldTarget); - } - return result; -} -__name(clear, "clear"); -function createForEach(isReadonly2, isShallow2) { - return /* @__PURE__ */ __name(function forEach(callback, thisArg) { - const observed = this; - const target = observed["__v_raw"]; - const rawTarget = toRaw(target); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; - !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); - return target.forEach((value3, key) => { - return callback.call(thisArg, wrap(value3), wrap(key), observed); - }); - }, "forEach"); -} -__name(createForEach, "createForEach"); -function createIterableMethod(method, isReadonly2, isShallow2) { - return function(...args) { - const target = this["__v_raw"]; - const rawTarget = toRaw(target); - const targetIsMap = isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; - const innerIterator = target[method](...args); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive$1; - !isReadonly2 && track( - rawTarget, - "iterate", - isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY - ); - return { - // iterator protocol - next() { - const { value: value3, done } = innerIterator.next(); - return done ? { value: value3, done } : { - value: isPair ? [wrap(value3[0]), wrap(value3[1])] : wrap(value3), - done - }; - }, - // iterable protocol - [Symbol.iterator]() { - return this; - } - }; - }; -} -__name(createIterableMethod, "createIterableMethod"); -function createReadonlyMethod(type) { - return function(...args) { - if (false) { - const key = args[0] ? `on key "${args[0]}" ` : ``; - warn$3( - `${capitalize$1(type)} operation ${key}failed: target is readonly.`, - toRaw(this) - ); - } - return type === "delete" ? false : type === "clear" ? void 0 : this; - }; -} -__name(createReadonlyMethod, "createReadonlyMethod"); -function createInstrumentations() { - const mutableInstrumentations2 = { - get(key) { - return get$2(this, key); - }, - get size() { - return size(this); - }, - has, - add, - set: set$4, - delete: deleteEntry, - clear, - forEach: createForEach(false, false) - }; - const shallowInstrumentations2 = { - get(key) { - return get$2(this, key, false, true); - }, - get size() { - return size(this); - }, - has, - add, - set: set$4, - delete: deleteEntry, - clear, - forEach: createForEach(false, true) - }; - const readonlyInstrumentations2 = { - get(key) { - return get$2(this, key, true); - }, - get size() { - return size(this, true); - }, - has(key) { - return has.call(this, key, true); - }, - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear"), - forEach: createForEach(true, false) - }; - const shallowReadonlyInstrumentations2 = { - get(key) { - return get$2(this, key, true, true); - }, - get size() { - return size(this, true); - }, - has(key) { - return has.call(this, key, true); - }, - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear"), - forEach: createForEach(true, true) - }; - const iteratorMethods = [ - "keys", - "values", - "entries", - Symbol.iterator - ]; - iteratorMethods.forEach((method) => { - mutableInstrumentations2[method] = createIterableMethod(method, false, false); - readonlyInstrumentations2[method] = createIterableMethod(method, true, false); - shallowInstrumentations2[method] = createIterableMethod(method, false, true); - shallowReadonlyInstrumentations2[method] = createIterableMethod( - method, - true, - true - ); - }); - return [ - mutableInstrumentations2, - readonlyInstrumentations2, - shallowInstrumentations2, - shallowReadonlyInstrumentations2 - ]; -} -__name(createInstrumentations, "createInstrumentations"); -const [ - mutableInstrumentations, - readonlyInstrumentations, - shallowInstrumentations, - shallowReadonlyInstrumentations -] = /* @__PURE__ */ createInstrumentations(); -function createInstrumentationGetter(isReadonly2, shallow) { - const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; - return (target, key, receiver) => { - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_raw") { - return target; - } - return Reflect.get( - hasOwn$3(instrumentations, key) && key in target ? instrumentations : target, - key, - receiver - ); - }; -} -__name(createInstrumentationGetter, "createInstrumentationGetter"); -const mutableCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, false) -}; -const shallowCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, true) -}; -const readonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, false) -}; -const shallowReadonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, true) -}; -function checkIdentityKeys(target, has2, key) { - const rawKey = toRaw(key); - if (rawKey !== key && has2.call(target, rawKey)) { - const type = toRawType(target); - warn$3( - `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` - ); - } -} -__name(checkIdentityKeys, "checkIdentityKeys"); -const reactiveMap = /* @__PURE__ */ new WeakMap(); -const shallowReactiveMap = /* @__PURE__ */ new WeakMap(); -const readonlyMap = /* @__PURE__ */ new WeakMap(); -const shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); -function targetTypeMap(rawType) { - switch (rawType) { - case "Object": - case "Array": - return 1; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": - return 2; - default: - return 0; - } -} -__name(targetTypeMap, "targetTypeMap"); -function getTargetType(value3) { - return value3["__v_skip"] || !Object.isExtensible(value3) ? 0 : targetTypeMap(toRawType(value3)); -} -__name(getTargetType, "getTargetType"); -function reactive(target) { - if (isReadonly(target)) { - return target; - } - return createReactiveObject( - target, - false, - mutableHandlers, - mutableCollectionHandlers, - reactiveMap - ); -} -__name(reactive, "reactive"); -function shallowReactive(target) { - return createReactiveObject( - target, - false, - shallowReactiveHandlers, - shallowCollectionHandlers, - shallowReactiveMap - ); -} -__name(shallowReactive, "shallowReactive"); -function readonly(target) { - return createReactiveObject( - target, - true, - readonlyHandlers, - readonlyCollectionHandlers, - readonlyMap - ); -} -__name(readonly, "readonly"); -function shallowReadonly(target) { - return createReactiveObject( - target, - true, - shallowReadonlyHandlers, - shallowReadonlyCollectionHandlers, - shallowReadonlyMap - ); -} -__name(shallowReadonly, "shallowReadonly"); -function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { - if (!isObject$5(target)) { - if (false) { - warn$3( - `value cannot be made ${isReadonly2 ? "readonly" : "reactive"}: ${String( - target - )}` - ); - } - return target; - } - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { - return target; - } - const existingProxy = proxyMap.get(target); - if (existingProxy) { - return existingProxy; - } - const targetType = getTargetType(target); - if (targetType === 0) { - return target; - } - const proxy = new Proxy( - target, - targetType === 2 ? collectionHandlers : baseHandlers - ); - proxyMap.set(target, proxy); - return proxy; -} -__name(createReactiveObject, "createReactiveObject"); -function isReactive(value3) { - if (isReadonly(value3)) { - return isReactive(value3["__v_raw"]); - } - return !!(value3 && value3["__v_isReactive"]); -} -__name(isReactive, "isReactive"); -function isReadonly(value3) { - return !!(value3 && value3["__v_isReadonly"]); -} -__name(isReadonly, "isReadonly"); -function isShallow(value3) { - return !!(value3 && value3["__v_isShallow"]); -} -__name(isShallow, "isShallow"); -function isProxy(value3) { - return value3 ? !!value3["__v_raw"] : false; -} -__name(isProxy, "isProxy"); -function toRaw(observed) { - const raw = observed && observed["__v_raw"]; - return raw ? toRaw(raw) : observed; -} -__name(toRaw, "toRaw"); -function markRaw(value3) { - if (Object.isExtensible(value3)) { - def(value3, "__v_skip", true); - } - return value3; -} -__name(markRaw, "markRaw"); -const toReactive$1 = /* @__PURE__ */ __name((value3) => isObject$5(value3) ? reactive(value3) : value3, "toReactive$1"); -const toReadonly = /* @__PURE__ */ __name((value3) => isObject$5(value3) ? readonly(value3) : value3, "toReadonly"); -const COMPUTED_SIDE_EFFECT_WARN = `Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter. State mutations in computed getters should be avoided. Check the docs for more details: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free`; -const _ComputedRefImpl = class _ComputedRefImpl { - constructor(getter, _setter, isReadonly2, isSSR) { - this.getter = getter; - this._setter = _setter; - this.dep = void 0; - this.__v_isRef = true; - this["__v_isReadonly"] = false; - this.effect = new ReactiveEffect( - () => getter(this._value), - () => triggerRefValue( - this, - this.effect._dirtyLevel === 2 ? 2 : 3 - ) - ); - this.effect.computed = this; - this.effect.active = this._cacheable = !isSSR; - this["__v_isReadonly"] = isReadonly2; - } - get value() { - const self2 = toRaw(this); - if ((!self2._cacheable || self2.effect.dirty) && hasChanged(self2._value, self2._value = self2.effect.run())) { - triggerRefValue(self2, 4); - } - trackRefValue(self2); - if (self2.effect._dirtyLevel >= 2) { - if (false) { - warn$3(COMPUTED_SIDE_EFFECT_WARN, ` - -getter: `, this.getter); - } - triggerRefValue(self2, 2); - } - return self2._value; - } - set value(newValue) { - this._setter(newValue); - } - // #region polyfill _dirty for backward compatibility third party code for Vue <= 3.3.x - get _dirty() { - return this.effect.dirty; - } - set _dirty(v2) { - this.effect.dirty = v2; - } - // #endregion -}; -__name(_ComputedRefImpl, "ComputedRefImpl"); -let ComputedRefImpl = _ComputedRefImpl; -function computed$1(getterOrOptions, debugOptions, isSSR = false) { - let getter; - let setter; - const onlyGetter = isFunction$3(getterOrOptions); - if (onlyGetter) { - getter = getterOrOptions; - setter = false ? () => { - warn$3("Write operation failed: computed value is readonly"); - } : NOOP; - } else { - getter = getterOrOptions.get; - setter = getterOrOptions.set; - } - const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); - if (false) { - cRef.effect.onTrack = debugOptions.onTrack; - cRef.effect.onTrigger = debugOptions.onTrigger; - } - return cRef; -} -__name(computed$1, "computed$1"); -function trackRefValue(ref2) { - var _a2; - if (shouldTrack && activeEffect) { - ref2 = toRaw(ref2); - trackEffect( - activeEffect, - (_a2 = ref2.dep) != null ? _a2 : ref2.dep = createDep( - () => ref2.dep = void 0, - ref2 instanceof ComputedRefImpl ? ref2 : void 0 - ), - false ? { - target: ref2, - type: "get", - key: "value" - } : void 0 - ); - } -} -__name(trackRefValue, "trackRefValue"); -function triggerRefValue(ref2, dirtyLevel = 4, newVal, oldVal) { - ref2 = toRaw(ref2); - const dep = ref2.dep; - if (dep) { - triggerEffects( - dep, - dirtyLevel, - false ? { - target: ref2, - type: "set", - key: "value", - newValue: newVal, - oldValue: oldVal - } : void 0 - ); - } -} -__name(triggerRefValue, "triggerRefValue"); -function isRef(r) { - return !!(r && r.__v_isRef === true); -} -__name(isRef, "isRef"); -function ref(value3) { - return createRef(value3, false); -} -__name(ref, "ref"); -function shallowRef(value3) { - return createRef(value3, true); -} -__name(shallowRef, "shallowRef"); -function createRef(rawValue, shallow) { - if (isRef(rawValue)) { - return rawValue; - } - return new RefImpl(rawValue, shallow); -} -__name(createRef, "createRef"); -const _RefImpl = class _RefImpl { - constructor(value3, __v_isShallow) { - this.__v_isShallow = __v_isShallow; - this.dep = void 0; - this.__v_isRef = true; - this._rawValue = __v_isShallow ? value3 : toRaw(value3); - this._value = __v_isShallow ? value3 : toReactive$1(value3); - } - get value() { - trackRefValue(this); - return this._value; - } - set value(newVal) { - const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal); - newVal = useDirectValue ? newVal : toRaw(newVal); - if (hasChanged(newVal, this._rawValue)) { - const oldVal = this._rawValue; - this._rawValue = newVal; - this._value = useDirectValue ? newVal : toReactive$1(newVal); - triggerRefValue(this, 4, newVal, oldVal); - } - } -}; -__name(_RefImpl, "RefImpl"); -let RefImpl = _RefImpl; -function triggerRef(ref2) { - triggerRefValue(ref2, 4, false ? ref2.value : void 0); -} -__name(triggerRef, "triggerRef"); -function unref(ref2) { - return isRef(ref2) ? ref2.value : ref2; -} -__name(unref, "unref"); -function toValue$2(source) { - return isFunction$3(source) ? source() : unref(source); -} -__name(toValue$2, "toValue$2"); -const shallowUnwrapHandlers = { - get: /* @__PURE__ */ __name((target, key, receiver) => unref(Reflect.get(target, key, receiver)), "get"), - set: /* @__PURE__ */ __name((target, key, value3, receiver) => { - const oldValue = target[key]; - if (isRef(oldValue) && !isRef(value3)) { - oldValue.value = value3; - return true; - } else { - return Reflect.set(target, key, value3, receiver); - } - }, "set") -}; -function proxyRefs(objectWithRefs) { - return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); -} -__name(proxyRefs, "proxyRefs"); -const _CustomRefImpl = class _CustomRefImpl { - constructor(factory) { - this.dep = void 0; - this.__v_isRef = true; - const { get: get2, set: set2 } = factory( - () => trackRefValue(this), - () => triggerRefValue(this) - ); - this._get = get2; - this._set = set2; - } - get value() { - return this._get(); - } - set value(newVal) { - this._set(newVal); - } -}; -__name(_CustomRefImpl, "CustomRefImpl"); -let CustomRefImpl = _CustomRefImpl; -function customRef(factory) { - return new CustomRefImpl(factory); -} -__name(customRef, "customRef"); -function toRefs$1(object) { - if (false) { - warn$3(`toRefs() expects a reactive object but received a plain one.`); - } - const ret = isArray$3(object) ? new Array(object.length) : {}; - for (const key in object) { - ret[key] = propertyToRef(object, key); - } - return ret; -} -__name(toRefs$1, "toRefs$1"); -const _ObjectRefImpl = class _ObjectRefImpl { - constructor(_object, _key, _defaultValue) { - this._object = _object; - this._key = _key; - this._defaultValue = _defaultValue; - this.__v_isRef = true; - } - get value() { - const val = this._object[this._key]; - return val === void 0 ? this._defaultValue : val; - } - set value(newVal) { - this._object[this._key] = newVal; - } - get dep() { - return getDepFromReactive(toRaw(this._object), this._key); - } -}; -__name(_ObjectRefImpl, "ObjectRefImpl"); -let ObjectRefImpl = _ObjectRefImpl; -const _GetterRefImpl = class _GetterRefImpl { - constructor(_getter) { - this._getter = _getter; - this.__v_isRef = true; - this.__v_isReadonly = true; - } - get value() { - return this._getter(); - } -}; -__name(_GetterRefImpl, "GetterRefImpl"); -let GetterRefImpl = _GetterRefImpl; -function toRef$1(source, key, defaultValue) { - if (isRef(source)) { - return source; - } else if (isFunction$3(source)) { - return new GetterRefImpl(source); - } else if (isObject$5(source) && arguments.length > 1) { - return propertyToRef(source, key, defaultValue); - } else { - return ref(source); - } -} -__name(toRef$1, "toRef$1"); -function propertyToRef(source, key, defaultValue) { - const val = source[key]; - return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue); -} -__name(propertyToRef, "propertyToRef"); -const deferredComputed = computed$1; -const TrackOpTypes = { - "GET": "get", - "HAS": "has", - "ITERATE": "iterate" -}; -const TriggerOpTypes = { - "SET": "set", - "ADD": "add", - "DELETE": "delete", - "CLEAR": "clear" -}; -const ReactiveFlags = { - "SKIP": "__v_skip", - "IS_REACTIVE": "__v_isReactive", - "IS_READONLY": "__v_isReadonly", - "IS_SHALLOW": "__v_isShallow", - "RAW": "__v_raw" -}; -/** -* @vue/runtime-core v3.4.31 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -const stack = []; -function pushWarningContext(vnode) { - stack.push(vnode); -} -__name(pushWarningContext, "pushWarningContext"); -function popWarningContext() { - stack.pop(); -} -__name(popWarningContext, "popWarningContext"); -function warn$1(msg, ...args) { - pauseTracking(); - const instance = stack.length ? stack[stack.length - 1].component : null; - const appWarnHandler = instance && instance.appContext.config.warnHandler; - const trace = getComponentTrace(); - if (appWarnHandler) { - callWithErrorHandling( - appWarnHandler, - instance, - 11, - [ - // eslint-disable-next-line no-restricted-syntax - msg + args.map((a) => { - var _a2, _b2; - return (_b2 = (_a2 = a.toString) == null ? void 0 : _a2.call(a)) != null ? _b2 : JSON.stringify(a); - }).join(""), - instance && instance.proxy, - trace.map( - ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` - ).join("\n"), - trace - ] - ); - } else { - const warnArgs = [`[Vue warn]: ${msg}`, ...args]; - if (trace.length && // avoid spamming console during tests - true) { - warnArgs.push(` -`, ...formatTrace(trace)); - } - console.warn(...warnArgs); - } - resetTracking(); -} -__name(warn$1, "warn$1"); -function getComponentTrace() { - let currentVNode = stack[stack.length - 1]; - if (!currentVNode) { - return []; - } - const normalizedStack = []; - while (currentVNode) { - const last = normalizedStack[0]; - if (last && last.vnode === currentVNode) { - last.recurseCount++; - } else { - normalizedStack.push({ - vnode: currentVNode, - recurseCount: 0 - }); - } - const parentInstance = currentVNode.component && currentVNode.component.parent; - currentVNode = parentInstance && parentInstance.vnode; - } - return normalizedStack; -} -__name(getComponentTrace, "getComponentTrace"); -function formatTrace(trace) { - const logs = []; - trace.forEach((entry, i2) => { - logs.push(...i2 === 0 ? [] : [` -`], ...formatTraceEntry(entry)); - }); - return logs; -} -__name(formatTrace, "formatTrace"); -function formatTraceEntry({ vnode, recurseCount }) { - const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; - const isRoot = vnode.component ? vnode.component.parent == null : false; - const open2 = ` at <${formatComponentName( - vnode.component, - vnode.type, - isRoot - )}`; - const close4 = `>` + postfix; - return vnode.props ? [open2, ...formatProps(vnode.props), close4] : [open2 + close4]; -} -__name(formatTraceEntry, "formatTraceEntry"); -function formatProps(props) { - const res = []; - const keys2 = Object.keys(props); - keys2.slice(0, 3).forEach((key) => { - res.push(...formatProp(key, props[key])); - }); - if (keys2.length > 3) { - res.push(` ...`); - } - return res; -} -__name(formatProps, "formatProps"); -function formatProp(key, value3, raw) { - if (isString$4(value3)) { - value3 = JSON.stringify(value3); - return raw ? value3 : [`${key}=${value3}`]; - } else if (typeof value3 === "number" || typeof value3 === "boolean" || value3 == null) { - return raw ? value3 : [`${key}=${value3}`]; - } else if (isRef(value3)) { - value3 = formatProp(key, toRaw(value3.value), true); - return raw ? value3 : [`${key}=Ref<`, value3, `>`]; - } else if (isFunction$3(value3)) { - return [`${key}=fn${value3.name ? `<${value3.name}>` : ``}`]; - } else { - value3 = toRaw(value3); - return raw ? value3 : [`${key}=`, value3]; - } -} -__name(formatProp, "formatProp"); -function assertNumber(val, type) { - if (true) return; - if (val === void 0) { - return; - } else if (typeof val !== "number") { - warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); - } else if (isNaN(val)) { - warn$1(`${type} is NaN - the duration expression might be incorrect.`); - } -} -__name(assertNumber, "assertNumber"); -const ErrorCodes = { - "SETUP_FUNCTION": 0, - "0": "SETUP_FUNCTION", - "RENDER_FUNCTION": 1, - "1": "RENDER_FUNCTION", - "WATCH_GETTER": 2, - "2": "WATCH_GETTER", - "WATCH_CALLBACK": 3, - "3": "WATCH_CALLBACK", - "WATCH_CLEANUP": 4, - "4": "WATCH_CLEANUP", - "NATIVE_EVENT_HANDLER": 5, - "5": "NATIVE_EVENT_HANDLER", - "COMPONENT_EVENT_HANDLER": 6, - "6": "COMPONENT_EVENT_HANDLER", - "VNODE_HOOK": 7, - "7": "VNODE_HOOK", - "DIRECTIVE_HOOK": 8, - "8": "DIRECTIVE_HOOK", - "TRANSITION_HOOK": 9, - "9": "TRANSITION_HOOK", - "APP_ERROR_HANDLER": 10, - "10": "APP_ERROR_HANDLER", - "APP_WARN_HANDLER": 11, - "11": "APP_WARN_HANDLER", - "FUNCTION_REF": 12, - "12": "FUNCTION_REF", - "ASYNC_COMPONENT_LOADER": 13, - "13": "ASYNC_COMPONENT_LOADER", - "SCHEDULER": 14, - "14": "SCHEDULER" -}; -const ErrorTypeStrings$1 = { - ["sp"]: "serverPrefetch hook", - ["bc"]: "beforeCreate hook", - ["c"]: "created hook", - ["bm"]: "beforeMount hook", - ["m"]: "mounted hook", - ["bu"]: "beforeUpdate hook", - ["u"]: "updated", - ["bum"]: "beforeUnmount hook", - ["um"]: "unmounted hook", - ["a"]: "activated hook", - ["da"]: "deactivated hook", - ["ec"]: "errorCaptured hook", - ["rtc"]: "renderTracked hook", - ["rtg"]: "renderTriggered hook", - [0]: "setup function", - [1]: "render function", - [2]: "watcher getter", - [3]: "watcher callback", - [4]: "watcher cleanup function", - [5]: "native event handler", - [6]: "component event handler", - [7]: "vnode hook", - [8]: "directive hook", - [9]: "transition hook", - [10]: "app errorHandler", - [11]: "app warnHandler", - [12]: "ref function", - [13]: "async component loader", - [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core ." -}; -function callWithErrorHandling(fn, instance, type, args) { - try { - return args ? fn(...args) : fn(); - } catch (err) { - handleError(err, instance, type); - } -} -__name(callWithErrorHandling, "callWithErrorHandling"); -function callWithAsyncErrorHandling(fn, instance, type, args) { - if (isFunction$3(fn)) { - const res = callWithErrorHandling(fn, instance, type, args); - if (res && isPromise$2(res)) { - res.catch((err) => { - handleError(err, instance, type); - }); - } - return res; - } - if (isArray$3(fn)) { - const values2 = []; - for (let i2 = 0; i2 < fn.length; i2++) { - values2.push(callWithAsyncErrorHandling(fn[i2], instance, type, args)); - } - return values2; - } else if (false) { - warn$1( - `Invalid value type passed to callWithAsyncErrorHandling(): ${typeof fn}` - ); - } -} -__name(callWithAsyncErrorHandling, "callWithAsyncErrorHandling"); -function handleError(err, instance, type, throwInDev = true) { - const contextVNode = instance ? instance.vnode : null; - if (instance) { - let cur = instance.parent; - const exposedInstance = instance.proxy; - const errorInfo = false ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`; - while (cur) { - const errorCapturedHooks = cur.ec; - if (errorCapturedHooks) { - for (let i2 = 0; i2 < errorCapturedHooks.length; i2++) { - if (errorCapturedHooks[i2](err, exposedInstance, errorInfo) === false) { - return; - } - } - } - cur = cur.parent; - } - const appErrorHandler = instance.appContext.config.errorHandler; - if (appErrorHandler) { - pauseTracking(); - callWithErrorHandling( - appErrorHandler, - null, - 10, - [err, exposedInstance, errorInfo] - ); - resetTracking(); - return; - } - } - logError(err, type, contextVNode, throwInDev); -} -__name(handleError, "handleError"); -function logError(err, type, contextVNode, throwInDev = true) { - if (false) { - const info = ErrorTypeStrings$1[type]; - if (contextVNode) { - pushWarningContext(contextVNode); - } - warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); - if (contextVNode) { - popWarningContext(); - } - if (throwInDev) { - throw err; - } else { - console.error(err); - } - } else { - console.error(err); - } -} -__name(logError, "logError"); -let isFlushing = false; -let isFlushPending = false; -const queue = []; -let flushIndex = 0; -const pendingPostFlushCbs = []; -let activePostFlushCbs = null; -let postFlushIndex = 0; -const resolvedPromise = /* @__PURE__ */ Promise.resolve(); -let currentFlushPromise = null; -const RECURSION_LIMIT = 100; -function nextTick(fn) { - const p2 = currentFlushPromise || resolvedPromise; - return fn ? p2.then(this ? fn.bind(this) : fn) : p2; -} -__name(nextTick, "nextTick"); -function findInsertionIndex(id2) { - let start2 = flushIndex + 1; - let end = queue.length; - while (start2 < end) { - const middle = start2 + end >>> 1; - const middleJob = queue[middle]; - const middleJobId = getId(middleJob); - if (middleJobId < id2 || middleJobId === id2 && middleJob.pre) { - start2 = middle + 1; - } else { - end = middle; - } - } - return start2; -} -__name(findInsertionIndex, "findInsertionIndex"); -function queueJob(job) { - if (!queue.length || !queue.includes( - job, - isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex - )) { - if (job.id == null) { - queue.push(job); - } else { - queue.splice(findInsertionIndex(job.id), 0, job); - } - queueFlush(); - } -} -__name(queueJob, "queueJob"); -function queueFlush() { - if (!isFlushing && !isFlushPending) { - isFlushPending = true; - currentFlushPromise = resolvedPromise.then(flushJobs); - } -} -__name(queueFlush, "queueFlush"); -function invalidateJob(job) { - const i2 = queue.indexOf(job); - if (i2 > flushIndex) { - queue.splice(i2, 1); - } -} -__name(invalidateJob, "invalidateJob"); -function queuePostFlushCb(cb) { - if (!isArray$3(cb)) { - if (!activePostFlushCbs || !activePostFlushCbs.includes( - cb, - cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex - )) { - pendingPostFlushCbs.push(cb); - } - } else { - pendingPostFlushCbs.push(...cb); - } - queueFlush(); -} -__name(queuePostFlushCb, "queuePostFlushCb"); -function flushPreFlushCbs(instance, seen2, i2 = isFlushing ? flushIndex + 1 : 0) { - if (false) { - seen2 = seen2 || /* @__PURE__ */ new Map(); - } - for (; i2 < queue.length; i2++) { - const cb = queue[i2]; - if (cb && cb.pre) { - if (instance && cb.id !== instance.uid) { - continue; - } - if (false) { - continue; - } - queue.splice(i2, 1); - i2--; - cb(); - } - } -} -__name(flushPreFlushCbs, "flushPreFlushCbs"); -function flushPostFlushCbs(seen2) { - if (pendingPostFlushCbs.length) { - const deduped = [...new Set(pendingPostFlushCbs)].sort( - (a, b) => getId(a) - getId(b) - ); - pendingPostFlushCbs.length = 0; - if (activePostFlushCbs) { - activePostFlushCbs.push(...deduped); - return; - } - activePostFlushCbs = deduped; - if (false) { - seen2 = seen2 || /* @__PURE__ */ new Map(); - } - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - const cb = activePostFlushCbs[postFlushIndex]; - if (false) { - continue; - } - if (cb.active !== false) cb(); - } - activePostFlushCbs = null; - postFlushIndex = 0; - } -} -__name(flushPostFlushCbs, "flushPostFlushCbs"); -const getId = /* @__PURE__ */ __name((job) => job.id == null ? Infinity : job.id, "getId"); -const comparator = /* @__PURE__ */ __name((a, b) => { - const diff = getId(a) - getId(b); - if (diff === 0) { - if (a.pre && !b.pre) return -1; - if (b.pre && !a.pre) return 1; - } - return diff; -}, "comparator"); -function flushJobs(seen2) { - isFlushPending = false; - isFlushing = true; - if (false) { - seen2 = seen2 || /* @__PURE__ */ new Map(); - } - queue.sort(comparator); - const check = false ? (job) => checkRecursiveUpdates(seen2, job) : NOOP; - try { - for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job && job.active !== false) { - if (false) { - continue; - } - callWithErrorHandling(job, null, 14); - } - } - } finally { - flushIndex = 0; - queue.length = 0; - flushPostFlushCbs(seen2); - isFlushing = false; - currentFlushPromise = null; - if (queue.length || pendingPostFlushCbs.length) { - flushJobs(seen2); - } - } -} -__name(flushJobs, "flushJobs"); -function checkRecursiveUpdates(seen2, fn) { - if (!seen2.has(fn)) { - seen2.set(fn, 1); - } else { - const count = seen2.get(fn); - if (count > RECURSION_LIMIT) { - const instance = fn.ownerInstance; - const componentName = instance && getComponentName(instance.type); - handleError( - `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`, - null, - 10 - ); - return true; - } else { - seen2.set(fn, count + 1); - } - } -} -__name(checkRecursiveUpdates, "checkRecursiveUpdates"); -let isHmrUpdating = false; -const hmrDirtyComponents = /* @__PURE__ */ new Set(); -if (false) { - getGlobalThis$1().__VUE_HMR_RUNTIME__ = { - createRecord: tryWrap(createRecord), - rerender: tryWrap(rerender), - reload: tryWrap(reload) - }; -} -const map = /* @__PURE__ */ new Map(); -function registerHMR(instance) { - const id2 = instance.type.__hmrId; - let record = map.get(id2); - if (!record) { - createRecord(id2, instance.type); - record = map.get(id2); - } - record.instances.add(instance); -} -__name(registerHMR, "registerHMR"); -function unregisterHMR(instance) { - map.get(instance.type.__hmrId).instances.delete(instance); -} -__name(unregisterHMR, "unregisterHMR"); -function createRecord(id2, initialDef) { - if (map.has(id2)) { - return false; - } - map.set(id2, { - initialDef: normalizeClassComponent(initialDef), - instances: /* @__PURE__ */ new Set() - }); - return true; -} -__name(createRecord, "createRecord"); -function normalizeClassComponent(component) { - return isClassComponent(component) ? component.__vccOpts : component; -} -__name(normalizeClassComponent, "normalizeClassComponent"); -function rerender(id2, newRender) { - const record = map.get(id2); - if (!record) { - return; - } - record.initialDef.render = newRender; - [...record.instances].forEach((instance) => { - if (newRender) { - instance.render = newRender; - normalizeClassComponent(instance.type).render = newRender; - } - instance.renderCache = []; - isHmrUpdating = true; - instance.effect.dirty = true; - instance.update(); - isHmrUpdating = false; - }); -} -__name(rerender, "rerender"); -function reload(id2, newComp) { - const record = map.get(id2); - if (!record) return; - newComp = normalizeClassComponent(newComp); - updateComponentDef(record.initialDef, newComp); - const instances = [...record.instances]; - for (const instance of instances) { - const oldComp = normalizeClassComponent(instance.type); - if (!hmrDirtyComponents.has(oldComp)) { - if (oldComp !== record.initialDef) { - updateComponentDef(oldComp, newComp); - } - hmrDirtyComponents.add(oldComp); - } - instance.appContext.propsCache.delete(instance.type); - instance.appContext.emitsCache.delete(instance.type); - instance.appContext.optionsCache.delete(instance.type); - if (instance.ceReload) { - hmrDirtyComponents.add(oldComp); - instance.ceReload(newComp.styles); - hmrDirtyComponents.delete(oldComp); - } else if (instance.parent) { - instance.parent.effect.dirty = true; - queueJob(() => { - instance.parent.update(); - hmrDirtyComponents.delete(oldComp); - }); - } else if (instance.appContext.reload) { - instance.appContext.reload(); - } else if (typeof window !== "undefined") { - window.location.reload(); - } else { - console.warn( - "[HMR] Root or manually mounted instance modified. Full reload required." - ); - } - } - queuePostFlushCb(() => { - for (const instance of instances) { - hmrDirtyComponents.delete( - normalizeClassComponent(instance.type) - ); - } - }); -} -__name(reload, "reload"); -function updateComponentDef(oldComp, newComp) { - extend(oldComp, newComp); - for (const key in oldComp) { - if (key !== "__file" && !(key in newComp)) { - delete oldComp[key]; - } - } -} -__name(updateComponentDef, "updateComponentDef"); -function tryWrap(fn) { - return (id2, arg) => { - try { - return fn(id2, arg); - } catch (e) { - console.error(e); - console.warn( - `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` - ); - } - }; -} -__name(tryWrap, "tryWrap"); -let devtools$1; -let buffer = []; -let devtoolsNotInstalled = false; -function emit$1(event2, ...args) { - if (devtools$1) { - devtools$1.emit(event2, ...args); - } else if (!devtoolsNotInstalled) { - buffer.push({ event: event2, args }); - } -} -__name(emit$1, "emit$1"); -function setDevtoolsHook$1(hook, target) { - var _a2, _b2; - devtools$1 = hook; - if (devtools$1) { - devtools$1.enabled = true; - buffer.forEach(({ event: event2, args }) => devtools$1.emit(event2, ...args)); - buffer = []; - } else if ( - // handle late devtools injection - only do this if we are in an actual - // browser environment to avoid the timer handle stalling test runner exit - // (#4815) - typeof window !== "undefined" && // some envs mock window but not fully - window.HTMLElement && // also exclude jsdom - // eslint-disable-next-line no-restricted-syntax - !((_b2 = (_a2 = window.navigator) == null ? void 0 : _a2.userAgent) == null ? void 0 : _b2.includes("jsdom")) - ) { - const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; - replay.push((newHook) => { - setDevtoolsHook$1(newHook, target); - }); - setTimeout(() => { - if (!devtools$1) { - target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; - devtoolsNotInstalled = true; - buffer = []; - } - }, 3e3); - } else { - devtoolsNotInstalled = true; - buffer = []; - } -} -__name(setDevtoolsHook$1, "setDevtoolsHook$1"); -function devtoolsInitApp(app2, version2) { - emit$1("app:init", app2, version2, { - Fragment, - Text, - Comment, - Static - }); -} -__name(devtoolsInitApp, "devtoolsInitApp"); -function devtoolsUnmountApp(app2) { - emit$1("app:unmount", app2); -} -__name(devtoolsUnmountApp, "devtoolsUnmountApp"); -const devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook( - "component:added" - /* COMPONENT_ADDED */ -); -const devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook( - "component:updated" - /* COMPONENT_UPDATED */ -); -const _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook( - "component:removed" - /* COMPONENT_REMOVED */ -); -const devtoolsComponentRemoved = /* @__PURE__ */ __name((component) => { - if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && // remove the component if it wasn't buffered - !devtools$1.cleanupBuffer(component)) { - _devtoolsComponentRemoved(component); - } -}, "devtoolsComponentRemoved"); -/*! #__NO_SIDE_EFFECTS__ */ -// @__NO_SIDE_EFFECTS__ -function createDevtoolsComponentHook(hook) { - return (component) => { - emit$1( - hook, - component.appContext.app, - component.uid, - component.parent ? component.parent.uid : void 0, - component - ); - }; -} -__name(createDevtoolsComponentHook, "createDevtoolsComponentHook"); -const devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:start" - /* PERFORMANCE_START */ -); -const devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:end" - /* PERFORMANCE_END */ -); -function createDevtoolsPerformanceHook(hook) { - return (component, type, time) => { - emit$1(hook, component.appContext.app, component.uid, component, type, time); - }; -} -__name(createDevtoolsPerformanceHook, "createDevtoolsPerformanceHook"); -function devtoolsComponentEmit(component, event2, params) { - emit$1( - "component:emit", - component.appContext.app, - component, - event2, - params - ); -} -__name(devtoolsComponentEmit, "devtoolsComponentEmit"); -function emit(instance, event2, ...rawArgs) { - if (instance.isUnmounted) return; - const props = instance.vnode.props || EMPTY_OBJ; - if (false) { - const { - emitsOptions, - propsOptions: [propsOptions] - } = instance; - if (emitsOptions) { - if (!(event2 in emitsOptions) && true) { - if (!propsOptions || !(toHandlerKey(event2) in propsOptions)) { - warn$1( - `Component emitted event "${event2}" but it is neither declared in the emits option nor as an "${toHandlerKey(event2)}" prop.` - ); - } - } else { - const validator2 = emitsOptions[event2]; - if (isFunction$3(validator2)) { - const isValid2 = validator2(...rawArgs); - if (!isValid2) { - warn$1( - `Invalid event arguments: event validation failed for event "${event2}".` - ); - } - } - } - } - } - let args = rawArgs; - const isModelListener2 = event2.startsWith("update:"); - const modelArg = isModelListener2 && event2.slice(7); - if (modelArg && modelArg in props) { - const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`; - const { number: number2, trim } = props[modifiersKey] || EMPTY_OBJ; - if (trim) { - args = rawArgs.map((a) => isString$4(a) ? a.trim() : a); - } - if (number2) { - args = rawArgs.map(looseToNumber); - } - } - if (false) { - devtoolsComponentEmit(instance, event2, args); - } - if (false) { - const lowerCaseEvent = event2.toLowerCase(); - if (lowerCaseEvent !== event2 && props[toHandlerKey(lowerCaseEvent)]) { - warn$1( - `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( - instance, - instance.type - )} but the handler is registered for "${event2}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate$1( - event2 - )}" instead of "${event2}".` - ); - } - } - let handlerName; - let handler4 = props[handlerName = toHandlerKey(event2)] || // also try camelCase event handler (#2249) - props[handlerName = toHandlerKey(camelize$1(event2))]; - if (!handler4 && isModelListener2) { - handler4 = props[handlerName = toHandlerKey(hyphenate$1(event2))]; - } - if (handler4) { - callWithAsyncErrorHandling( - handler4, - instance, - 6, - args - ); - } - const onceHandler = props[handlerName + `Once`]; - if (onceHandler) { - if (!instance.emitted) { - instance.emitted = {}; - } else if (instance.emitted[handlerName]) { - return; - } - instance.emitted[handlerName] = true; - callWithAsyncErrorHandling( - onceHandler, - instance, - 6, - args - ); - } -} -__name(emit, "emit"); -function normalizeEmitsOptions(comp, appContext, asMixin = false) { - const cache2 = appContext.emitsCache; - const cached = cache2.get(comp); - if (cached !== void 0) { - return cached; - } - const raw = comp.emits; - let normalized = {}; - let hasExtends = false; - if (!isFunction$3(comp)) { - const extendEmits = /* @__PURE__ */ __name((raw2) => { - const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); - if (normalizedFromExtend) { - hasExtends = true; - extend(normalized, normalizedFromExtend); - } - }, "extendEmits"); - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendEmits); - } - if (comp.extends) { - extendEmits(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendEmits); - } - } - if (!raw && !hasExtends) { - if (isObject$5(comp)) { - cache2.set(comp, null); - } - return null; - } - if (isArray$3(raw)) { - raw.forEach((key) => normalized[key] = null); - } else { - extend(normalized, raw); - } - if (isObject$5(comp)) { - cache2.set(comp, normalized); - } - return normalized; -} -__name(normalizeEmitsOptions, "normalizeEmitsOptions"); -function isEmitListener(options3, key) { - if (!options3 || !isOn(key)) { - return false; - } - key = key.slice(2).replace(/Once$/, ""); - return hasOwn$3(options3, key[0].toLowerCase() + key.slice(1)) || hasOwn$3(options3, hyphenate$1(key)) || hasOwn$3(options3, key); -} -__name(isEmitListener, "isEmitListener"); -let currentRenderingInstance = null; -let currentScopeId = null; -function setCurrentRenderingInstance(instance) { - const prev2 = currentRenderingInstance; - currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; - return prev2; -} -__name(setCurrentRenderingInstance, "setCurrentRenderingInstance"); -function pushScopeId(id2) { - currentScopeId = id2; -} -__name(pushScopeId, "pushScopeId"); -function popScopeId() { - currentScopeId = null; -} -__name(popScopeId, "popScopeId"); -const withScopeId = /* @__PURE__ */ __name((_id2) => withCtx, "withScopeId"); -function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { - if (!ctx) return fn; - if (fn._n) { - return fn; - } - const renderFnWithContext = /* @__PURE__ */ __name((...args) => { - if (renderFnWithContext._d) { - setBlockTracking(-1); - } - const prevInstance = setCurrentRenderingInstance(ctx); - let res; - try { - res = fn(...args); - } finally { - setCurrentRenderingInstance(prevInstance); - if (renderFnWithContext._d) { - setBlockTracking(1); - } - } - if (false) { - devtoolsComponentUpdated(ctx); - } - return res; - }, "renderFnWithContext"); - renderFnWithContext._n = true; - renderFnWithContext._c = true; - renderFnWithContext._d = true; - return renderFnWithContext; -} -__name(withCtx, "withCtx"); -let accessedAttrs = false; -function markAttrsAccessed() { - accessedAttrs = true; -} -__name(markAttrsAccessed, "markAttrsAccessed"); -function renderComponentRoot(instance) { - const { - type: Component, - vnode, - proxy, - withProxy, - propsOptions: [propsOptions], - slots, - attrs: attrs3, - emit: emit2, - render: render2, - renderCache, - props, - data: data21, - setupState, - ctx, - inheritAttrs - } = instance; - const prev2 = setCurrentRenderingInstance(instance); - let result; - let fallthroughAttrs; - if (false) { - accessedAttrs = false; - } - try { - if (vnode.shapeFlag & 4) { - const proxyToUse = withProxy || proxy; - const thisProxy = false ? new Proxy(proxyToUse, { - get(target, key, receiver) { - warn$1( - `Property '${String( - key - )}' was accessed via 'this'. Avoid using 'this' in templates.` - ); - return Reflect.get(target, key, receiver); - } - }) : proxyToUse; - result = normalizeVNode( - render2.call( - thisProxy, - proxyToUse, - renderCache, - false ? shallowReadonly(props) : props, - setupState, - data21, - ctx - ) - ); - fallthroughAttrs = attrs3; - } else { - const render22 = Component; - if (false) { - markAttrsAccessed(); - } - result = normalizeVNode( - render22.length > 1 ? render22( - false ? shallowReadonly(props) : props, - false ? { - get attrs() { - markAttrsAccessed(); - return shallowReadonly(attrs3); - }, - slots, - emit: emit2 - } : { attrs: attrs3, slots, emit: emit2 } - ) : render22( - false ? shallowReadonly(props) : props, - null - ) - ); - fallthroughAttrs = Component.props ? attrs3 : getFunctionalFallthrough(attrs3); - } - } catch (err) { - blockStack.length = 0; - handleError(err, instance, 1); - result = createVNode(Comment); - } - let root26 = result; - let setRoot = void 0; - if (false) { - [root26, setRoot] = getChildRoot(result); - } - if (fallthroughAttrs && inheritAttrs !== false) { - const keys2 = Object.keys(fallthroughAttrs); - const { shapeFlag } = root26; - if (keys2.length) { - if (shapeFlag & (1 | 6)) { - if (propsOptions && keys2.some(isModelListener)) { - fallthroughAttrs = filterModelListeners( - fallthroughAttrs, - propsOptions - ); - } - root26 = cloneVNode(root26, fallthroughAttrs, false, true); - } else if (false) { - const allAttrs = Object.keys(attrs3); - const eventAttrs = []; - const extraAttrs = []; - for (let i2 = 0, l = allAttrs.length; i2 < l; i2++) { - const key = allAttrs[i2]; - if (isOn(key)) { - if (!isModelListener(key)) { - eventAttrs.push(key[2].toLowerCase() + key.slice(3)); - } - } else { - extraAttrs.push(key); - } - } - if (extraAttrs.length) { - warn$1( - `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.` - ); - } - if (eventAttrs.length) { - warn$1( - `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` - ); - } - } - } - } - if (vnode.dirs) { - if (false) { - warn$1( - `Runtime directive used on component with non-element root node. The directives will not function as intended.` - ); - } - root26 = cloneVNode(root26, null, false, true); - root26.dirs = root26.dirs ? root26.dirs.concat(vnode.dirs) : vnode.dirs; - } - if (vnode.transition) { - if (false) { - warn$1( - `Component inside renders non-element root node that cannot be animated.` - ); - } - root26.transition = vnode.transition; - } - if (false) { - setRoot(root26); - } else { - result = root26; - } - setCurrentRenderingInstance(prev2); - return result; -} -__name(renderComponentRoot, "renderComponentRoot"); -const getChildRoot = /* @__PURE__ */ __name((vnode) => { - const rawChildren = vnode.children; - const dynamicChildren = vnode.dynamicChildren; - const childRoot = filterSingleRoot(rawChildren, false); - if (!childRoot) { - return [vnode, void 0]; - } else if (false) { - return getChildRoot(childRoot); - } - const index2 = rawChildren.indexOf(childRoot); - const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; - const setRoot = /* @__PURE__ */ __name((updatedRoot) => { - rawChildren[index2] = updatedRoot; - if (dynamicChildren) { - if (dynamicIndex > -1) { - dynamicChildren[dynamicIndex] = updatedRoot; - } else if (updatedRoot.patchFlag > 0) { - vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; - } - } - }, "setRoot"); - return [normalizeVNode(childRoot), setRoot]; -}, "getChildRoot"); -function filterSingleRoot(children, recurse = true) { - let singleRoot; - for (let i2 = 0; i2 < children.length; i2++) { - const child = children[i2]; - if (isVNode$1(child)) { - if (child.type !== Comment || child.children === "v-if") { - if (singleRoot) { - return; - } else { - singleRoot = child; - if (false) { - return filterSingleRoot(singleRoot.children); - } - } - } - } else { - return; - } - } - return singleRoot; -} -__name(filterSingleRoot, "filterSingleRoot"); -const getFunctionalFallthrough = /* @__PURE__ */ __name((attrs3) => { - let res; - for (const key in attrs3) { - if (key === "class" || key === "style" || isOn(key)) { - (res || (res = {}))[key] = attrs3[key]; - } - } - return res; -}, "getFunctionalFallthrough"); -const filterModelListeners = /* @__PURE__ */ __name((attrs3, props) => { - const res = {}; - for (const key in attrs3) { - if (!isModelListener(key) || !(key.slice(9) in props)) { - res[key] = attrs3[key]; - } - } - return res; -}, "filterModelListeners"); -const isElementRoot = /* @__PURE__ */ __name((vnode) => { - return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; -}, "isElementRoot"); -function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - const { props: prevProps, children: prevChildren, component } = prevVNode; - const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; - const emits = component.emitsOptions; - if (false) { - return true; - } - if (nextVNode.dirs || nextVNode.transition) { - return true; - } - if (optimized && patchFlag >= 0) { - if (patchFlag & 1024) { - return true; - } - if (patchFlag & 16) { - if (!prevProps) { - return !!nextProps; - } - return hasPropsChanged(prevProps, nextProps, emits); - } else if (patchFlag & 8) { - const dynamicProps = nextVNode.dynamicProps; - for (let i2 = 0; i2 < dynamicProps.length; i2++) { - const key = dynamicProps[i2]; - if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) { - return true; - } - } - } - } else { - if (prevChildren || nextChildren) { - if (!nextChildren || !nextChildren.$stable) { - return true; - } - } - if (prevProps === nextProps) { - return false; - } - if (!prevProps) { - return !!nextProps; - } - if (!nextProps) { - return true; - } - return hasPropsChanged(prevProps, nextProps, emits); - } - return false; -} -__name(shouldUpdateComponent, "shouldUpdateComponent"); -function hasPropsChanged(prevProps, nextProps, emitsOptions) { - const nextKeys = Object.keys(nextProps); - if (nextKeys.length !== Object.keys(prevProps).length) { - return true; - } - for (let i2 = 0; i2 < nextKeys.length; i2++) { - const key = nextKeys[i2]; - if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) { - return true; - } - } - return false; -} -__name(hasPropsChanged, "hasPropsChanged"); -function updateHOCHostEl({ vnode, parent }, el) { - while (parent) { - const root26 = parent.subTree; - if (root26.suspense && root26.suspense.activeBranch === vnode) { - root26.el = vnode.el; - } - if (root26 === vnode) { - (vnode = parent.vnode).el = el; - parent = parent.parent; - } else { - break; - } - } -} -__name(updateHOCHostEl, "updateHOCHostEl"); -const COMPONENTS = "components"; -const DIRECTIVES = "directives"; -function resolveComponent(name, maybeSelfReference) { - return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; -} -__name(resolveComponent, "resolveComponent"); -const NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); -function resolveDynamicComponent(component) { - if (isString$4(component)) { - return resolveAsset(COMPONENTS, component, false) || component; - } else { - return component || NULL_DYNAMIC_COMPONENT; - } -} -__name(resolveDynamicComponent, "resolveDynamicComponent"); -function resolveDirective(name) { - return resolveAsset(DIRECTIVES, name); -} -__name(resolveDirective, "resolveDirective"); -function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { - const instance = currentRenderingInstance || currentInstance; - if (instance) { - const Component = instance.type; - if (type === COMPONENTS) { - const selfName = getComponentName( - Component, - false - ); - if (selfName && (selfName === name || selfName === camelize$1(name) || selfName === capitalize$1(camelize$1(name)))) { - return Component; - } - } - const res = ( - // local registration - // check instance[type] first which is resolved for options API - resolve$1(instance[type] || Component[type], name) || // global registration - resolve$1(instance.appContext[type], name) - ); - if (!res && maybeSelfReference) { - return Component; - } - if (false) { - const extra = type === COMPONENTS ? ` -If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; - warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); - } - return res; - } else if (false) { - warn$1( - `resolve${capitalize$1(type.slice(0, -1))} can only be used in render() or setup().` - ); - } -} -__name(resolveAsset, "resolveAsset"); -function resolve$1(registry, name) { - return registry && (registry[name] || registry[camelize$1(name)] || registry[capitalize$1(camelize$1(name))]); -} -__name(resolve$1, "resolve$1"); -const isSuspense = /* @__PURE__ */ __name((type) => type.__isSuspense, "isSuspense"); -let suspenseId = 0; -const SuspenseImpl = { - name: "Suspense", - // In order to make Suspense tree-shakable, we need to avoid importing it - // directly in the renderer. The renderer checks for the __isSuspense flag - // on a vnode's type and calls the `process` method, passing in renderer - // internals. - __isSuspense: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - if (n1 == null) { - mountSuspense( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } else { - if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback) { - n2.suspense = n1.suspense; - n2.suspense.vnode = n2; - n2.el = n1.el; - return; - } - patchSuspense( - n1, - n2, - container, - anchor, - parentComponent, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } - }, - hydrate: hydrateSuspense, - normalize: normalizeSuspenseChildren -}; -const Suspense = SuspenseImpl; -function triggerEvent(vnode, name) { - const eventListener = vnode.props && vnode.props[name]; - if (isFunction$3(eventListener)) { - eventListener(); - } -} -__name(triggerEvent, "triggerEvent"); -function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - const { - p: patch, - o: { createElement: createElement2 } - } = rendererInternals; - const hiddenContainer = createElement2("div"); - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - container, - hiddenContainer, - anchor, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - patch( - null, - suspense.pendingBranch = vnode.ssContent, - hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds - ); - if (suspense.deps > 0) { - triggerEvent(vnode, "onPending"); - triggerEvent(vnode, "onFallback"); - patch( - null, - vnode.ssFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds - ); - setActiveBranch(suspense, vnode.ssFallback); - } else { - suspense.resolve(false, true); - } -} -__name(mountSuspense, "mountSuspense"); -function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement: createElement2 } }) { - const suspense = n2.suspense = n1.suspense; - suspense.vnode = n2; - n2.el = n1.el; - const newBranch = n2.ssContent; - const newFallback = n2.ssFallback; - const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; - if (pendingBranch) { - suspense.pendingBranch = newBranch; - if (isSameVNodeType(newBranch, pendingBranch)) { - patch( - pendingBranch, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (isInFallback) { - if (!isHydrating) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } - } else { - suspense.pendingId = suspenseId++; - if (isHydrating) { - suspense.isHydrating = false; - suspense.activeBranch = pendingBranch; - } else { - unmount(pendingBranch, parentComponent, suspense); - } - suspense.deps = 0; - suspense.effects.length = 0; - suspense.hiddenContainer = createElement2("div"); - if (isInFallback) { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - suspense.resolve(true); - } else { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } - } - } - } else { - if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newBranch); - } else { - triggerEvent(n2, "onPending"); - suspense.pendingBranch = newBranch; - if (newBranch.shapeFlag & 512) { - suspense.pendingId = newBranch.component.suspenseId; - } else { - suspense.pendingId = suspenseId++; - } - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - const { timeout, pendingId } = suspense; - if (timeout > 0) { - setTimeout(() => { - if (suspense.pendingId === pendingId) { - suspense.fallback(newFallback); - } - }, timeout); - } else if (timeout === 0) { - suspense.fallback(newFallback); - } - } - } - } -} -__name(patchSuspense, "patchSuspense"); -let hasWarned$1 = false; -function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { - if (false) { - hasWarned$1 = true; - console[console.info ? "info" : "log"]( - ` is an experimental feature and its API will likely change.` - ); - } - const { - p: patch, - m: move, - um: unmount, - n: next2, - o: { parentNode, remove: remove22 } - } = rendererInternals; - let parentSuspenseId; - const isSuspensible = isVNodeSuspensible(vnode); - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch) { - parentSuspenseId = parentSuspense.pendingId; - parentSuspense.deps++; - } - } - const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0; - if (false) { - assertNumber(timeout, `Suspense timeout`); - } - const initialAnchor = anchor; - const suspense = { - vnode, - parent: parentSuspense, - parentComponent, - namespace, - container, - hiddenContainer, - deps: 0, - pendingId: suspenseId++, - timeout: typeof timeout === "number" ? timeout : -1, - activeBranch: null, - pendingBranch: null, - isInFallback: !isHydrating, - isHydrating, - isUnmounted: false, - effects: [], - resolve(resume = false, sync = false) { - if (false) { - if (!resume && !suspense.pendingBranch) { - throw new Error( - `suspense.resolve() is called without a pending branch.` - ); - } - if (suspense.isUnmounted) { - throw new Error( - `suspense.resolve() is called on an already unmounted suspense boundary.` - ); - } - } - const { - vnode: vnode2, - activeBranch, - pendingBranch, - pendingId, - effects, - parentComponent: parentComponent2, - container: container2 - } = suspense; - let delayEnter = false; - if (suspense.isHydrating) { - suspense.isHydrating = false; - } else if (!resume) { - delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; - if (delayEnter) { - activeBranch.transition.afterLeave = () => { - if (pendingId === suspense.pendingId) { - move( - pendingBranch, - container2, - anchor === initialAnchor ? next2(activeBranch) : anchor, - 0 - ); - queuePostFlushCb(effects); - } - }; - } - if (activeBranch) { - if (parentNode(activeBranch.el) !== suspense.hiddenContainer) { - anchor = next2(activeBranch); - } - unmount(activeBranch, parentComponent2, suspense, true); - } - if (!delayEnter) { - move(pendingBranch, container2, anchor, 0); - } - } - setActiveBranch(suspense, pendingBranch); - suspense.pendingBranch = null; - suspense.isInFallback = false; - let parent = suspense.parent; - let hasUnresolvedAncestor = false; - while (parent) { - if (parent.pendingBranch) { - parent.effects.push(...effects); - hasUnresolvedAncestor = true; - break; - } - parent = parent.parent; - } - if (!hasUnresolvedAncestor && !delayEnter) { - queuePostFlushCb(effects); - } - suspense.effects = []; - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { - parentSuspense.deps--; - if (parentSuspense.deps === 0 && !sync) { - parentSuspense.resolve(); - } - } - } - triggerEvent(vnode2, "onResolve"); - }, - fallback(fallbackVNode) { - if (!suspense.pendingBranch) { - return; - } - const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; - triggerEvent(vnode2, "onFallback"); - const anchor2 = next2(activeBranch); - const mountFallback = /* @__PURE__ */ __name(() => { - if (!suspense.isInFallback) { - return; - } - patch( - null, - fallbackVNode, - container2, - anchor2, - parentComponent2, - null, - // fallback tree will not have suspense context - namespace2, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, fallbackVNode); - }, "mountFallback"); - const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; - if (delayEnter) { - activeBranch.transition.afterLeave = mountFallback; - } - suspense.isInFallback = true; - unmount( - activeBranch, - parentComponent2, - null, - // no suspense so unmount hooks fire now - true - // shouldRemove - ); - if (!delayEnter) { - mountFallback(); - } - }, - move(container2, anchor2, type) { - suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); - suspense.container = container2; - }, - next() { - return suspense.activeBranch && next2(suspense.activeBranch); - }, - registerDep(instance, setupRenderEffect, optimized2) { - const isInPendingSuspense = !!suspense.pendingBranch; - if (isInPendingSuspense) { - suspense.deps++; - } - const hydratedEl = instance.vnode.el; - instance.asyncDep.catch((err) => { - handleError(err, instance, 0); - }).then((asyncSetupResult) => { - if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { - return; - } - instance.asyncResolved = true; - const { vnode: vnode2 } = instance; - if (false) { - pushWarningContext(vnode2); - } - handleSetupResult(instance, asyncSetupResult, false); - if (hydratedEl) { - vnode2.el = hydratedEl; - } - const placeholder = !hydratedEl && instance.subTree.el; - setupRenderEffect( - instance, - vnode2, - // component may have been moved before resolve. - // if this is not a hydration, instance.subTree will be the comment - // placeholder. - parentNode(hydratedEl || instance.subTree.el), - // anchor will not be used if this is hydration, so only need to - // consider the comment placeholder case. - hydratedEl ? null : next2(instance.subTree), - suspense, - namespace, - optimized2 - ); - if (placeholder) { - remove22(placeholder); - } - updateHOCHostEl(instance, vnode2.el); - if (false) { - popWarningContext(); - } - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - }); - }, - unmount(parentSuspense2, doRemove) { - suspense.isUnmounted = true; - if (suspense.activeBranch) { - unmount( - suspense.activeBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - if (suspense.pendingBranch) { - unmount( - suspense.pendingBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - } - }; - return suspense; -} -__name(createSuspenseBoundary, "createSuspenseBoundary"); -function hydrateSuspense(node3, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - node3.parentNode, - // eslint-disable-next-line no-restricted-globals - document.createElement("div"), - null, - namespace, - slotScopeIds, - optimized, - rendererInternals, - true - ); - const result = hydrateNode( - node3, - suspense.pendingBranch = vnode.ssContent, - parentComponent, - suspense, - slotScopeIds, - optimized - ); - if (suspense.deps === 0) { - suspense.resolve(false, true); - } - return result; -} -__name(hydrateSuspense, "hydrateSuspense"); -function normalizeSuspenseChildren(vnode) { - const { shapeFlag, children } = vnode; - const isSlotChildren = shapeFlag & 32; - vnode.ssContent = normalizeSuspenseSlot( - isSlotChildren ? children.default : children - ); - vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); -} -__name(normalizeSuspenseChildren, "normalizeSuspenseChildren"); -function normalizeSuspenseSlot(s) { - let block2; - if (isFunction$3(s)) { - const trackBlock = isBlockTreeEnabled && s._c; - if (trackBlock) { - s._d = false; - openBlock(); - } - s = s(); - if (trackBlock) { - s._d = true; - block2 = currentBlock; - closeBlock(); - } - } - if (isArray$3(s)) { - const singleChild = filterSingleRoot(s); - if (false) { - warn$1(` slots expect a single root node.`); - } - s = singleChild; - } - s = normalizeVNode(s); - if (block2 && !s.dynamicChildren) { - s.dynamicChildren = block2.filter((c) => c !== s); - } - return s; -} -__name(normalizeSuspenseSlot, "normalizeSuspenseSlot"); -function queueEffectWithSuspense(fn, suspense) { - if (suspense && suspense.pendingBranch) { - if (isArray$3(fn)) { - suspense.effects.push(...fn); - } else { - suspense.effects.push(fn); - } - } else { - queuePostFlushCb(fn); - } -} -__name(queueEffectWithSuspense, "queueEffectWithSuspense"); -function setActiveBranch(suspense, branch) { - suspense.activeBranch = branch; - const { vnode, parentComponent } = suspense; - let el = branch.el; - while (!el && branch.component) { - branch = branch.component.subTree; - el = branch.el; - } - vnode.el = el; - if (parentComponent && parentComponent.subTree === vnode) { - parentComponent.vnode.el = el; - updateHOCHostEl(parentComponent, el); - } -} -__name(setActiveBranch, "setActiveBranch"); -function isVNodeSuspensible(vnode) { - const suspensible = vnode.props && vnode.props.suspensible; - return suspensible != null && suspensible !== false; -} -__name(isVNodeSuspensible, "isVNodeSuspensible"); -function injectHook(type, hook, target = currentInstance, prepend = false) { - if (target) { - const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - pauseTracking(); - const reset = setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - reset(); - resetTracking(); - return res; - }); - if (prepend) { - hooks.unshift(wrappedHook); - } else { - hooks.push(wrappedHook); - } - return wrappedHook; - } else if (false) { - const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); - warn$1( - `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` - ); - } -} -__name(injectHook, "injectHook"); -const createHook = /* @__PURE__ */ __name((lifecycle2) => (hook, target = currentInstance) => { - if (!isInSSRComponentSetup || lifecycle2 === "sp") { - injectHook(lifecycle2, (...args) => hook(...args), target); - } -}, "createHook"); -const onBeforeMount = createHook("bm"); -const onMounted = createHook("m"); -const onBeforeUpdate = createHook("bu"); -const onUpdated = createHook("u"); -const onBeforeUnmount = createHook("bum"); -const onUnmounted = createHook("um"); -const onServerPrefetch = createHook("sp"); -const onRenderTriggered = createHook( - "rtg" -); -const onRenderTracked = createHook( - "rtc" -); -function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); -} -__name(onErrorCaptured, "onErrorCaptured"); -function validateDirectiveName(name) { - if (isBuiltInDirective(name)) { - warn$1("Do not use built-in directive ids as custom directive id: " + name); - } -} -__name(validateDirectiveName, "validateDirectiveName"); -function withDirectives(vnode, directives) { - if (currentRenderingInstance === null) { - return vnode; - } - const instance = getComponentPublicInstance(currentRenderingInstance); - const bindings = vnode.dirs || (vnode.dirs = []); - for (let i2 = 0; i2 < directives.length; i2++) { - let [dir, value3, arg, modifiers = EMPTY_OBJ] = directives[i2]; - if (dir) { - if (isFunction$3(dir)) { - dir = { - mounted: dir, - updated: dir - }; - } - if (dir.deep) { - traverse(value3); - } - bindings.push({ - dir, - instance, - value: value3, - oldValue: void 0, - arg, - modifiers - }); - } - } - return vnode; -} -__name(withDirectives, "withDirectives"); -function invokeDirectiveHook(vnode, prevVNode, instance, name) { - const bindings = vnode.dirs; - const oldBindings = prevVNode && prevVNode.dirs; - for (let i2 = 0; i2 < bindings.length; i2++) { - const binding = bindings[i2]; - if (oldBindings) { - binding.oldValue = oldBindings[i2].value; - } - let hook = binding.dir[name]; - if (hook) { - pauseTracking(); - callWithAsyncErrorHandling(hook, instance, 8, [ - vnode.el, - binding, - vnode, - prevVNode - ]); - resetTracking(); - } - } -} -__name(invokeDirectiveHook, "invokeDirectiveHook"); -function renderList(source, renderItem, cache2, index2) { - let ret; - const cached = cache2 && cache2[index2]; - if (isArray$3(source) || isString$4(source)) { - ret = new Array(source.length); - for (let i2 = 0, l = source.length; i2 < l; i2++) { - ret[i2] = renderItem(source[i2], i2, void 0, cached && cached[i2]); - } - } else if (typeof source === "number") { - if (false) { - warn$1(`The v-for range expect an integer value but got ${source}.`); - } - ret = new Array(source); - for (let i2 = 0; i2 < source; i2++) { - ret[i2] = renderItem(i2 + 1, i2, void 0, cached && cached[i2]); - } - } else if (isObject$5(source)) { - if (source[Symbol.iterator]) { - ret = Array.from( - source, - (item2, i2) => renderItem(item2, i2, void 0, cached && cached[i2]) - ); - } else { - const keys2 = Object.keys(source); - ret = new Array(keys2.length); - for (let i2 = 0, l = keys2.length; i2 < l; i2++) { - const key = keys2[i2]; - ret[i2] = renderItem(source[key], key, i2, cached && cached[i2]); - } - } - } else { - ret = []; - } - if (cache2) { - cache2[index2] = ret; - } - return ret; -} -__name(renderList, "renderList"); -function createSlots(slots, dynamicSlots) { - for (let i2 = 0; i2 < dynamicSlots.length; i2++) { - const slot = dynamicSlots[i2]; - if (isArray$3(slot)) { - for (let j = 0; j < slot.length; j++) { - slots[slot[j].name] = slot[j].fn; - } - } else if (slot) { - slots[slot.name] = slot.key ? (...args) => { - const res = slot.fn(...args); - if (res) res.key = slot.key; - return res; - } : slot.fn; - } - } - return slots; -} -__name(createSlots, "createSlots"); -/*! #__NO_SIDE_EFFECTS__ */ -// @__NO_SIDE_EFFECTS__ -function defineComponent(options3, extraOptions) { - return isFunction$3(options3) ? ( - // #8326: extend call and options.name access are considered side-effects - // by Rollup, so we have to wrap it in a pure-annotated IIFE. - /* @__PURE__ */ (() => extend({ name: options3.name }, extraOptions, { setup: options3 }))() - ) : options3; -} -__name(defineComponent, "defineComponent"); -const isAsyncWrapper = /* @__PURE__ */ __name((i2) => !!i2.type.__asyncLoader, "isAsyncWrapper"); -/*! #__NO_SIDE_EFFECTS__ */ -// @__NO_SIDE_EFFECTS__ -function defineAsyncComponent(source) { - if (isFunction$3(source)) { - source = { loader: source }; - } - const { - loader, - loadingComponent, - errorComponent, - delay = 200, - timeout, - // undefined = never times out - suspensible = true, - onError: userOnError - } = source; - let pendingRequest = null; - let resolvedComp; - let retries = 0; - const retry = /* @__PURE__ */ __name(() => { - retries++; - pendingRequest = null; - return load2(); - }, "retry"); - const load2 = /* @__PURE__ */ __name(() => { - let thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { - err = err instanceof Error ? err : new Error(String(err)); - if (userOnError) { - return new Promise((resolve22, reject2) => { - const userRetry = /* @__PURE__ */ __name(() => resolve22(retry()), "userRetry"); - const userFail = /* @__PURE__ */ __name(() => reject2(err), "userFail"); - userOnError(err, userRetry, userFail, retries + 1); - }); - } else { - throw err; - } - }).then((comp) => { - if (thisRequest !== pendingRequest && pendingRequest) { - return pendingRequest; - } - if (false) { - warn$1( - `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` - ); - } - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - comp = comp.default; - } - if (false) { - throw new Error(`Invalid async component load result: ${comp}`); - } - resolvedComp = comp; - return comp; - })); - }, "load"); - return /* @__PURE__ */ defineComponent({ - name: "AsyncComponentWrapper", - __asyncLoader: load2, - get __asyncResolved() { - return resolvedComp; - }, - setup() { - const instance = currentInstance; - if (resolvedComp) { - return () => createInnerComp(resolvedComp, instance); - } - const onError = /* @__PURE__ */ __name((err) => { - pendingRequest = null; - handleError( - err, - instance, - 13, - !errorComponent - ); - }, "onError"); - if (suspensible && instance.suspense || isInSSRComponentSetup) { - return load2().then((comp) => { - return () => createInnerComp(comp, instance); - }).catch((err) => { - onError(err); - return () => errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }); - } - const loaded = ref(false); - const error = ref(); - const delayed = ref(!!delay); - if (delay) { - setTimeout(() => { - delayed.value = false; - }, delay); - } - if (timeout != null) { - setTimeout(() => { - if (!loaded.value && !error.value) { - const err = new Error( - `Async component timed out after ${timeout}ms.` - ); - onError(err); - error.value = err; - } - }, timeout); - } - load2().then(() => { - loaded.value = true; - if (instance.parent && isKeepAlive(instance.parent.vnode)) { - instance.parent.effect.dirty = true; - queueJob(instance.parent.update); - } - }).catch((err) => { - onError(err); - error.value = err; - }); - return () => { - if (loaded.value && resolvedComp) { - return createInnerComp(resolvedComp, instance); - } else if (error.value && errorComponent) { - return createVNode(errorComponent, { - error: error.value - }); - } else if (loadingComponent && !delayed.value) { - return createVNode(loadingComponent); - } - }; - } - }); -} -__name(defineAsyncComponent, "defineAsyncComponent"); -function createInnerComp(comp, parent) { - const { ref: ref22, props, children, ce } = parent.vnode; - const vnode = createVNode(comp, props, children); - vnode.ref = ref22; - vnode.ce = ce; - delete parent.vnode.ce; - return vnode; -} -__name(createInnerComp, "createInnerComp"); -function renderSlot(slots, name, props = {}, fallback, noSlotted) { - if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) { - if (name !== "default") props.name = name; - return createVNode("slot", props, fallback && fallback()); - } - let slot = slots[name]; - if (false) { - warn$1( - `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` - ); - slot = /* @__PURE__ */ __name(() => [], "slot"); - } - if (slot && slot._c) { - slot._d = false; - } - openBlock(); - const validSlotContent = slot && ensureValidVNode(slot(props)); - const rendered = createBlock( - Fragment, - { - key: props.key || // slot content array of a dynamic conditional slot may have a branch - // key attached in the `createSlots` helper, respect that - validSlotContent && validSlotContent.key || `_${name}` - }, - validSlotContent || (fallback ? fallback() : []), - validSlotContent && slots._ === 1 ? 64 : -2 - ); - if (!noSlotted && rendered.scopeId) { - rendered.slotScopeIds = [rendered.scopeId + "-s"]; - } - if (slot && slot._c) { - slot._d = true; - } - return rendered; -} -__name(renderSlot, "renderSlot"); -function ensureValidVNode(vnodes) { - return vnodes.some((child) => { - if (!isVNode$1(child)) return true; - if (child.type === Comment) return false; - if (child.type === Fragment && !ensureValidVNode(child.children)) - return false; - return true; - }) ? vnodes : null; -} -__name(ensureValidVNode, "ensureValidVNode"); -function toHandlers(obj, preserveCaseIfNecessary) { - const ret = {}; - if (false) { - warn$1(`v-on with no argument expects an object value.`); - return ret; - } - for (const key in obj) { - ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; - } - return ret; -} -__name(toHandlers, "toHandlers"); -const getPublicInstance = /* @__PURE__ */ __name((i2) => { - if (!i2) return null; - if (isStatefulComponent(i2)) return getComponentPublicInstance(i2); - return getPublicInstance(i2.parent); -}, "getPublicInstance"); -const publicPropertiesMap = ( - // Move PURE marker to new line to workaround compiler discarding it - // due to type annotation - /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), { - $: /* @__PURE__ */ __name((i2) => i2, "$"), - $el: /* @__PURE__ */ __name((i2) => i2.vnode.el, "$el"), - $data: /* @__PURE__ */ __name((i2) => i2.data, "$data"), - $props: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.props) : i2.props, "$props"), - $attrs: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.attrs) : i2.attrs, "$attrs"), - $slots: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.slots) : i2.slots, "$slots"), - $refs: /* @__PURE__ */ __name((i2) => false ? shallowReadonly(i2.refs) : i2.refs, "$refs"), - $parent: /* @__PURE__ */ __name((i2) => getPublicInstance(i2.parent), "$parent"), - $root: /* @__PURE__ */ __name((i2) => getPublicInstance(i2.root), "$root"), - $emit: /* @__PURE__ */ __name((i2) => i2.emit, "$emit"), - $options: /* @__PURE__ */ __name((i2) => true ? resolveMergedOptions(i2) : i2.type, "$options"), - $forceUpdate: /* @__PURE__ */ __name((i2) => i2.f || (i2.f = () => { - i2.effect.dirty = true; - queueJob(i2.update); - }), "$forceUpdate"), - $nextTick: /* @__PURE__ */ __name((i2) => i2.n || (i2.n = nextTick.bind(i2.proxy)), "$nextTick"), - $watch: /* @__PURE__ */ __name((i2) => true ? instanceWatch.bind(i2) : NOOP, "$watch") - }) -); -const isReservedPrefix = /* @__PURE__ */ __name((key) => key === "_" || key === "$", "isReservedPrefix"); -const hasSetupBinding = /* @__PURE__ */ __name((state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn$3(state, key), "hasSetupBinding"); -const PublicInstanceProxyHandlers = { - get({ _: instance }, key) { - if (key === "__v_skip") { - return true; - } - const { ctx, setupState, data: data21, props, accessCache, type, appContext } = instance; - if (false) { - return true; - } - let normalizedProps; - if (key[0] !== "$") { - const n = accessCache[key]; - if (n !== void 0) { - switch (n) { - case 1: - return setupState[key]; - case 2: - return data21[key]; - case 4: - return ctx[key]; - case 3: - return props[key]; - } - } else if (hasSetupBinding(setupState, key)) { - accessCache[key] = 1; - return setupState[key]; - } else if (data21 !== EMPTY_OBJ && hasOwn$3(data21, key)) { - accessCache[key] = 2; - return data21[key]; - } else if ( - // only cache other properties when instance has declared (thus stable) - // props - (normalizedProps = instance.propsOptions[0]) && hasOwn$3(normalizedProps, key) - ) { - accessCache[key] = 3; - return props[key]; - } else if (ctx !== EMPTY_OBJ && hasOwn$3(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if (shouldCacheAccess) { - accessCache[key] = 0; - } - } - const publicGetter = publicPropertiesMap[key]; - let cssModule, globalProperties; - if (publicGetter) { - if (key === "$attrs") { - track(instance.attrs, "get", ""); - } else if (false) { - track(instance, "get", key); - } - return publicGetter(instance); - } else if ( - // css module (injected by vue-loader) - (cssModule = type.__cssModules) && (cssModule = cssModule[key]) - ) { - return cssModule; - } else if (ctx !== EMPTY_OBJ && hasOwn$3(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if ( - // global properties - globalProperties = appContext.config.globalProperties, hasOwn$3(globalProperties, key) - ) { - { - return globalProperties[key]; - } - } else if (false) { - if (data21 !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn$3(data21, key)) { - warn$1( - `Property ${JSON.stringify( - key - )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` - ); - } else if (instance === currentRenderingInstance) { - warn$1( - `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` - ); - } - } - }, - set({ _: instance }, key, value3) { - const { data: data21, setupState, ctx } = instance; - if (hasSetupBinding(setupState, key)) { - setupState[key] = value3; - return true; - } else if (false) { - warn$1(`Cannot mutate \r\n\r\n\r\n\r\n\r\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?: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])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\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])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","// lib/isZodErrorLike.ts\nfunction isZodErrorLike(err) {\n return err instanceof Error && err.name === \"ZodError\" && \"issues\" in err && Array.isArray(err.issues);\n}\n\n// lib/ValidationError.ts\nvar ValidationError = class extends Error {\n name;\n details;\n constructor(message, options) {\n super(message, options);\n this.name = \"ZodValidationError\";\n this.details = getIssuesFromErrorOptions(options);\n }\n toString() {\n return this.message;\n }\n};\nfunction getIssuesFromErrorOptions(options) {\n if (options) {\n const cause = options.cause;\n if (isZodErrorLike(cause)) {\n return cause.issues;\n }\n }\n return [];\n}\n\n// lib/isValidationError.ts\nfunction isValidationError(err) {\n return err instanceof ValidationError;\n}\n\n// lib/isValidationErrorLike.ts\nfunction isValidationErrorLike(err) {\n return err instanceof Error && err.name === \"ZodValidationError\";\n}\n\n// lib/fromZodIssue.ts\nimport * as zod from \"zod\";\n\n// lib/config.ts\nvar ISSUE_SEPARATOR = \"; \";\nvar MAX_ISSUES_IN_MESSAGE = 99;\nvar PREFIX = \"Validation error\";\nvar PREFIX_SEPARATOR = \": \";\nvar UNION_SEPARATOR = \", or \";\n\n// lib/prefixMessage.ts\nfunction prefixMessage(message, prefix, prefixSeparator) {\n if (prefix !== null) {\n if (message.length > 0) {\n return [prefix, message].join(prefixSeparator);\n }\n return prefix;\n }\n if (message.length > 0) {\n return message;\n }\n return PREFIX;\n}\n\n// lib/utils/joinPath.ts\nvar identifierRegex = /[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/u;\nfunction joinPath(path) {\n if (path.length === 1) {\n return path[0].toString();\n }\n return path.reduce((acc, item) => {\n if (typeof item === \"number\") {\n return acc + \"[\" + item.toString() + \"]\";\n }\n if (item.includes('\"')) {\n return acc + '[\"' + escapeQuotes(item) + '\"]';\n }\n if (!identifierRegex.test(item)) {\n return acc + '[\"' + item + '\"]';\n }\n const separator = acc.length === 0 ? \"\" : \".\";\n return acc + separator + item;\n }, \"\");\n}\nfunction escapeQuotes(str) {\n return str.replace(/\"/g, '\\\\\"');\n}\n\n// lib/utils/NonEmptyArray.ts\nfunction isNonEmptyArray(value) {\n return value.length !== 0;\n}\n\n// lib/fromZodIssue.ts\nfunction getMessageFromZodIssue(props) {\n const { issue, issueSeparator, unionSeparator, includePath } = props;\n if (issue.code === \"invalid_union\") {\n return issue.unionErrors.reduce((acc, zodError) => {\n const newIssues = zodError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n ).join(issueSeparator);\n if (!acc.includes(newIssues)) {\n acc.push(newIssues);\n }\n return acc;\n }, []).join(unionSeparator);\n }\n if (issue.code === \"invalid_arguments\") {\n return [\n issue.message,\n ...issue.argumentsError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n )\n ].join(issueSeparator);\n }\n if (issue.code === \"invalid_return_type\") {\n return [\n issue.message,\n ...issue.returnTypeError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n )\n ].join(issueSeparator);\n }\n if (includePath && isNonEmptyArray(issue.path)) {\n if (issue.path.length === 1) {\n const identifier = issue.path[0];\n if (typeof identifier === \"number\") {\n return `${issue.message} at index ${identifier}`;\n }\n }\n return `${issue.message} at \"${joinPath(issue.path)}\"`;\n }\n return issue.message;\n}\nfunction fromZodIssue(issue, options = {}) {\n const {\n issueSeparator = ISSUE_SEPARATOR,\n unionSeparator = UNION_SEPARATOR,\n prefixSeparator = PREFIX_SEPARATOR,\n prefix = PREFIX,\n includePath = true\n } = options;\n const reason = getMessageFromZodIssue({\n issue,\n issueSeparator,\n unionSeparator,\n includePath\n });\n const message = prefixMessage(reason, prefix, prefixSeparator);\n return new ValidationError(message, { cause: new zod.ZodError([issue]) });\n}\n\n// lib/errorMap.ts\nvar errorMap = (issue, ctx) => {\n const error = fromZodIssue({\n ...issue,\n // fallback to the default error message\n // when issue does not have a message\n message: issue.message ?? ctx.defaultError\n });\n return {\n message: error.message\n };\n};\n\n// lib/fromZodError.ts\nfunction fromZodError(zodError, options = {}) {\n if (!isZodErrorLike(zodError)) {\n throw new TypeError(\n `Invalid zodError param; expected instance of ZodError. Did you mean to use the \"${fromError.name}\" method instead?`\n );\n }\n return fromZodErrorWithoutRuntimeCheck(zodError, options);\n}\nfunction fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {\n const {\n maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE,\n issueSeparator = ISSUE_SEPARATOR,\n unionSeparator = UNION_SEPARATOR,\n prefixSeparator = PREFIX_SEPARATOR,\n prefix = PREFIX,\n includePath = true\n } = options;\n const zodIssues = zodError.errors;\n const reason = zodIssues.length === 0 ? zodError.message : zodIssues.slice(0, maxIssuesInMessage).map(\n (issue) => getMessageFromZodIssue({\n issue,\n issueSeparator,\n unionSeparator,\n includePath\n })\n ).join(issueSeparator);\n const message = prefixMessage(reason, prefix, prefixSeparator);\n return new ValidationError(message, { cause: zodError });\n}\n\n// lib/toValidationError.ts\nvar toValidationError = (options = {}) => (err) => {\n if (isZodErrorLike(err)) {\n return fromZodErrorWithoutRuntimeCheck(err, options);\n }\n if (err instanceof Error) {\n return new ValidationError(err.message, { cause: err });\n }\n return new ValidationError(\"Unknown error\");\n};\n\n// lib/fromError.ts\nfunction fromError(err, options = {}) {\n return toValidationError(options)(err);\n}\nexport {\n ValidationError,\n errorMap,\n fromError,\n fromZodError,\n fromZodIssue,\n isValidationError,\n isValidationErrorLike,\n isZodErrorLike,\n toValidationError\n};\n//# sourceMappingURL=index.mjs.map","import { z } from 'zod'\r\nimport { fromZodError } from 'zod-validation-error'\r\n\r\n// GroupNode is hacking node id to be a string, so we need to allow that.\r\n// innerNode.id = `${this.node.id}:${i}`\r\n// Remove it after GroupNode is redesigned.\r\nexport const zNodeId = z.union([z.number().int(), z.string()])\r\nexport type NodeId = z.infer\r\nexport const zSlotIndex = z.union([\r\n z.number().int(),\r\n z\r\n .string()\r\n .transform((val) => parseInt(val))\r\n .refine((val) => !isNaN(val), {\r\n message: 'Invalid number'\r\n })\r\n])\r\n\r\n// TODO: Investigate usage of array and number as data type usage in custom nodes.\r\n// Known usage:\r\n// - https://github.com/rgthree/rgthree-comfy Context Big node is using array as type.\r\nexport const zDataType = z.union([z.string(), z.array(z.string()), z.number()])\r\n\r\n// Definition of an AI model file used in the workflow.\r\nconst zModelFile = z.object({\r\n name: z.string(),\r\n url: z.string().url(),\r\n hash: z.string(),\r\n hash_type: z.string(),\r\n directory: z.string()\r\n})\r\n\r\nconst zComfyLink = z.tuple([\r\n z.number(), // Link id\r\n zNodeId, // Node id of source node\r\n zSlotIndex, // Output slot# of source node\r\n zNodeId, // Node id of destination node\r\n zSlotIndex, // Input slot# of destination node\r\n zDataType // Data type\r\n])\r\n\r\nconst zNodeOutput = z\r\n .object({\r\n name: z.string(),\r\n type: zDataType,\r\n links: z.array(z.number()).nullable().optional(),\r\n slot_index: zSlotIndex.optional()\r\n })\r\n .passthrough()\r\n\r\nconst zNodeInput = z\r\n .object({\r\n name: z.string(),\r\n type: zDataType,\r\n link: z.number().nullable().optional(),\r\n slot_index: zSlotIndex.optional()\r\n })\r\n .passthrough()\r\n\r\nconst zFlags = z\r\n .object({\r\n collapsed: z.boolean().optional(),\r\n pinned: z.boolean().optional(),\r\n allow_interaction: z.boolean().optional(),\r\n horizontal: z.boolean().optional(),\r\n skip_repeated_outputs: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zProperties = z\r\n .object({\r\n ['Node name for S&R']: z.string().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zVector2 = z.union([\r\n z.object({ 0: z.number(), 1: z.number() }).transform((v) => [v[0], v[1]]),\r\n z.tuple([z.number(), z.number()])\r\n])\r\n\r\nconst zWidgetValues = z.union([z.array(z.any()), z.record(z.any())])\r\n\r\nconst zComfyNode = z\r\n .object({\r\n id: zNodeId,\r\n type: z.string(),\r\n pos: zVector2,\r\n size: zVector2,\r\n flags: zFlags,\r\n order: z.number(),\r\n mode: z.number(),\r\n inputs: z.array(zNodeInput).optional(),\r\n outputs: z.array(zNodeOutput).optional(),\r\n properties: zProperties,\r\n widgets_values: zWidgetValues.optional(),\r\n color: z.string().optional(),\r\n bgcolor: z.string().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zGroup = z\r\n .object({\r\n title: z.string(),\r\n bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),\r\n color: z.string().optional(),\r\n font_size: z.number().optional(),\r\n locked: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zInfo = z\r\n .object({\r\n name: z.string(),\r\n author: z.string(),\r\n description: z.string(),\r\n version: z.string(),\r\n created: z.string(),\r\n modified: z.string(),\r\n software: z.string()\r\n })\r\n .passthrough()\r\n\r\nconst zDS = z\r\n .object({\r\n scale: z.number(),\r\n offset: zVector2\r\n })\r\n .passthrough()\r\n\r\nconst zConfig = z\r\n .object({\r\n links_ontop: z.boolean().optional(),\r\n align_to_grid: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zExtra = z\r\n .object({\r\n ds: zDS.optional(),\r\n info: zInfo.optional()\r\n })\r\n .passthrough()\r\n\r\nexport const zComfyWorkflow = z\r\n .object({\r\n last_node_id: zNodeId,\r\n last_link_id: z.number(),\r\n nodes: z.array(zComfyNode),\r\n links: z.array(zComfyLink),\r\n groups: z.array(zGroup).optional(),\r\n config: zConfig.optional().nullable(),\r\n extra: zExtra.optional().nullable(),\r\n version: z.number(),\r\n models: z.array(zModelFile).optional()\r\n })\r\n .passthrough()\r\n\r\nexport type NodeInput = z.infer\r\nexport type NodeOutput = z.infer\r\nexport type ComfyLink = z.infer\r\nexport type ComfyNode = z.infer\r\nexport type ComfyWorkflowJSON = z.infer\r\n\r\nexport async function validateComfyWorkflow(\r\n data: any,\r\n onError: (error: string) => void = console.warn\r\n): Promise {\r\n const result = await zComfyWorkflow.safeParseAsync(data)\r\n if (!result.success) {\r\n const error = fromZodError(result.error)\r\n onError(`Invalid workflow against zod schema:\\n${error}`)\r\n return null\r\n }\r\n return result.data\r\n}\r\n","import { z } from 'zod'\r\n\r\nconst nodeSlotSchema = z\r\n .object({\r\n BOOLEAN: z.string().optional(),\r\n CLIP: z.string(),\r\n CLIP_VISION: z.string(),\r\n CLIP_VISION_OUTPUT: z.string(),\r\n CONDITIONING: z.string(),\r\n CONTROL_NET: z.string(),\r\n CONTROL_NET_WEIGHTS: z.string().optional(),\r\n FLOAT: z.string().optional(),\r\n GLIGEN: z.string().optional(),\r\n IMAGE: z.string(),\r\n IMAGEUPLOAD: z.string().optional(),\r\n INT: z.string().optional(),\r\n LATENT: z.string(),\r\n LATENT_KEYFRAME: z.string().optional(),\r\n MASK: z.string(),\r\n MODEL: z.string(),\r\n SAMPLER: z.string().optional(),\r\n SIGMAS: z.string().optional(),\r\n STRING: z.string().optional(),\r\n STYLE_MODEL: z.string(),\r\n T2I_ADAPTER_WEIGHTS: z.string().optional(),\r\n TAESD: z.string(),\r\n TIMESTEP_KEYFRAME: z.string().optional(),\r\n UPSCALE_MODEL: z.string().optional(),\r\n VAE: z.string()\r\n })\r\n .passthrough()\r\n\r\nconst litegraphBaseSchema = z\r\n .object({\r\n BACKGROUND_IMAGE: z.string(),\r\n CLEAR_BACKGROUND_COLOR: z.string(),\r\n NODE_TITLE_COLOR: z.string(),\r\n NODE_SELECTED_TITLE_COLOR: z.string(),\r\n NODE_TEXT_SIZE: z.number(),\r\n NODE_TEXT_COLOR: z.string(),\r\n NODE_SUBTEXT_SIZE: z.number(),\r\n NODE_DEFAULT_COLOR: z.string(),\r\n NODE_DEFAULT_BGCOLOR: z.string(),\r\n NODE_DEFAULT_BOXCOLOR: z.string(),\r\n NODE_DEFAULT_SHAPE: z.string(),\r\n NODE_BOX_OUTLINE_COLOR: z.string(),\r\n DEFAULT_SHADOW_COLOR: z.string(),\r\n DEFAULT_GROUP_FONT: z.number(),\r\n WIDGET_BGCOLOR: z.string(),\r\n WIDGET_OUTLINE_COLOR: z.string(),\r\n WIDGET_TEXT_COLOR: z.string(),\r\n WIDGET_SECONDARY_TEXT_COLOR: z.string(),\r\n LINK_COLOR: z.string(),\r\n EVENT_LINK_COLOR: z.string(),\r\n CONNECTING_LINK_COLOR: z.string()\r\n })\r\n .passthrough()\r\n\r\nconst comfyBaseSchema = z.object({\r\n ['fg-color']: z.string(),\r\n ['bg-color']: z.string(),\r\n ['comfy-menu-bg']: z.string(),\r\n ['comfy-input-bg']: z.string(),\r\n ['input-text']: z.string(),\r\n ['descrip-text']: z.string(),\r\n ['drag-text']: z.string(),\r\n ['error-text']: z.string(),\r\n ['border-color']: z.string(),\r\n ['tr-even-bg-color']: z.string(),\r\n ['tr-odd-bg-color']: z.string(),\r\n ['content-bg']: z.string(),\r\n ['content-fg']: z.string(),\r\n ['content-hover-bg']: z.string(),\r\n ['content-hover-fg']: z.string()\r\n})\r\n\r\nconst colorsSchema = z\r\n .object({\r\n node_slot: nodeSlotSchema,\r\n litegraph_base: litegraphBaseSchema,\r\n comfy_base: comfyBaseSchema\r\n })\r\n .passthrough()\r\n\r\nconst paletteSchema = z.object({\r\n id: z.string(),\r\n name: z.string(),\r\n colors: colorsSchema\r\n})\r\n\r\nexport const colorPalettesSchema = z.record(paletteSchema)\r\n\r\nexport type Colors = z.infer\r\nexport type Palette = z.infer\r\nexport type ColorPalettes = z.infer\r\n","import { ZodType, z } from 'zod'\r\nimport { zComfyWorkflow, zNodeId } from './comfyWorkflow'\r\nimport { fromZodError } from 'zod-validation-error'\r\nimport { colorPalettesSchema } from './colorPalette'\r\n\r\nconst zNodeType = z.string()\r\nconst zQueueIndex = z.number()\r\nconst zPromptId = z.string()\r\nconst zResultItem = z.object({\r\n filename: z.string(),\r\n subfolder: z.string().optional(),\r\n type: z.string()\r\n})\r\nexport type ResultItem = z.infer\r\nconst zOutputs = z\r\n .object({\r\n audio: z.array(zResultItem).optional(),\r\n images: z.array(zResultItem).optional()\r\n })\r\n .passthrough()\r\n\r\n// WS messages\r\nconst zStatusWsMessageStatus = z.object({\r\n exec_info: z.object({\r\n queue_remaining: z.number().int()\r\n })\r\n})\r\n\r\nconst zStatusWsMessage = z.object({\r\n status: zStatusWsMessageStatus.nullable().optional()\r\n})\r\n\r\nconst zProgressWsMessage = z.object({\r\n value: z.number().int(),\r\n max: z.number().int(),\r\n prompt_id: zPromptId,\r\n node: zNodeId\r\n})\r\n\r\nconst zExecutingWsMessage = z.object({\r\n node: zNodeId,\r\n display_node: zNodeId,\r\n prompt_id: zPromptId\r\n})\r\n\r\nconst zExecutedWsMessage = zExecutingWsMessage.extend({\r\n outputs: zOutputs\r\n})\r\n\r\nconst zExecutionWsMessageBase = z.object({\r\n prompt_id: zPromptId,\r\n timestamp: z.number().int()\r\n})\r\n\r\nconst zExecutionStartWsMessage = zExecutionWsMessageBase\r\nconst zExecutionSuccessWsMessage = zExecutionWsMessageBase\r\nconst zExecutionCachedWsMessage = zExecutionWsMessageBase.extend({\r\n nodes: z.array(zNodeId)\r\n})\r\nconst zExecutionInterruptedWsMessage = zExecutionWsMessageBase.extend({\r\n node_id: zNodeId,\r\n node_type: zNodeType,\r\n executed: z.array(zNodeId)\r\n})\r\nconst zExecutionErrorWsMessage = zExecutionWsMessageBase.extend({\r\n node_id: zNodeId,\r\n node_type: zNodeType,\r\n executed: z.array(zNodeId),\r\n exception_message: z.string(),\r\n exception_type: z.string(),\r\n traceback: z.string(),\r\n current_inputs: z.any(),\r\n current_outputs: z.any()\r\n})\r\n\r\nexport type StatusWsMessageStatus = z.infer\r\nexport type StatusWsMessage = z.infer\r\nexport type ProgressWsMessage = z.infer\r\nexport type ExecutingWsMessage = z.infer\r\nexport type ExecutedWsMessage = z.infer\r\nexport type ExecutionStartWsMessage = z.infer\r\nexport type ExecutionSuccessWsMessage = z.infer<\r\n typeof zExecutionSuccessWsMessage\r\n>\r\nexport type ExecutionCachedWsMessage = z.infer\r\nexport type ExecutionInterruptedWsMessage = z.infer<\r\n typeof zExecutionInterruptedWsMessage\r\n>\r\nexport type ExecutionErrorWsMessage = z.infer\r\n// End of ws messages\r\n\r\nconst zPromptInputItem = z.object({\r\n inputs: z.record(z.string(), z.any()),\r\n class_type: zNodeType\r\n})\r\n\r\nconst zPromptInputs = z.record(zPromptInputItem)\r\n\r\nconst zExtraPngInfo = z\r\n .object({\r\n workflow: zComfyWorkflow\r\n })\r\n .passthrough()\r\n\r\nconst zExtraData = z.object({\r\n extra_pnginfo: zExtraPngInfo,\r\n client_id: z.string()\r\n})\r\nconst zOutputsToExecute = z.array(zNodeId)\r\n\r\nconst zExecutionStartMessage = z.tuple([\r\n z.literal('execution_start'),\r\n zExecutionStartWsMessage\r\n])\r\n\r\nconst zExecutionSuccessMessage = z.tuple([\r\n z.literal('execution_success'),\r\n zExecutionSuccessWsMessage\r\n])\r\n\r\nconst zExecutionCachedMessage = z.tuple([\r\n z.literal('execution_cached'),\r\n zExecutionCachedWsMessage\r\n])\r\n\r\nconst zExecutionInterruptedMessage = z.tuple([\r\n z.literal('execution_interrupted'),\r\n zExecutionInterruptedWsMessage\r\n])\r\n\r\nconst zExecutionErrorMessage = z.tuple([\r\n z.literal('execution_error'),\r\n zExecutionErrorWsMessage\r\n])\r\n\r\nconst zStatusMessage = z.union([\r\n zExecutionStartMessage,\r\n zExecutionSuccessMessage,\r\n zExecutionCachedMessage,\r\n zExecutionInterruptedMessage,\r\n zExecutionErrorMessage\r\n])\r\n\r\nconst zStatus = z.object({\r\n status_str: z.enum(['success', 'error']),\r\n completed: z.boolean(),\r\n messages: z.array(zStatusMessage)\r\n})\r\n\r\nconst zTaskPrompt = z.tuple([\r\n zQueueIndex,\r\n zPromptId,\r\n zPromptInputs,\r\n zExtraData,\r\n zOutputsToExecute\r\n])\r\n\r\nconst zRunningTaskItem = z.object({\r\n taskType: z.literal('Running'),\r\n prompt: zTaskPrompt,\r\n // @Deprecated\r\n remove: z.object({\r\n name: z.literal('Cancel'),\r\n cb: z.function()\r\n })\r\n})\r\n\r\nconst zPendingTaskItem = z.object({\r\n taskType: z.literal('Pending'),\r\n prompt: zTaskPrompt\r\n})\r\n\r\nconst zTaskOutput = z.record(zNodeId, zOutputs)\r\n\r\nconst zHistoryTaskItem = z.object({\r\n taskType: z.literal('History'),\r\n prompt: zTaskPrompt,\r\n status: zStatus.optional(),\r\n outputs: zTaskOutput\r\n})\r\n\r\nconst zTaskItem = z.union([\r\n zRunningTaskItem,\r\n zPendingTaskItem,\r\n zHistoryTaskItem\r\n])\r\n\r\nconst zTaskType = z.union([\r\n z.literal('Running'),\r\n z.literal('Pending'),\r\n z.literal('History')\r\n])\r\n\r\nexport type TaskType = z.infer\r\nexport type TaskPrompt = z.infer\r\nexport type TaskStatus = z.infer\r\nexport type TaskOutput = z.infer\r\n\r\n// `/queue`\r\nexport type RunningTaskItem = z.infer\r\nexport type PendingTaskItem = z.infer\r\n// `/history`\r\nexport type HistoryTaskItem = z.infer\r\nexport type TaskItem = z.infer\r\n\r\nexport function validateTaskItem(taskItem: unknown) {\r\n const result = zTaskItem.safeParse(taskItem)\r\n if (!result.success) {\r\n const zodError = fromZodError(result.error)\r\n // TODO accept a callback to report error.\r\n console.warn(\r\n `Invalid TaskItem: ${JSON.stringify(taskItem)}\\n${zodError.message}`\r\n )\r\n }\r\n return result\r\n}\r\n\r\nfunction inputSpec(\r\n spec: [ZodType, ZodType],\r\n allowUpcast: boolean = true\r\n): ZodType {\r\n const [inputType, inputSpec] = spec\r\n // e.g. \"INT\" => [\"INT\", {}]\r\n const upcastTypes: ZodType[] = allowUpcast\r\n ? [inputType.transform((type) => [type, {}])]\r\n : []\r\n\r\n return z.union([\r\n z.tuple([inputType, inputSpec]),\r\n z.tuple([inputType]).transform(([type]) => [type, {}]),\r\n ...upcastTypes\r\n ])\r\n}\r\n\r\nconst zBaseInputSpecValue = z\r\n .object({\r\n default: z.any().optional(),\r\n forceInput: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zIntInputSpec = inputSpec([\r\n z.literal('INT'),\r\n zBaseInputSpecValue.extend({\r\n min: z.number().optional(),\r\n max: z.number().optional(),\r\n step: z.number().optional(),\r\n // Note: Many node authors are using INT to pass list of INT.\r\n // TODO: Add list of ints type.\r\n default: z.union([z.number(), z.array(z.number())]).optional()\r\n })\r\n])\r\n\r\nconst zFloatInputSpec = inputSpec([\r\n z.literal('FLOAT'),\r\n zBaseInputSpecValue.extend({\r\n min: z.number().optional(),\r\n max: z.number().optional(),\r\n step: z.number().optional(),\r\n round: z.union([z.number(), z.literal(false)]).optional(),\r\n // Note: Many node authors are using FLOAT to pass list of FLOAT.\r\n // TODO: Add list of floats type.\r\n default: z.union([z.number(), z.array(z.number())]).optional()\r\n })\r\n])\r\n\r\nconst zBooleanInputSpec = inputSpec([\r\n z.literal('BOOLEAN'),\r\n zBaseInputSpecValue.extend({\r\n label_on: z.string().optional(),\r\n label_off: z.string().optional(),\r\n default: z.boolean().optional()\r\n })\r\n])\r\n\r\nconst zStringInputSpec = inputSpec([\r\n z.literal('STRING'),\r\n zBaseInputSpecValue.extend({\r\n default: z.string().optional(),\r\n multiline: z.boolean().optional(),\r\n dynamicPrompts: z.boolean().optional()\r\n })\r\n])\r\n\r\n// Dropdown Selection.\r\nconst zComboInputSpec = inputSpec(\r\n [\r\n z.array(z.any()),\r\n zBaseInputSpecValue.extend({\r\n control_after_generate: z.boolean().optional(),\r\n image_upload: z.boolean().optional()\r\n })\r\n ],\r\n /* allowUpcast=*/ false\r\n)\r\n\r\nconst excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])\r\n\r\nconst zCustomInputSpec = inputSpec([\r\n z.string().refine((value) => !excludedLiterals.has(value)),\r\n zBaseInputSpecValue\r\n])\r\n\r\nconst zInputSpec = z.union([\r\n zIntInputSpec,\r\n zFloatInputSpec,\r\n zBooleanInputSpec,\r\n zStringInputSpec,\r\n zComboInputSpec,\r\n zCustomInputSpec\r\n])\r\n\r\nconst zComfyInputsSpec = z.object({\r\n required: z.record(zInputSpec).optional(),\r\n optional: z.record(zInputSpec).optional(),\r\n // Frontend repo is not using it, but some custom nodes are using the\r\n // hidden field to pass various values.\r\n hidden: z.record(z.any()).optional()\r\n})\r\n\r\nconst zComfyNodeDataType = z.string()\r\nconst zComfyComboOutput = z.array(z.any())\r\nconst zComfyOutputTypesSpec = z.array(\r\n z.union([zComfyNodeDataType, zComfyComboOutput])\r\n)\r\n\r\nconst zComfyNodeDef = z.object({\r\n input: zComfyInputsSpec,\r\n output: zComfyOutputTypesSpec,\r\n output_is_list: z.array(z.boolean()),\r\n output_name: z.array(z.string()),\r\n output_tooltips: z.array(z.string()).optional(),\r\n name: z.string(),\r\n display_name: z.string(),\r\n description: z.string(),\r\n category: z.string(),\r\n output_node: z.boolean(),\r\n python_module: z.string(),\r\n deprecated: z.boolean().optional(),\r\n experimental: z.boolean().optional()\r\n})\r\n\r\n// `/object_info`\r\nexport type ComfyInputsSpec = z.infer\r\nexport type ComfyOutputTypesSpec = z.infer\r\nexport type ComfyNodeDef = z.infer\r\n\r\nexport function validateComfyNodeDef(\r\n data: any,\r\n onError: (error: string) => void = console.warn\r\n): ComfyNodeDef | null {\r\n const result = zComfyNodeDef.safeParse(data)\r\n if (!result.success) {\r\n const zodError = fromZodError(result.error)\r\n onError(\r\n `Invalid ComfyNodeDef: ${JSON.stringify(data)}\\n${zodError.message}`\r\n )\r\n return null\r\n }\r\n return result.data\r\n}\r\n\r\nconst zEmbeddingsResponse = z.array(z.string())\r\nconst zExtensionsResponse = z.array(z.string())\r\nconst zPromptResponse = z.object({\r\n node_errors: z.array(z.string()).optional(),\r\n prompt_id: z.string().optional(),\r\n exec_info: z\r\n .object({\r\n queue_remaining: z.number().optional()\r\n })\r\n .optional()\r\n})\r\nexport const zSystemStats = z.object({\r\n system: z.object({\r\n os: z.string(),\r\n python_version: z.string(),\r\n embedded_python: z.boolean()\r\n }),\r\n devices: z.array(\r\n z.object({\r\n name: z.string(),\r\n type: z.string(),\r\n index: z.number().optional(),\r\n vram_total: z.number(),\r\n vram_free: z.number(),\r\n torch_vram_total: z.number(),\r\n torch_vram_free: z.number()\r\n })\r\n )\r\n})\r\nconst zUser = z.object({\r\n storage: z.enum(['server', 'browser']),\r\n migrated: z.boolean(),\r\n users: z.record(z.string(), z.unknown())\r\n})\r\nconst zUserData = z.array(z.array(z.string(), z.string()))\r\nconst zSettings = z.record(z.any()).and(\r\n z\r\n .object({\r\n 'Comfy.ColorPalette': z.string(),\r\n 'Comfy.CustomColorPalettes': colorPalettesSchema,\r\n 'Comfy.ConfirmClear': z.boolean(),\r\n 'Comfy.DevMode': z.boolean(),\r\n 'Comfy.DisableFloatRounding': z.boolean(),\r\n 'Comfy.DisableSliders': z.boolean(),\r\n 'Comfy.DOMClippingEnabled': z.boolean(),\r\n 'Comfy.EditAttention.Delta': z.number(),\r\n 'Comfy.EnableTooltips': z.boolean(),\r\n 'Comfy.EnableWorkflowViewRestore': z.boolean(),\r\n 'Comfy.FloatRoundingPrecision': z.number(),\r\n 'Comfy.InvertMenuScrolling': z.boolean(),\r\n 'Comfy.Logging.Enabled': z.boolean(),\r\n 'Comfy.NodeInputConversionSubmenus': z.boolean(),\r\n 'Comfy.NodeSearchBoxImpl.LinkReleaseTrigger': z.enum([\r\n 'always',\r\n 'hold shift',\r\n 'NOT hold shift'\r\n ]),\r\n 'Comfy.NodeSearchBoxImpl.NodePreview': z.boolean(),\r\n 'Comfy.NodeSearchBoxImpl': z.enum(['default', 'simple']),\r\n 'Comfy.NodeSearchBoxImpl.ShowCategory': z.boolean(),\r\n 'Comfy.NodeSuggestions.number': z.number(),\r\n 'Comfy.Node.ShowDeprecated': z.boolean(),\r\n 'Comfy.Node.ShowExperimental': z.boolean(),\r\n 'Comfy.PreviewFormat': z.string(),\r\n 'Comfy.PromptFilename': z.boolean(),\r\n 'Comfy.Sidebar.Location': z.enum(['left', 'right']),\r\n 'Comfy.Sidebar.Size': z.number(),\r\n 'Comfy.SwitchUser': z.any(),\r\n 'Comfy.SnapToGrid.GridSize': z.number(),\r\n 'Comfy.TextareaWidget.FontSize': z.number(),\r\n 'Comfy.UseNewMenu': z.any(),\r\n 'Comfy.Validation.Workflows': z.boolean(),\r\n 'Comfy.Workflow.SortNodeIdOnSave': z.boolean()\r\n })\r\n .optional()\r\n)\r\n\r\nexport type EmbeddingsResponse = z.infer\r\nexport type ExtensionsResponse = z.infer\r\nexport type PromptResponse = z.infer\r\nexport type Settings = z.infer\r\nexport type SystemStats = z.infer\r\nexport type User = z.infer\r\nexport type UserData = z.infer\r\n","import { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\r\nimport {\r\n HistoryTaskItem,\r\n PendingTaskItem,\r\n RunningTaskItem,\r\n ComfyNodeDef,\r\n validateComfyNodeDef,\r\n EmbeddingsResponse,\r\n ExtensionsResponse,\r\n PromptResponse,\r\n SystemStats,\r\n User,\r\n Settings\r\n} from '@/types/apiTypes'\r\n\r\ninterface QueuePromptRequestBody {\r\n client_id: string\r\n // Mapping from node id to node info + input values\r\n // TODO: Type this.\r\n prompt: Record\r\n extra_data: {\r\n extra_pnginfo: {\r\n workflow: ComfyWorkflowJSON\r\n }\r\n }\r\n front?: boolean\r\n number?: number\r\n}\r\n\r\nclass ComfyApi extends EventTarget {\r\n #registered = new Set()\r\n api_host: string\r\n api_base: string\r\n initialClientId: string\r\n user: string\r\n socket?: WebSocket\r\n clientId?: string\r\n\r\n reportedUnknownMessageTypes = new Set()\r\n\r\n constructor() {\r\n super()\r\n this.api_host = location.host\r\n this.api_base = location.pathname.split('/').slice(0, -1).join('/')\r\n this.initialClientId = sessionStorage.getItem('clientId')\r\n }\r\n\r\n apiURL(route: string): string {\r\n return this.api_base + '/api' + route\r\n }\r\n\r\n fileURL(route: string): string {\r\n return this.api_base + route\r\n }\r\n\r\n fetchApi(route: string, options?: RequestInit) {\r\n if (!options) {\r\n options = {}\r\n }\r\n if (!options.headers) {\r\n options.headers = {}\r\n }\r\n if (!options.cache) {\r\n options.cache = 'no-cache'\r\n }\r\n options.headers['Comfy-User'] = this.user\r\n return fetch(this.apiURL(route), options)\r\n }\r\n\r\n addEventListener(\r\n type: string,\r\n callback: any,\r\n options?: AddEventListenerOptions\r\n ) {\r\n super.addEventListener(type, callback, options)\r\n this.#registered.add(type)\r\n }\r\n\r\n /**\r\n * Poll status for colab and other things that don't support websockets.\r\n */\r\n #pollQueue() {\r\n setInterval(async () => {\r\n try {\r\n const resp = await this.fetchApi('/prompt')\r\n const status = await resp.json()\r\n this.dispatchEvent(new CustomEvent('status', { detail: status }))\r\n } catch (error) {\r\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\r\n }\r\n }, 1000)\r\n }\r\n\r\n /**\r\n * Creates and connects a WebSocket for realtime updates\r\n * @param {boolean} isReconnect If the socket is connection is a reconnect attempt\r\n */\r\n #createSocket(isReconnect?: boolean) {\r\n if (this.socket) {\r\n return\r\n }\r\n\r\n let opened = false\r\n let existingSession = window.name\r\n if (existingSession) {\r\n existingSession = '?clientId=' + existingSession\r\n }\r\n this.socket = new WebSocket(\r\n `ws${window.location.protocol === 'https:' ? 's' : ''}://${this.api_host}${this.api_base}/ws${existingSession}`\r\n )\r\n this.socket.binaryType = 'arraybuffer'\r\n\r\n this.socket.addEventListener('open', () => {\r\n opened = true\r\n if (isReconnect) {\r\n this.dispatchEvent(new CustomEvent('reconnected'))\r\n }\r\n })\r\n\r\n this.socket.addEventListener('error', () => {\r\n if (this.socket) this.socket.close()\r\n if (!isReconnect && !opened) {\r\n this.#pollQueue()\r\n }\r\n })\r\n\r\n this.socket.addEventListener('close', () => {\r\n setTimeout(() => {\r\n this.socket = null\r\n this.#createSocket(true)\r\n }, 300)\r\n if (opened) {\r\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\r\n this.dispatchEvent(new CustomEvent('reconnecting'))\r\n }\r\n })\r\n\r\n this.socket.addEventListener('message', (event) => {\r\n try {\r\n if (event.data instanceof ArrayBuffer) {\r\n const view = new DataView(event.data)\r\n const eventType = view.getUint32(0)\r\n const buffer = event.data.slice(4)\r\n switch (eventType) {\r\n case 1:\r\n const view2 = new DataView(event.data)\r\n const imageType = view2.getUint32(0)\r\n let imageMime\r\n switch (imageType) {\r\n case 1:\r\n default:\r\n imageMime = 'image/jpeg'\r\n break\r\n case 2:\r\n imageMime = 'image/png'\r\n }\r\n const imageBlob = new Blob([buffer.slice(4)], {\r\n type: imageMime\r\n })\r\n this.dispatchEvent(\r\n new CustomEvent('b_preview', { detail: imageBlob })\r\n )\r\n break\r\n default:\r\n throw new Error(\r\n `Unknown binary websocket message of type ${eventType}`\r\n )\r\n }\r\n } else {\r\n const msg = JSON.parse(event.data)\r\n switch (msg.type) {\r\n case 'status':\r\n if (msg.data.sid) {\r\n this.clientId = msg.data.sid\r\n window.name = this.clientId // use window name so it isnt reused when duplicating tabs\r\n sessionStorage.setItem('clientId', this.clientId) // store in session storage so duplicate tab can load correct workflow\r\n }\r\n this.dispatchEvent(\r\n new CustomEvent('status', { detail: msg.data.status })\r\n )\r\n break\r\n case 'progress':\r\n this.dispatchEvent(\r\n new CustomEvent('progress', { detail: msg.data })\r\n )\r\n break\r\n case 'executing':\r\n this.dispatchEvent(\r\n new CustomEvent('executing', {\r\n detail: msg.data.display_node || msg.data.node\r\n })\r\n )\r\n break\r\n case 'executed':\r\n this.dispatchEvent(\r\n new CustomEvent('executed', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_start':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_start', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_success':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_success', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_error':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_error', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_cached':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_cached', { detail: msg.data })\r\n )\r\n break\r\n default:\r\n if (this.#registered.has(msg.type)) {\r\n this.dispatchEvent(\r\n new CustomEvent(msg.type, { detail: msg.data })\r\n )\r\n } else if (!this.reportedUnknownMessageTypes.has(msg.type)) {\r\n this.reportedUnknownMessageTypes.add(msg.type)\r\n throw new Error(`Unknown message type ${msg.type}`)\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.warn('Unhandled message:', event.data, error)\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Initialises sockets and realtime updates\r\n */\r\n init() {\r\n this.#createSocket()\r\n }\r\n\r\n /**\r\n * Gets a list of extension urls\r\n */\r\n async getExtensions(): Promise {\r\n const resp = await this.fetchApi('/extensions', { cache: 'no-store' })\r\n return await resp.json()\r\n }\r\n\r\n /**\r\n * Gets a list of embedding names\r\n */\r\n async getEmbeddings(): Promise {\r\n const resp = await this.fetchApi('/embeddings', { cache: 'no-store' })\r\n return await resp.json()\r\n }\r\n\r\n /**\r\n * Loads node object definitions for the graph\r\n * @returns The node definitions\r\n */\r\n async getNodeDefs(): Promise> {\r\n const resp = await this.fetchApi('/object_info', { cache: 'no-store' })\r\n const objectInfoUnsafe = await resp.json()\r\n const objectInfo: Record = {}\r\n for (const key in objectInfoUnsafe) {\r\n const validatedDef = validateComfyNodeDef(\r\n objectInfoUnsafe[key],\r\n /* onError=*/ (errorMessage: string) => {\r\n console.warn(\r\n `Skipping invalid node definition: ${key}. See debug log for more information.`\r\n )\r\n console.debug(errorMessage)\r\n }\r\n )\r\n if (validatedDef !== null) {\r\n objectInfo[key] = validatedDef\r\n }\r\n }\r\n return objectInfo\r\n }\r\n\r\n /**\r\n *\r\n * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue\r\n * @param {object} prompt The prompt data to queue\r\n */\r\n async queuePrompt(\r\n number: number,\r\n { output, workflow }\r\n ): Promise {\r\n const body: QueuePromptRequestBody = {\r\n client_id: this.clientId,\r\n prompt: output,\r\n extra_data: { extra_pnginfo: { workflow } }\r\n }\r\n\r\n if (number === -1) {\r\n body.front = true\r\n } else if (number != 0) {\r\n body.number = number\r\n }\r\n\r\n const res = await this.fetchApi('/prompt', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify(body)\r\n })\r\n\r\n if (res.status !== 200) {\r\n throw {\r\n response: await res.json()\r\n }\r\n }\r\n\r\n return await res.json()\r\n }\r\n\r\n /**\r\n * Loads a list of items (queue or history)\r\n * @param {string} type The type of items to load, queue or history\r\n * @returns The items of the specified type grouped by their status\r\n */\r\n async getItems(type: 'queue' | 'history') {\r\n if (type === 'queue') {\r\n return this.getQueue()\r\n }\r\n return this.getHistory()\r\n }\r\n\r\n /**\r\n * Gets the current state of the queue\r\n * @returns The currently running and queued items\r\n */\r\n async getQueue(): Promise<{\r\n Running: RunningTaskItem[]\r\n Pending: PendingTaskItem[]\r\n }> {\r\n try {\r\n const res = await this.fetchApi('/queue')\r\n const data = await res.json()\r\n return {\r\n // Running action uses a different endpoint for cancelling\r\n Running: data.queue_running.map((prompt) => ({\r\n taskType: 'Running',\r\n prompt,\r\n remove: { name: 'Cancel', cb: () => api.interrupt() }\r\n })),\r\n Pending: data.queue_pending.map((prompt) => ({\r\n taskType: 'Pending',\r\n prompt\r\n }))\r\n }\r\n } catch (error) {\r\n console.error(error)\r\n return { Running: [], Pending: [] }\r\n }\r\n }\r\n\r\n /**\r\n * Gets the prompt execution history\r\n * @returns Prompt history including node outputs\r\n */\r\n async getHistory(\r\n max_items: number = 200\r\n ): Promise<{ History: HistoryTaskItem[] }> {\r\n try {\r\n const res = await this.fetchApi(`/history?max_items=${max_items}`)\r\n const json: Promise = await res.json()\r\n return {\r\n History: Object.values(json).map((item) => ({\r\n ...item,\r\n taskType: 'History'\r\n }))\r\n }\r\n } catch (error) {\r\n console.error(error)\r\n return { History: [] }\r\n }\r\n }\r\n\r\n /**\r\n * Gets system & device stats\r\n * @returns System stats such as python version, OS, per device info\r\n */\r\n async getSystemStats(): Promise {\r\n const res = await this.fetchApi('/system_stats')\r\n return await res.json()\r\n }\r\n\r\n /**\r\n * Sends a POST request to the API\r\n * @param {*} type The endpoint to post to\r\n * @param {*} body Optional POST data\r\n */\r\n async #postItem(type: string, body: any) {\r\n try {\r\n await this.fetchApi('/' + type, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: body ? JSON.stringify(body) : undefined\r\n })\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n /**\r\n * Deletes an item from the specified list\r\n * @param {string} type The type of item to delete, queue or history\r\n * @param {number} id The id of the item to delete\r\n */\r\n async deleteItem(type: string, id: string) {\r\n await this.#postItem(type, { delete: [id] })\r\n }\r\n\r\n /**\r\n * Clears the specified list\r\n * @param {string} type The type of list to clear, queue or history\r\n */\r\n async clearItems(type: string) {\r\n await this.#postItem(type, { clear: true })\r\n }\r\n\r\n /**\r\n * Interrupts the execution of the running prompt\r\n */\r\n async interrupt() {\r\n await this.#postItem('interrupt', null)\r\n }\r\n\r\n /**\r\n * Gets user configuration data and where data should be stored\r\n */\r\n async getUserConfig(): Promise {\r\n return (await this.fetchApi('/users')).json()\r\n }\r\n\r\n /**\r\n * Creates a new user\r\n * @param { string } username\r\n * @returns The fetch response\r\n */\r\n createUser(username: string) {\r\n return this.fetchApi('/users', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ username })\r\n })\r\n }\r\n\r\n /**\r\n * Gets all setting values for the current user\r\n * @returns { Promise } A dictionary of id -> value\r\n */\r\n async getSettings(): Promise {\r\n return (await this.fetchApi('/settings')).json()\r\n }\r\n\r\n /**\r\n * Gets a setting for the current user\r\n * @param { string } id The id of the setting to fetch\r\n * @returns { Promise } The setting value\r\n */\r\n async getSetting(id: keyof Settings): Promise {\r\n return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json()\r\n }\r\n\r\n /**\r\n * Stores a dictionary of settings for the current user\r\n */\r\n async storeSettings(settings: Settings) {\r\n return this.fetchApi(`/settings`, {\r\n method: 'POST',\r\n body: JSON.stringify(settings)\r\n })\r\n }\r\n\r\n /**\r\n * Stores a setting for the current user\r\n */\r\n async storeSetting(id: keyof Settings, value: Settings[keyof Settings]) {\r\n return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {\r\n method: 'POST',\r\n body: JSON.stringify(value)\r\n })\r\n }\r\n\r\n /**\r\n * Gets a user data file for the current user\r\n */\r\n async getUserData(file: string, options?: RequestInit) {\r\n return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options)\r\n }\r\n\r\n /**\r\n * Stores a user data file for the current user\r\n * @param { string } file The name of the userdata file to save\r\n * @param { unknown } data The data to save to the file\r\n * @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]\r\n * @returns { Promise }\r\n */\r\n async storeUserData(\r\n file: string,\r\n data: any,\r\n options: RequestInit & {\r\n overwrite?: boolean\r\n stringify?: boolean\r\n throwOnError?: boolean\r\n } = { overwrite: true, stringify: true, throwOnError: true }\r\n ): Promise {\r\n const resp = await this.fetchApi(\r\n `/userdata/${encodeURIComponent(file)}?overwrite=${options.overwrite}`,\r\n {\r\n method: 'POST',\r\n body: options?.stringify ? JSON.stringify(data) : data,\r\n ...options\r\n }\r\n )\r\n if (resp.status !== 200 && options.throwOnError !== false) {\r\n throw new Error(\r\n `Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`\r\n )\r\n }\r\n\r\n return resp\r\n }\r\n\r\n /**\r\n * Deletes a user data file for the current user\r\n * @param { string } file The name of the userdata file to delete\r\n */\r\n async deleteUserData(file: string) {\r\n const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {\r\n method: 'DELETE'\r\n })\r\n if (resp.status !== 204) {\r\n throw new Error(\r\n `Error removing user data file '${file}': ${resp.status} ${resp.statusText}`\r\n )\r\n }\r\n }\r\n\r\n /**\r\n * Move a user data file for the current user\r\n * @param { string } source The userdata file to move\r\n * @param { string } dest The destination for the file\r\n */\r\n async moveUserData(\r\n source: string,\r\n dest: string,\r\n options = { overwrite: false }\r\n ) {\r\n const resp = await this.fetchApi(\r\n `/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`,\r\n {\r\n method: 'POST'\r\n }\r\n )\r\n return resp\r\n }\r\n\r\n /**\r\n * @overload\r\n * Lists user data files for the current user\r\n * @param { string } dir The directory in which to list files\r\n * @param { boolean } [recurse] If the listing should be recursive\r\n * @param { true } [split] If the paths should be split based on the os path separator\r\n * @returns { Promise } The list of split file paths in the format [fullPath, ...splitPath]\r\n */\r\n /**\r\n * @overload\r\n * Lists user data files for the current user\r\n * @param { string } dir The directory in which to list files\r\n * @param { boolean } [recurse] If the listing should be recursive\r\n * @param { false | undefined } [split] If the paths should be split based on the os path separator\r\n * @returns { Promise } The list of files\r\n */\r\n async listUserData(\r\n dir: string,\r\n recurse: true,\r\n split?: boolean\r\n ): Promise\r\n async listUserData(\r\n dir: string,\r\n recurse: false,\r\n split?: boolean\r\n ): Promise\r\n async listUserData(dir, recurse, split) {\r\n const resp = await this.fetchApi(\r\n `/userdata?${new URLSearchParams({\r\n recurse,\r\n dir,\r\n split\r\n })}`\r\n )\r\n if (resp.status === 404) return []\r\n if (resp.status !== 200) {\r\n throw new Error(\r\n `Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`\r\n )\r\n }\r\n return resp.json()\r\n }\r\n}\r\n\r\nexport const api = new ComfyApi()\r\n","import { useDialogStore } from '@/stores/dialogStore'\r\nimport { $el } from '../ui'\r\n\r\nexport class ComfyDialog<\r\n T extends HTMLElement = HTMLElement\r\n> extends EventTarget {\r\n element: T\r\n textElement: HTMLElement\r\n #buttons: HTMLButtonElement[] | null\r\n\r\n constructor(type = 'div', buttons = null) {\r\n super()\r\n this.#buttons = buttons\r\n this.element = $el(type + '.comfy-modal', { parent: document.body }, [\r\n $el('div.comfy-modal-content', [\r\n $el('p', { $: (p) => (this.textElement = p) }),\r\n ...this.createButtons()\r\n ])\r\n ]) as T\r\n }\r\n\r\n createButtons() {\r\n return (\r\n this.#buttons ?? [\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Close',\r\n onclick: () => this.close()\r\n })\r\n ]\r\n )\r\n }\r\n\r\n close() {\r\n this.element.style.display = 'none'\r\n }\r\n\r\n show(html) {\r\n if (typeof html === 'string') {\r\n this.textElement.innerHTML = html\r\n } else {\r\n this.textElement.replaceChildren(\r\n ...(html instanceof Array ? html : [html])\r\n )\r\n }\r\n this.element.style.display = 'flex'\r\n }\r\n}\r\n","import { $el } from '../ui'\r\n\r\n/**\r\n * @typedef { { text: string, value?: string, tooltip?: string } } ToggleSwitchItem\r\n */\r\n/**\r\n * Creates a toggle switch element\r\n * @param { string } name\r\n * @param { Array | ToggleSwitchItem } items\r\n * @param { Object } [opts]\r\n * @param { (e: { item: ToggleSwitchItem, prev?: ToggleSwitchItem }) => void } [opts.onChange]\r\n */\r\nexport function toggleSwitch(name, items, e?) {\r\n const onChange = e?.onChange\r\n\r\n let selectedIndex\r\n let elements\r\n\r\n function updateSelected(index) {\r\n if (selectedIndex != null) {\r\n elements[selectedIndex].classList.remove('comfy-toggle-selected')\r\n }\r\n onChange?.({\r\n item: items[index],\r\n prev: selectedIndex == null ? undefined : items[selectedIndex]\r\n })\r\n selectedIndex = index\r\n elements[selectedIndex].classList.add('comfy-toggle-selected')\r\n }\r\n\r\n elements = items.map((item, i) => {\r\n if (typeof item === 'string') item = { text: item }\r\n if (!item.value) item.value = item.text\r\n\r\n const toggle = $el(\r\n 'label',\r\n {\r\n textContent: item.text,\r\n title: item.tooltip ?? ''\r\n },\r\n $el('input', {\r\n name,\r\n type: 'radio',\r\n value: item.value ?? item.text,\r\n checked: item.selected,\r\n onchange: () => {\r\n updateSelected(i)\r\n }\r\n })\r\n )\r\n if (item.selected) {\r\n updateSelected(i)\r\n }\r\n return toggle\r\n })\r\n\r\n const container = $el('div.comfy-toggle-switch', elements)\r\n\r\n if (selectedIndex == null) {\r\n elements[0].children[0].checked = true\r\n updateSelected(0)\r\n }\r\n\r\n return container\r\n}\r\n","import { $el } from '../ui'\r\nimport { api } from '../api'\r\nimport { ComfyDialog } from './dialog'\r\nimport type { ComfyApp } from '../app'\r\nimport type { Setting, SettingParams } from '@/types/settingTypes'\r\nimport { useSettingStore } from '@/stores/settingStore'\r\nimport { Settings } from '@/types/apiTypes'\r\n\r\nexport class ComfySettingsDialog extends ComfyDialog {\r\n app: ComfyApp\r\n settingsValues: any\r\n settingsLookup: Record\r\n settingsParamLookup: Record\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n const frontendVersion = window['__COMFYUI_FRONTEND_VERSION__']\r\n this.app = app\r\n this.settingsValues = {}\r\n this.settingsLookup = {}\r\n this.settingsParamLookup = {}\r\n this.element = $el(\r\n 'dialog',\r\n {\r\n id: 'comfy-settings-dialog',\r\n parent: document.body\r\n },\r\n [\r\n $el('table.comfy-modal-content.comfy-table', [\r\n $el(\r\n 'caption',\r\n { textContent: `Settings (v${frontendVersion})` },\r\n $el('button.comfy-btn', {\r\n type: 'button',\r\n textContent: '\\u00d7',\r\n onclick: () => {\r\n this.element.close()\r\n }\r\n })\r\n ),\r\n $el('tbody', { $: (tbody) => (this.textElement = tbody) }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Close',\r\n style: {\r\n cursor: 'pointer'\r\n },\r\n onclick: () => {\r\n this.element.close()\r\n }\r\n })\r\n ])\r\n ]\r\n ) as HTMLDialogElement\r\n }\r\n\r\n get settings() {\r\n return Object.values(this.settingsLookup)\r\n }\r\n\r\n #dispatchChange(id: string, value: T, oldValue?: T) {\r\n // Keep the settingStore updated. Not using `store.set` as it would trigger\r\n // setSettingValue again.\r\n // `load` re-dispatch the change for any settings added before load so\r\n // settingStore is always up to date.\r\n if (this.app.vueAppReady) {\r\n useSettingStore().settingValues[id] = value\r\n }\r\n\r\n this.dispatchEvent(\r\n new CustomEvent(id + '.change', {\r\n detail: {\r\n value,\r\n oldValue\r\n }\r\n })\r\n )\r\n }\r\n\r\n async load() {\r\n if (this.app.storageLocation === 'browser') {\r\n this.settingsValues = localStorage\r\n } else {\r\n this.settingsValues = await api.getSettings()\r\n }\r\n\r\n // Trigger onChange for any settings added before load\r\n for (const id in this.settingsLookup) {\r\n const value = this.settingsValues[this.getId(id)]\r\n this.settingsLookup[id].onChange?.(value)\r\n this.#dispatchChange(id, value)\r\n }\r\n }\r\n\r\n getId(id: string) {\r\n if (this.app.storageLocation === 'browser') {\r\n id = 'Comfy.Settings.' + id\r\n }\r\n return id\r\n }\r\n\r\n getSettingValue(\r\n id: K,\r\n defaultValue?: Settings[K]\r\n ): Settings[K] {\r\n let value = this.settingsValues[this.getId(id)]\r\n if (value != null) {\r\n if (this.app.storageLocation === 'browser') {\r\n try {\r\n value = JSON.parse(value)\r\n } catch (error) {}\r\n }\r\n }\r\n return (value ?? defaultValue) as Settings[K]\r\n }\r\n\r\n getSettingDefaultValue(id: string) {\r\n const param = this.settingsParamLookup[id]\r\n return param?.defaultValue\r\n }\r\n\r\n async setSettingValueAsync(\r\n id: K,\r\n value: Settings[K]\r\n ) {\r\n const json = JSON.stringify(value)\r\n localStorage['Comfy.Settings.' + id] = json // backwards compatibility for extensions keep setting in storage\r\n\r\n let oldValue = this.getSettingValue(id, undefined)\r\n this.settingsValues[this.getId(id)] = value\r\n\r\n if (id in this.settingsLookup) {\r\n this.settingsLookup[id].onChange?.(value, oldValue)\r\n }\r\n this.#dispatchChange(id, value, oldValue)\r\n\r\n await api.storeSetting(id, value)\r\n }\r\n\r\n setSettingValue(id: K, value: Settings[K]) {\r\n this.setSettingValueAsync(id, value).catch((err) => {\r\n alert(`Error saving setting '${id}'`)\r\n console.error(err)\r\n })\r\n }\r\n\r\n refreshSetting(id: keyof Settings) {\r\n const value = this.getSettingValue(id)\r\n this.settingsLookup[id].onChange?.(value)\r\n this.#dispatchChange(id, value)\r\n }\r\n\r\n addSetting(params: SettingParams) {\r\n const {\r\n id,\r\n name,\r\n type,\r\n defaultValue,\r\n onChange,\r\n attrs = {},\r\n tooltip = '',\r\n options = undefined\r\n } = params\r\n if (!id) {\r\n throw new Error('Settings must have an ID')\r\n }\r\n\r\n if (id in this.settingsLookup) {\r\n throw new Error(`Setting ${id} of type ${type} must have a unique ID.`)\r\n }\r\n\r\n let skipOnChange = false\r\n let value = this.getSettingValue(id)\r\n if (value == null) {\r\n if (this.app.isNewUserSession) {\r\n // Check if we have a localStorage value but not a setting value and we are a new user\r\n const localValue = localStorage['Comfy.Settings.' + id]\r\n if (localValue) {\r\n value = JSON.parse(localValue)\r\n this.setSettingValue(id, value) // Store on the server\r\n }\r\n }\r\n if (value == null) {\r\n value = defaultValue\r\n }\r\n }\r\n\r\n // Trigger initial setting of value\r\n if (!skipOnChange) {\r\n onChange?.(value, undefined)\r\n this.#dispatchChange(id, value)\r\n }\r\n\r\n this.settingsParamLookup[id] = params\r\n if (this.app.vueAppReady) {\r\n useSettingStore().settings[id] = params\r\n }\r\n this.settingsLookup[id] = {\r\n id,\r\n onChange,\r\n name,\r\n render: () => {\r\n if (type === 'hidden') return\r\n\r\n const setter = (v) => {\r\n if (onChange) {\r\n onChange(v, value)\r\n }\r\n\r\n this.setSettingValue(id, v)\r\n value = v\r\n }\r\n value = this.getSettingValue(id, defaultValue)\r\n\r\n let element\r\n const htmlID = id.replaceAll('.', '-')\r\n\r\n const labelCell = $el('td', [\r\n $el('label', {\r\n for: htmlID,\r\n classList: [tooltip !== '' ? 'comfy-tooltip-indicator' : ''],\r\n textContent: name\r\n })\r\n ])\r\n\r\n if (typeof type === 'function') {\r\n element = type(name, setter, value, attrs)\r\n } else {\r\n switch (type) {\r\n case 'boolean':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n id: htmlID,\r\n type: 'checkbox',\r\n checked: value,\r\n onchange: (event) => {\r\n const isChecked = event.target.checked\r\n if (onChange !== undefined) {\r\n onChange(isChecked)\r\n }\r\n this.setSettingValue(id, isChecked)\r\n }\r\n })\r\n ])\r\n ])\r\n break\r\n case 'number':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n type,\r\n value,\r\n id: htmlID,\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n },\r\n ...attrs\r\n })\r\n ])\r\n ])\r\n break\r\n case 'slider':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el(\r\n 'div',\r\n {\r\n style: {\r\n display: 'grid',\r\n gridAutoFlow: 'column'\r\n }\r\n },\r\n [\r\n $el('input', {\r\n ...attrs,\r\n value,\r\n type: 'range',\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n e.target.nextElementSibling.value = e.target.value\r\n }\r\n }),\r\n $el('input', {\r\n ...attrs,\r\n value,\r\n id: htmlID,\r\n type: 'number',\r\n style: { maxWidth: '4rem' },\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n e.target.previousElementSibling.value = e.target.value\r\n }\r\n })\r\n ]\r\n )\r\n ])\r\n ])\r\n break\r\n case 'combo':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el(\r\n 'select',\r\n {\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n }\r\n },\r\n (typeof options === 'function'\r\n ? options(value)\r\n : options || []\r\n ).map((opt) => {\r\n if (typeof opt === 'string') {\r\n opt = { text: opt }\r\n }\r\n const v = opt.value ?? opt.text\r\n return $el('option', {\r\n value: v,\r\n textContent: opt.text,\r\n selected: value + '' === v + ''\r\n })\r\n })\r\n )\r\n ])\r\n ])\r\n break\r\n case 'text':\r\n default:\r\n if (type !== 'text') {\r\n console.warn(\r\n `Unsupported setting type '${type}, defaulting to text`\r\n )\r\n }\r\n\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n value,\r\n id: htmlID,\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n },\r\n ...attrs\r\n })\r\n ])\r\n ])\r\n break\r\n }\r\n }\r\n if (tooltip) {\r\n element.title = tooltip\r\n }\r\n\r\n return element\r\n }\r\n } as Setting\r\n\r\n const self = this\r\n return {\r\n get value() {\r\n return self.getSettingValue(id, defaultValue)\r\n },\r\n set value(v) {\r\n self.setSettingValue(id, v)\r\n }\r\n }\r\n }\r\n\r\n show() {\r\n this.textElement.replaceChildren(\r\n $el(\r\n 'tr',\r\n {\r\n style: { display: 'none' }\r\n },\r\n [$el('th'), $el('th', { style: { width: '33%' } })]\r\n ),\r\n ...this.settings\r\n .sort((a, b) => a.name.localeCompare(b.name))\r\n .map((s) => s.render())\r\n .filter(Boolean)\r\n )\r\n this.element.showModal()\r\n }\r\n}\r\n","import * as Vue from 'vue'\n\nvar isVue2 = false\nvar isVue3 = true\nvar Vue2 = undefined\n\nfunction install() {}\n\nexport function set(target, key, val) {\n if (Array.isArray(target)) {\n target.length = Math.max(target.length, key)\n target.splice(key, 1, val)\n return val\n }\n target[key] = val\n return val\n}\n\nexport function del(target, key) {\n if (Array.isArray(target)) {\n target.splice(key, 1)\n return\n }\n delete target[key]\n}\n\nexport * from 'vue'\nexport {\n Vue,\n Vue2,\n isVue2,\n isVue3,\n install,\n}\n","export function getDevtoolsGlobalHook() {\n return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;\n}\nexport function getTarget() {\n // @ts-expect-error navigator and windows are not available in all environments\n return (typeof navigator !== 'undefined' && typeof window !== 'undefined')\n ? window\n : typeof globalThis !== 'undefined'\n ? globalThis\n : {};\n}\nexport const isProxyAvailable = typeof Proxy === 'function';\n","export const HOOK_SETUP = 'devtools-plugin:setup';\nexport const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';\n","let supported;\nlet perf;\nexport function isPerformanceSupported() {\n var _a;\n if (supported !== undefined) {\n return supported;\n }\n if (typeof window !== 'undefined' && window.performance) {\n supported = true;\n perf = window.performance;\n }\n else if (typeof globalThis !== 'undefined' && ((_a = globalThis.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {\n supported = true;\n perf = globalThis.perf_hooks.performance;\n }\n else {\n supported = false;\n }\n return supported;\n}\nexport function now() {\n return isPerformanceSupported() ? perf.now() : Date.now();\n}\n","import { HOOK_PLUGIN_SETTINGS_SET } from './const.js';\nimport { now } from './time.js';\nexport class ApiProxy {\n constructor(plugin, hook) {\n this.target = null;\n this.targetQueue = [];\n this.onQueue = [];\n this.plugin = plugin;\n this.hook = hook;\n const defaultSettings = {};\n if (plugin.settings) {\n for (const id in plugin.settings) {\n const item = plugin.settings[id];\n defaultSettings[id] = item.defaultValue;\n }\n }\n const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;\n let currentSettings = Object.assign({}, defaultSettings);\n try {\n const raw = localStorage.getItem(localSettingsSaveId);\n const data = JSON.parse(raw);\n Object.assign(currentSettings, data);\n }\n catch (e) {\n // noop\n }\n this.fallbacks = {\n getSettings() {\n return currentSettings;\n },\n setSettings(value) {\n try {\n localStorage.setItem(localSettingsSaveId, JSON.stringify(value));\n }\n catch (e) {\n // noop\n }\n currentSettings = value;\n },\n now() {\n return now();\n },\n };\n if (hook) {\n hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {\n if (pluginId === this.plugin.id) {\n this.fallbacks.setSettings(value);\n }\n });\n }\n this.proxiedOn = new Proxy({}, {\n get: (_target, prop) => {\n if (this.target) {\n return this.target.on[prop];\n }\n else {\n return (...args) => {\n this.onQueue.push({\n method: prop,\n args,\n });\n };\n }\n },\n });\n this.proxiedTarget = new Proxy({}, {\n get: (_target, prop) => {\n if (this.target) {\n return this.target[prop];\n }\n else if (prop === 'on') {\n return this.proxiedOn;\n }\n else if (Object.keys(this.fallbacks).includes(prop)) {\n return (...args) => {\n this.targetQueue.push({\n method: prop,\n args,\n resolve: () => { },\n });\n return this.fallbacks[prop](...args);\n };\n }\n else {\n return (...args) => {\n return new Promise((resolve) => {\n this.targetQueue.push({\n method: prop,\n args,\n resolve,\n });\n });\n };\n }\n },\n });\n }\n async setRealTarget(target) {\n this.target = target;\n for (const item of this.onQueue) {\n this.target.on[item.method](...item.args);\n }\n for (const item of this.targetQueue) {\n item.resolve(await this.target[item.method](...item.args));\n }\n }\n}\n","import { getDevtoolsGlobalHook, getTarget, isProxyAvailable } from './env.js';\nimport { HOOK_SETUP } from './const.js';\nimport { ApiProxy } from './proxy.js';\nexport * from './api/index.js';\nexport * from './plugin.js';\nexport * from './time.js';\nexport function setupDevtoolsPlugin(pluginDescriptor, setupFn) {\n const descriptor = pluginDescriptor;\n const target = getTarget();\n const hook = getDevtoolsGlobalHook();\n const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;\n if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {\n hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);\n }\n else {\n const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;\n const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];\n list.push({\n pluginDescriptor: descriptor,\n setupFn,\n proxy,\n });\n if (proxy) {\n setupFn(proxy.proxiedTarget);\n }\n }\n}\n","/*!\n * pinia v2.1.7\n * (c) 2023 Eduardo San Martin Morote\n * @license MIT\n */\nimport { hasInjectionContext, inject, toRaw, watch, unref, markRaw, effectScope, ref, isVue2, isRef, isReactive, set, getCurrentScope, onScopeDispose, getCurrentInstance, reactive, toRef, del, nextTick, computed, toRefs } from 'vue-demi';\nimport { setupDevtoolsPlugin } from '@vue/devtools-api';\n\n/**\n * setActivePinia must be called to handle SSR at the top of functions like\n * `fetch`, `setup`, `serverPrefetch` and others\n */\nlet activePinia;\n/**\n * Sets or unsets the active pinia. Used in SSR and internally when calling\n * actions and getters\n *\n * @param pinia - Pinia instance\n */\n// @ts-expect-error: cannot constrain the type of the return\nconst setActivePinia = (pinia) => (activePinia = pinia);\n/**\n * Get the currently active pinia if there is any.\n */\nconst getActivePinia = () => (hasInjectionContext() && inject(piniaSymbol)) || activePinia;\nconst piniaSymbol = ((process.env.NODE_ENV !== 'production') ? Symbol('pinia') : /* istanbul ignore next */ Symbol());\n\nfunction isPlainObject(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\no) {\n return (o &&\n typeof o === 'object' &&\n Object.prototype.toString.call(o) === '[object Object]' &&\n typeof o.toJSON !== 'function');\n}\n// type DeepReadonly = { readonly [P in keyof T]: DeepReadonly }\n// TODO: can we change these to numbers?\n/**\n * Possible types for SubscriptionCallback\n */\nvar MutationType;\n(function (MutationType) {\n /**\n * Direct mutation of the state:\n *\n * - `store.name = 'new name'`\n * - `store.$state.name = 'new name'`\n * - `store.list.push('new item')`\n */\n MutationType[\"direct\"] = \"direct\";\n /**\n * Mutated the state with `$patch` and an object\n *\n * - `store.$patch({ name: 'newName' })`\n */\n MutationType[\"patchObject\"] = \"patch object\";\n /**\n * Mutated the state with `$patch` and a function\n *\n * - `store.$patch(state => state.name = 'newName')`\n */\n MutationType[\"patchFunction\"] = \"patch function\";\n // maybe reset? for $state = {} and $reset\n})(MutationType || (MutationType = {}));\n\nconst IS_CLIENT = typeof window !== 'undefined';\n/**\n * Should we add the devtools plugins.\n * - only if dev mode or forced through the prod devtools flag\n * - not in test\n * - only if window exists (could change in the future)\n */\nconst USE_DEVTOOLS = ((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test') && IS_CLIENT;\n\n/*\n * FileSaver.js A saveAs() FileSaver implementation.\n *\n * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin\n * Morote.\n *\n * License : MIT\n */\n// The one and only way of getting global scope in all environments\n// https://stackoverflow.com/q/3277182/1008999\nconst _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window\n ? window\n : typeof self === 'object' && self.self === self\n ? self\n : typeof global === 'object' && global.global === global\n ? global\n : typeof globalThis === 'object'\n ? globalThis\n : { HTMLElement: null })();\nfunction bom(blob, { autoBom = false } = {}) {\n // prepend BOM for UTF-8 XML and text/* types (including HTML)\n // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF\n if (autoBom &&\n /^\\s*(?:text\\/\\S*|application\\/xml|\\S*\\/\\S*\\+xml)\\s*;.*charset\\s*=\\s*utf-8/i.test(blob.type)) {\n return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });\n }\n return blob;\n}\nfunction download(url, name, opts) {\n const xhr = new XMLHttpRequest();\n xhr.open('GET', url);\n xhr.responseType = 'blob';\n xhr.onload = function () {\n saveAs(xhr.response, name, opts);\n };\n xhr.onerror = function () {\n console.error('could not download file');\n };\n xhr.send();\n}\nfunction corsEnabled(url) {\n const xhr = new XMLHttpRequest();\n // use sync to avoid popup blocker\n xhr.open('HEAD', url, false);\n try {\n xhr.send();\n }\n catch (e) { }\n return xhr.status >= 200 && xhr.status <= 299;\n}\n// `a.click()` doesn't work for all browsers (#465)\nfunction click(node) {\n try {\n node.dispatchEvent(new MouseEvent('click'));\n }\n catch (e) {\n const evt = document.createEvent('MouseEvents');\n evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);\n node.dispatchEvent(evt);\n }\n}\nconst _navigator = \n typeof navigator === 'object' ? navigator : { userAgent: '' };\n// Detect WebView inside a native macOS app by ruling out all browsers\n// We just need to check for 'Safari' because all other browsers (besides Firefox) include that too\n// https://www.whatismybrowser.com/guides/the-latest-user-agent/macos\nconst isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) &&\n /AppleWebKit/.test(_navigator.userAgent) &&\n !/Safari/.test(_navigator.userAgent))();\nconst saveAs = !IS_CLIENT\n ? () => { } // noop\n : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program\n typeof HTMLAnchorElement !== 'undefined' &&\n 'download' in HTMLAnchorElement.prototype &&\n !isMacOSWebView\n ? downloadSaveAs\n : // Use msSaveOrOpenBlob as a second approach\n 'msSaveOrOpenBlob' in _navigator\n ? msSaveAs\n : // Fallback to using FileReader and a popup\n fileSaverSaveAs;\nfunction downloadSaveAs(blob, name = 'download', opts) {\n const a = document.createElement('a');\n a.download = name;\n a.rel = 'noopener'; // tabnabbing\n // TODO: detect chrome extensions & packaged apps\n // a.target = '_blank'\n if (typeof blob === 'string') {\n // Support regular links\n a.href = blob;\n if (a.origin !== location.origin) {\n if (corsEnabled(a.href)) {\n download(blob, name, opts);\n }\n else {\n a.target = '_blank';\n click(a);\n }\n }\n else {\n click(a);\n }\n }\n else {\n // Support blobs\n a.href = URL.createObjectURL(blob);\n setTimeout(function () {\n URL.revokeObjectURL(a.href);\n }, 4e4); // 40s\n setTimeout(function () {\n click(a);\n }, 0);\n }\n}\nfunction msSaveAs(blob, name = 'download', opts) {\n if (typeof blob === 'string') {\n if (corsEnabled(blob)) {\n download(blob, name, opts);\n }\n else {\n const a = document.createElement('a');\n a.href = blob;\n a.target = '_blank';\n setTimeout(function () {\n click(a);\n });\n }\n }\n else {\n // @ts-ignore: works on windows\n navigator.msSaveOrOpenBlob(bom(blob, opts), name);\n }\n}\nfunction fileSaverSaveAs(blob, name, opts, popup) {\n // Open a popup immediately do go around popup blocker\n // Mostly only available on user interaction and the fileReader is async so...\n popup = popup || open('', '_blank');\n if (popup) {\n popup.document.title = popup.document.body.innerText = 'downloading...';\n }\n if (typeof blob === 'string')\n return download(blob, name, opts);\n const force = blob.type === 'application/octet-stream';\n const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global;\n const isChromeIOS = /CriOS\\/[\\d]+/.test(navigator.userAgent);\n if ((isChromeIOS || (force && isSafari) || isMacOSWebView) &&\n typeof FileReader !== 'undefined') {\n // Safari doesn't allow downloading of blob URLs\n const reader = new FileReader();\n reader.onloadend = function () {\n let url = reader.result;\n if (typeof url !== 'string') {\n popup = null;\n throw new Error('Wrong reader.result type');\n }\n url = isChromeIOS\n ? url\n : url.replace(/^data:[^;]*;/, 'data:attachment/file;');\n if (popup) {\n popup.location.href = url;\n }\n else {\n location.assign(url);\n }\n popup = null; // reverse-tabnabbing #460\n };\n reader.readAsDataURL(blob);\n }\n else {\n const url = URL.createObjectURL(blob);\n if (popup)\n popup.location.assign(url);\n else\n location.href = url;\n popup = null; // reverse-tabnabbing #460\n setTimeout(function () {\n URL.revokeObjectURL(url);\n }, 4e4); // 40s\n }\n}\n\n/**\n * Shows a toast or console.log\n *\n * @param message - message to log\n * @param type - different color of the tooltip\n */\nfunction toastMessage(message, type) {\n const piniaMessage = '🍍 ' + message;\n if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') {\n // No longer available :(\n __VUE_DEVTOOLS_TOAST__(piniaMessage, type);\n }\n else if (type === 'error') {\n console.error(piniaMessage);\n }\n else if (type === 'warn') {\n console.warn(piniaMessage);\n }\n else {\n console.log(piniaMessage);\n }\n}\nfunction isPinia(o) {\n return '_a' in o && 'install' in o;\n}\n\n/**\n * This file contain devtools actions, they are not Pinia actions.\n */\n// ---\nfunction checkClipboardAccess() {\n if (!('clipboard' in navigator)) {\n toastMessage(`Your browser doesn't support the Clipboard API`, 'error');\n return true;\n }\n}\nfunction checkNotFocusedError(error) {\n if (error instanceof Error &&\n error.message.toLowerCase().includes('document is not focused')) {\n toastMessage('You need to activate the \"Emulate a focused page\" setting in the \"Rendering\" panel of devtools.', 'warn');\n return true;\n }\n return false;\n}\nasync function actionGlobalCopyState(pinia) {\n if (checkClipboardAccess())\n return;\n try {\n await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));\n toastMessage('Global state copied to clipboard.');\n }\n catch (error) {\n if (checkNotFocusedError(error))\n return;\n toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error');\n console.error(error);\n }\n}\nasync function actionGlobalPasteState(pinia) {\n if (checkClipboardAccess())\n return;\n try {\n loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));\n toastMessage('Global state pasted from clipboard.');\n }\n catch (error) {\n if (checkNotFocusedError(error))\n return;\n toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error');\n console.error(error);\n }\n}\nasync function actionGlobalSaveState(pinia) {\n try {\n saveAs(new Blob([JSON.stringify(pinia.state.value)], {\n type: 'text/plain;charset=utf-8',\n }), 'pinia-state.json');\n }\n catch (error) {\n toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');\n console.error(error);\n }\n}\nlet fileInput;\nfunction getFileOpener() {\n if (!fileInput) {\n fileInput = document.createElement('input');\n fileInput.type = 'file';\n fileInput.accept = '.json';\n }\n function openFile() {\n return new Promise((resolve, reject) => {\n fileInput.onchange = async () => {\n const files = fileInput.files;\n if (!files)\n return resolve(null);\n const file = files.item(0);\n if (!file)\n return resolve(null);\n return resolve({ text: await file.text(), file });\n };\n // @ts-ignore: TODO: changed from 4.3 to 4.4\n fileInput.oncancel = () => resolve(null);\n fileInput.onerror = reject;\n fileInput.click();\n });\n }\n return openFile;\n}\nasync function actionGlobalOpenStateFile(pinia) {\n try {\n const open = getFileOpener();\n const result = await open();\n if (!result)\n return;\n const { text, file } = result;\n loadStoresState(pinia, JSON.parse(text));\n toastMessage(`Global state imported from \"${file.name}\".`);\n }\n catch (error) {\n toastMessage(`Failed to import the state from JSON. Check the console for more details.`, 'error');\n console.error(error);\n }\n}\nfunction loadStoresState(pinia, state) {\n for (const key in state) {\n const storeState = pinia.state.value[key];\n // store is already instantiated, patch it\n if (storeState) {\n Object.assign(storeState, state[key]);\n }\n else {\n // store is not instantiated, set the initial state\n pinia.state.value[key] = state[key];\n }\n }\n}\n\nfunction formatDisplay(display) {\n return {\n _custom: {\n display,\n },\n };\n}\nconst PINIA_ROOT_LABEL = '🍍 Pinia (root)';\nconst PINIA_ROOT_ID = '_root';\nfunction formatStoreForInspectorTree(store) {\n return isPinia(store)\n ? {\n id: PINIA_ROOT_ID,\n label: PINIA_ROOT_LABEL,\n }\n : {\n id: store.$id,\n label: store.$id,\n };\n}\nfunction formatStoreForInspectorState(store) {\n if (isPinia(store)) {\n const storeNames = Array.from(store._s.keys());\n const storeMap = store._s;\n const state = {\n state: storeNames.map((storeId) => ({\n editable: true,\n key: storeId,\n value: store.state.value[storeId],\n })),\n getters: storeNames\n .filter((id) => storeMap.get(id)._getters)\n .map((id) => {\n const store = storeMap.get(id);\n return {\n editable: false,\n key: id,\n value: store._getters.reduce((getters, key) => {\n getters[key] = store[key];\n return getters;\n }, {}),\n };\n }),\n };\n return state;\n }\n const state = {\n state: Object.keys(store.$state).map((key) => ({\n editable: true,\n key,\n value: store.$state[key],\n })),\n };\n // avoid adding empty getters\n if (store._getters && store._getters.length) {\n state.getters = store._getters.map((getterName) => ({\n editable: false,\n key: getterName,\n value: store[getterName],\n }));\n }\n if (store._customProperties.size) {\n state.customProperties = Array.from(store._customProperties).map((key) => ({\n editable: true,\n key,\n value: store[key],\n }));\n }\n return state;\n}\nfunction formatEventData(events) {\n if (!events)\n return {};\n if (Array.isArray(events)) {\n // TODO: handle add and delete for arrays and objects\n return events.reduce((data, event) => {\n data.keys.push(event.key);\n data.operations.push(event.type);\n data.oldValue[event.key] = event.oldValue;\n data.newValue[event.key] = event.newValue;\n return data;\n }, {\n oldValue: {},\n keys: [],\n operations: [],\n newValue: {},\n });\n }\n else {\n return {\n operation: formatDisplay(events.type),\n key: formatDisplay(events.key),\n oldValue: events.oldValue,\n newValue: events.newValue,\n };\n }\n}\nfunction formatMutationType(type) {\n switch (type) {\n case MutationType.direct:\n return 'mutation';\n case MutationType.patchFunction:\n return '$patch';\n case MutationType.patchObject:\n return '$patch';\n default:\n return 'unknown';\n }\n}\n\n// timeline can be paused when directly changing the state\nlet isTimelineActive = true;\nconst componentStateTypes = [];\nconst MUTATIONS_LAYER_ID = 'pinia:mutations';\nconst INSPECTOR_ID = 'pinia';\nconst { assign: assign$1 } = Object;\n/**\n * Gets the displayed name of a store in devtools\n *\n * @param id - id of the store\n * @returns a formatted string\n */\nconst getStoreType = (id) => '🍍 ' + id;\n/**\n * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab\n * as soon as it is added to the application.\n *\n * @param app - Vue application\n * @param pinia - pinia instance\n */\nfunction registerPiniaDevtools(app, pinia) {\n setupDevtoolsPlugin({\n id: 'dev.esm.pinia',\n label: 'Pinia 🍍',\n logo: 'https://pinia.vuejs.org/logo.svg',\n packageName: 'pinia',\n homepage: 'https://pinia.vuejs.org',\n componentStateTypes,\n app,\n }, (api) => {\n if (typeof api.now !== 'function') {\n toastMessage('You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.');\n }\n api.addTimelineLayer({\n id: MUTATIONS_LAYER_ID,\n label: `Pinia 🍍`,\n color: 0xe5df88,\n });\n api.addInspector({\n id: INSPECTOR_ID,\n label: 'Pinia 🍍',\n icon: 'storage',\n treeFilterPlaceholder: 'Search stores',\n actions: [\n {\n icon: 'content_copy',\n action: () => {\n actionGlobalCopyState(pinia);\n },\n tooltip: 'Serialize and copy the state',\n },\n {\n icon: 'content_paste',\n action: async () => {\n await actionGlobalPasteState(pinia);\n api.sendInspectorTree(INSPECTOR_ID);\n api.sendInspectorState(INSPECTOR_ID);\n },\n tooltip: 'Replace the state with the content of your clipboard',\n },\n {\n icon: 'save',\n action: () => {\n actionGlobalSaveState(pinia);\n },\n tooltip: 'Save the state as a JSON file',\n },\n {\n icon: 'folder_open',\n action: async () => {\n await actionGlobalOpenStateFile(pinia);\n api.sendInspectorTree(INSPECTOR_ID);\n api.sendInspectorState(INSPECTOR_ID);\n },\n tooltip: 'Import the state from a JSON file',\n },\n ],\n nodeActions: [\n {\n icon: 'restore',\n tooltip: 'Reset the state (with \"$reset\")',\n action: (nodeId) => {\n const store = pinia._s.get(nodeId);\n if (!store) {\n toastMessage(`Cannot reset \"${nodeId}\" store because it wasn't found.`, 'warn');\n }\n else if (typeof store.$reset !== 'function') {\n toastMessage(`Cannot reset \"${nodeId}\" store because it doesn't have a \"$reset\" method implemented.`, 'warn');\n }\n else {\n store.$reset();\n toastMessage(`Store \"${nodeId}\" reset.`);\n }\n },\n },\n ],\n });\n api.on.inspectComponent((payload, ctx) => {\n const proxy = (payload.componentInstance &&\n payload.componentInstance.proxy);\n if (proxy && proxy._pStores) {\n const piniaStores = payload.componentInstance.proxy._pStores;\n Object.values(piniaStores).forEach((store) => {\n payload.instanceData.state.push({\n type: getStoreType(store.$id),\n key: 'state',\n editable: true,\n value: store._isOptionsAPI\n ? {\n _custom: {\n value: toRaw(store.$state),\n actions: [\n {\n icon: 'restore',\n tooltip: 'Reset the state of this store',\n action: () => store.$reset(),\n },\n ],\n },\n }\n : // NOTE: workaround to unwrap transferred refs\n Object.keys(store.$state).reduce((state, key) => {\n state[key] = store.$state[key];\n return state;\n }, {}),\n });\n if (store._getters && store._getters.length) {\n payload.instanceData.state.push({\n type: getStoreType(store.$id),\n key: 'getters',\n editable: false,\n value: store._getters.reduce((getters, key) => {\n try {\n getters[key] = store[key];\n }\n catch (error) {\n // @ts-expect-error: we just want to show it in devtools\n getters[key] = error;\n }\n return getters;\n }, {}),\n });\n }\n });\n }\n });\n api.on.getInspectorTree((payload) => {\n if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {\n let stores = [pinia];\n stores = stores.concat(Array.from(pinia._s.values()));\n payload.rootNodes = (payload.filter\n ? stores.filter((store) => '$id' in store\n ? store.$id\n .toLowerCase()\n .includes(payload.filter.toLowerCase())\n : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase()))\n : stores).map(formatStoreForInspectorTree);\n }\n });\n api.on.getInspectorState((payload) => {\n if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {\n const inspectedStore = payload.nodeId === PINIA_ROOT_ID\n ? pinia\n : pinia._s.get(payload.nodeId);\n if (!inspectedStore) {\n // this could be the selected store restored for a different project\n // so it's better not to say anything here\n return;\n }\n if (inspectedStore) {\n payload.state = formatStoreForInspectorState(inspectedStore);\n }\n }\n });\n api.on.editInspectorState((payload, ctx) => {\n if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {\n const inspectedStore = payload.nodeId === PINIA_ROOT_ID\n ? pinia\n : pinia._s.get(payload.nodeId);\n if (!inspectedStore) {\n return toastMessage(`store \"${payload.nodeId}\" not found`, 'error');\n }\n const { path } = payload;\n if (!isPinia(inspectedStore)) {\n // access only the state\n if (path.length !== 1 ||\n !inspectedStore._customProperties.has(path[0]) ||\n path[0] in inspectedStore.$state) {\n path.unshift('$state');\n }\n }\n else {\n // Root access, we can omit the `.value` because the devtools API does it for us\n path.unshift('state');\n }\n isTimelineActive = false;\n payload.set(inspectedStore, path, payload.state.value);\n isTimelineActive = true;\n }\n });\n api.on.editComponentState((payload) => {\n if (payload.type.startsWith('🍍')) {\n const storeId = payload.type.replace(/^🍍\\s*/, '');\n const store = pinia._s.get(storeId);\n if (!store) {\n return toastMessage(`store \"${storeId}\" not found`, 'error');\n }\n const { path } = payload;\n if (path[0] !== 'state') {\n return toastMessage(`Invalid path for store \"${storeId}\":\\n${path}\\nOnly state can be modified.`);\n }\n // rewrite the first entry to be able to directly set the state as\n // well as any other path\n path[0] = '$state';\n isTimelineActive = false;\n payload.set(store, path, payload.state.value);\n isTimelineActive = true;\n }\n });\n });\n}\nfunction addStoreToDevtools(app, store) {\n if (!componentStateTypes.includes(getStoreType(store.$id))) {\n componentStateTypes.push(getStoreType(store.$id));\n }\n setupDevtoolsPlugin({\n id: 'dev.esm.pinia',\n label: 'Pinia 🍍',\n logo: 'https://pinia.vuejs.org/logo.svg',\n packageName: 'pinia',\n homepage: 'https://pinia.vuejs.org',\n componentStateTypes,\n app,\n settings: {\n logStoreChanges: {\n label: 'Notify about new/deleted stores',\n type: 'boolean',\n defaultValue: true,\n },\n // useEmojis: {\n // label: 'Use emojis in messages ⚡️',\n // type: 'boolean',\n // defaultValue: true,\n // },\n },\n }, (api) => {\n // gracefully handle errors\n const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;\n store.$onAction(({ after, onError, name, args }) => {\n const groupId = runningActionId++;\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: {\n time: now(),\n title: '🛫 ' + name,\n subtitle: 'start',\n data: {\n store: formatDisplay(store.$id),\n action: formatDisplay(name),\n args,\n },\n groupId,\n },\n });\n after((result) => {\n activeAction = undefined;\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: {\n time: now(),\n title: '🛬 ' + name,\n subtitle: 'end',\n data: {\n store: formatDisplay(store.$id),\n action: formatDisplay(name),\n args,\n result,\n },\n groupId,\n },\n });\n });\n onError((error) => {\n activeAction = undefined;\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: {\n time: now(),\n logType: 'error',\n title: '💥 ' + name,\n subtitle: 'end',\n data: {\n store: formatDisplay(store.$id),\n action: formatDisplay(name),\n args,\n error,\n },\n groupId,\n },\n });\n });\n }, true);\n store._customProperties.forEach((name) => {\n watch(() => unref(store[name]), (newValue, oldValue) => {\n api.notifyComponentUpdate();\n api.sendInspectorState(INSPECTOR_ID);\n if (isTimelineActive) {\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: {\n time: now(),\n title: 'Change',\n subtitle: name,\n data: {\n newValue,\n oldValue,\n },\n groupId: activeAction,\n },\n });\n }\n }, { deep: true });\n });\n store.$subscribe(({ events, type }, state) => {\n api.notifyComponentUpdate();\n api.sendInspectorState(INSPECTOR_ID);\n if (!isTimelineActive)\n return;\n // rootStore.state[store.id] = state\n const eventData = {\n time: now(),\n title: formatMutationType(type),\n data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),\n groupId: activeAction,\n };\n if (type === MutationType.patchFunction) {\n eventData.subtitle = '⤵️';\n }\n else if (type === MutationType.patchObject) {\n eventData.subtitle = '🧩';\n }\n else if (events && !Array.isArray(events)) {\n eventData.subtitle = events.type;\n }\n if (events) {\n eventData.data['rawEvent(s)'] = {\n _custom: {\n display: 'DebuggerEvent',\n type: 'object',\n tooltip: 'raw DebuggerEvent[]',\n value: events,\n },\n };\n }\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: eventData,\n });\n }, { detached: true, flush: 'sync' });\n const hotUpdate = store._hotUpdate;\n store._hotUpdate = markRaw((newStore) => {\n hotUpdate(newStore);\n api.addTimelineEvent({\n layerId: MUTATIONS_LAYER_ID,\n event: {\n time: now(),\n title: '🔥 ' + store.$id,\n subtitle: 'HMR update',\n data: {\n store: formatDisplay(store.$id),\n info: formatDisplay(`HMR update`),\n },\n },\n });\n // update the devtools too\n api.notifyComponentUpdate();\n api.sendInspectorTree(INSPECTOR_ID);\n api.sendInspectorState(INSPECTOR_ID);\n });\n const { $dispose } = store;\n store.$dispose = () => {\n $dispose();\n api.notifyComponentUpdate();\n api.sendInspectorTree(INSPECTOR_ID);\n api.sendInspectorState(INSPECTOR_ID);\n api.getSettings().logStoreChanges &&\n toastMessage(`Disposed \"${store.$id}\" store 🗑`);\n };\n // trigger an update so it can display new registered stores\n api.notifyComponentUpdate();\n api.sendInspectorTree(INSPECTOR_ID);\n api.sendInspectorState(INSPECTOR_ID);\n api.getSettings().logStoreChanges &&\n toastMessage(`\"${store.$id}\" store installed 🆕`);\n });\n}\nlet runningActionId = 0;\nlet activeAction;\n/**\n * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the\n * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state\n * mutation to the action.\n *\n * @param store - store to patch\n * @param actionNames - list of actionst to patch\n */\nfunction patchActionForGrouping(store, actionNames, wrapWithProxy) {\n // original actions of the store as they are given by pinia. We are going to override them\n const actions = actionNames.reduce((storeActions, actionName) => {\n // use toRaw to avoid tracking #541\n storeActions[actionName] = toRaw(store)[actionName];\n return storeActions;\n }, {});\n for (const actionName in actions) {\n store[actionName] = function () {\n // the running action id is incremented in a before action hook\n const _actionId = runningActionId;\n const trackedStore = wrapWithProxy\n ? new Proxy(store, {\n get(...args) {\n activeAction = _actionId;\n return Reflect.get(...args);\n },\n set(...args) {\n activeAction = _actionId;\n return Reflect.set(...args);\n },\n })\n : store;\n // For Setup Stores we need https://github.com/tc39/proposal-async-context\n activeAction = _actionId;\n const retValue = actions[actionName].apply(trackedStore, arguments);\n // this is safer as async actions in Setup Stores would associate mutations done outside of the action\n activeAction = undefined;\n return retValue;\n };\n }\n}\n/**\n * pinia.use(devtoolsPlugin)\n */\nfunction devtoolsPlugin({ app, store, options }) {\n // HMR module\n if (store.$id.startsWith('__hot:')) {\n return;\n }\n // detect option api vs setup api\n store._isOptionsAPI = !!options.state;\n patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);\n // Upgrade the HMR to also update the new actions\n const originalHotUpdate = store._hotUpdate;\n toRaw(store)._hotUpdate = function (newStore) {\n originalHotUpdate.apply(this, arguments);\n patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);\n };\n addStoreToDevtools(app, \n // FIXME: is there a way to allow the assignment from Store to StoreGeneric?\n store);\n}\n\n/**\n * Creates a Pinia instance to be used by the application\n */\nfunction createPinia() {\n const scope = effectScope(true);\n // NOTE: here we could check the window object for a state and directly set it\n // if there is anything like it with Vue 3 SSR\n const state = scope.run(() => ref({}));\n let _p = [];\n // plugins added before calling app.use(pinia)\n let toBeInstalled = [];\n const pinia = markRaw({\n install(app) {\n // this allows calling useStore() outside of a component setup after\n // installing pinia's plugin\n setActivePinia(pinia);\n if (!isVue2) {\n pinia._a = app;\n app.provide(piniaSymbol, pinia);\n app.config.globalProperties.$pinia = pinia;\n /* istanbul ignore else */\n if (USE_DEVTOOLS) {\n registerPiniaDevtools(app, pinia);\n }\n toBeInstalled.forEach((plugin) => _p.push(plugin));\n toBeInstalled = [];\n }\n },\n use(plugin) {\n if (!this._a && !isVue2) {\n toBeInstalled.push(plugin);\n }\n else {\n _p.push(plugin);\n }\n return this;\n },\n _p,\n // it's actually undefined here\n // @ts-expect-error\n _a: null,\n _e: scope,\n _s: new Map(),\n state,\n });\n // pinia devtools rely on dev only features so they cannot be forced unless\n // the dev build of Vue is used. Avoid old browsers like IE11.\n if (USE_DEVTOOLS && typeof Proxy !== 'undefined') {\n pinia.use(devtoolsPlugin);\n }\n return pinia;\n}\n\n/**\n * Checks if a function is a `StoreDefinition`.\n *\n * @param fn - object to test\n * @returns true if `fn` is a StoreDefinition\n */\nconst isUseStore = (fn) => {\n return typeof fn === 'function' && typeof fn.$id === 'string';\n};\n/**\n * Mutates in place `newState` with `oldState` to _hot update_ it. It will\n * remove any key not existing in `newState` and recursively merge plain\n * objects.\n *\n * @param newState - new state object to be patched\n * @param oldState - old state that should be used to patch newState\n * @returns - newState\n */\nfunction patchObject(newState, oldState) {\n // no need to go through symbols because they cannot be serialized anyway\n for (const key in oldState) {\n const subPatch = oldState[key];\n // skip the whole sub tree\n if (!(key in newState)) {\n continue;\n }\n const targetValue = newState[key];\n if (isPlainObject(targetValue) &&\n isPlainObject(subPatch) &&\n !isRef(subPatch) &&\n !isReactive(subPatch)) {\n newState[key] = patchObject(targetValue, subPatch);\n }\n else {\n // objects are either a bit more complex (e.g. refs) or primitives, so we\n // just set the whole thing\n if (isVue2) {\n set(newState, key, subPatch);\n }\n else {\n newState[key] = subPatch;\n }\n }\n }\n return newState;\n}\n/**\n * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.\n *\n * @example\n * ```js\n * const useUser = defineStore(...)\n * if (import.meta.hot) {\n * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))\n * }\n * ```\n *\n * @param initialUseStore - return of the defineStore to hot update\n * @param hot - `import.meta.hot`\n */\nfunction acceptHMRUpdate(initialUseStore, hot) {\n // strip as much as possible from iife.prod\n if (!(process.env.NODE_ENV !== 'production')) {\n return () => { };\n }\n return (newModule) => {\n const pinia = hot.data.pinia || initialUseStore._pinia;\n if (!pinia) {\n // this store is still not used\n return;\n }\n // preserve the pinia instance across loads\n hot.data.pinia = pinia;\n // console.log('got data', newStore)\n for (const exportName in newModule) {\n const useStore = newModule[exportName];\n // console.log('checking for', exportName)\n if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {\n // console.log('Accepting update for', useStore.$id)\n const id = useStore.$id;\n if (id !== initialUseStore.$id) {\n console.warn(`The id of the store changed from \"${initialUseStore.$id}\" to \"${id}\". Reloading.`);\n // return import.meta.hot.invalidate()\n return hot.invalidate();\n }\n const existingStore = pinia._s.get(id);\n if (!existingStore) {\n console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);\n return;\n }\n useStore(pinia, existingStore);\n }\n }\n };\n}\n\nconst noop = () => { };\nfunction addSubscription(subscriptions, callback, detached, onCleanup = noop) {\n subscriptions.push(callback);\n const removeSubscription = () => {\n const idx = subscriptions.indexOf(callback);\n if (idx > -1) {\n subscriptions.splice(idx, 1);\n onCleanup();\n }\n };\n if (!detached && getCurrentScope()) {\n onScopeDispose(removeSubscription);\n }\n return removeSubscription;\n}\nfunction triggerSubscriptions(subscriptions, ...args) {\n subscriptions.slice().forEach((callback) => {\n callback(...args);\n });\n}\n\nconst fallbackRunWithContext = (fn) => fn();\nfunction mergeReactiveObjects(target, patchToApply) {\n // Handle Map instances\n if (target instanceof Map && patchToApply instanceof Map) {\n patchToApply.forEach((value, key) => target.set(key, value));\n }\n // Handle Set instances\n if (target instanceof Set && patchToApply instanceof Set) {\n patchToApply.forEach(target.add, target);\n }\n // no need to go through symbols because they cannot be serialized anyway\n for (const key in patchToApply) {\n if (!patchToApply.hasOwnProperty(key))\n continue;\n const subPatch = patchToApply[key];\n const targetValue = target[key];\n if (isPlainObject(targetValue) &&\n isPlainObject(subPatch) &&\n target.hasOwnProperty(key) &&\n !isRef(subPatch) &&\n !isReactive(subPatch)) {\n // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might\n // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that\n // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.\n target[key] = mergeReactiveObjects(targetValue, subPatch);\n }\n else {\n // @ts-expect-error: subPatch is a valid value\n target[key] = subPatch;\n }\n }\n return target;\n}\nconst skipHydrateSymbol = (process.env.NODE_ENV !== 'production')\n ? Symbol('pinia:skipHydration')\n : /* istanbul ignore next */ Symbol();\nconst skipHydrateMap = /*#__PURE__*/ new WeakMap();\n/**\n * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a\n * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.\n *\n * @param obj - target object\n * @returns obj\n */\nfunction skipHydrate(obj) {\n return isVue2\n ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...\n /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj\n : Object.defineProperty(obj, skipHydrateSymbol, {});\n}\n/**\n * Returns whether a value should be hydrated\n *\n * @param obj - target variable\n * @returns true if `obj` should be hydrated\n */\nfunction shouldHydrate(obj) {\n return isVue2\n ? /* istanbul ignore next */ !skipHydrateMap.has(obj)\n : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);\n}\nconst { assign } = Object;\nfunction isComputed(o) {\n return !!(isRef(o) && o.effect);\n}\nfunction createOptionsStore(id, options, pinia, hot) {\n const { state, actions, getters } = options;\n const initialState = pinia.state.value[id];\n let store;\n function setup() {\n if (!initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {\n /* istanbul ignore if */\n if (isVue2) {\n set(pinia.state.value, id, state ? state() : {});\n }\n else {\n pinia.state.value[id] = state ? state() : {};\n }\n }\n // avoid creating a state in pinia.state.value\n const localState = (process.env.NODE_ENV !== 'production') && hot\n ? // use ref() to unwrap refs inside state TODO: check if this is still necessary\n toRefs(ref(state ? state() : {}).value)\n : toRefs(pinia.state.value[id]);\n return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {\n if ((process.env.NODE_ENV !== 'production') && name in localState) {\n console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with \"${name}\" in store \"${id}\".`);\n }\n computedGetters[name] = markRaw(computed(() => {\n setActivePinia(pinia);\n // it was created just before\n const store = pinia._s.get(id);\n // allow cross using stores\n /* istanbul ignore next */\n if (isVue2 && !store._r)\n return;\n // @ts-expect-error\n // return getters![name].call(context, context)\n // TODO: avoid reading the getter while assigning with a global variable\n return getters[name].call(store, store);\n }));\n return computedGetters;\n }, {}));\n }\n store = createSetupStore(id, setup, options, pinia, hot, true);\n return store;\n}\nfunction createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {\n let scope;\n const optionsForPlugin = assign({ actions: {} }, options);\n /* istanbul ignore if */\n if ((process.env.NODE_ENV !== 'production') && !pinia._e.active) {\n throw new Error('Pinia destroyed');\n }\n // watcher options for $subscribe\n const $subscribeOptions = {\n deep: true,\n // flush: 'post',\n };\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production') && !isVue2) {\n $subscribeOptions.onTrigger = (event) => {\n /* istanbul ignore else */\n if (isListening) {\n debuggerEvents = event;\n // avoid triggering this while the store is being built and the state is being set in pinia\n }\n else if (isListening == false && !store._hotUpdating) {\n // let patch send all the events together later\n /* istanbul ignore else */\n if (Array.isArray(debuggerEvents)) {\n debuggerEvents.push(event);\n }\n else {\n console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');\n }\n }\n };\n }\n // internal state\n let isListening; // set to true at the end\n let isSyncListening; // set to true at the end\n let subscriptions = [];\n let actionSubscriptions = [];\n let debuggerEvents;\n const initialState = pinia.state.value[$id];\n // avoid setting the state for option stores if it is set\n // by the setup\n if (!isOptionsStore && !initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {\n /* istanbul ignore if */\n if (isVue2) {\n set(pinia.state.value, $id, {});\n }\n else {\n pinia.state.value[$id] = {};\n }\n }\n const hotState = ref({});\n // avoid triggering too many listeners\n // https://github.com/vuejs/pinia/issues/1129\n let activeListener;\n function $patch(partialStateOrMutator) {\n let subscriptionMutation;\n isListening = isSyncListening = false;\n // reset the debugger events since patches are sync\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production')) {\n debuggerEvents = [];\n }\n if (typeof partialStateOrMutator === 'function') {\n partialStateOrMutator(pinia.state.value[$id]);\n subscriptionMutation = {\n type: MutationType.patchFunction,\n storeId: $id,\n events: debuggerEvents,\n };\n }\n else {\n mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);\n subscriptionMutation = {\n type: MutationType.patchObject,\n payload: partialStateOrMutator,\n storeId: $id,\n events: debuggerEvents,\n };\n }\n const myListenerId = (activeListener = Symbol());\n nextTick().then(() => {\n if (activeListener === myListenerId) {\n isListening = true;\n }\n });\n isSyncListening = true;\n // because we paused the watcher, we need to manually call the subscriptions\n triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);\n }\n const $reset = isOptionsStore\n ? function $reset() {\n const { state } = options;\n const newState = state ? state() : {};\n // we use a patch to group all changes into one single subscription\n this.$patch(($state) => {\n assign($state, newState);\n });\n }\n : /* istanbul ignore next */\n (process.env.NODE_ENV !== 'production')\n ? () => {\n throw new Error(`🍍: Store \"${$id}\" is built using the setup syntax and does not implement $reset().`);\n }\n : noop;\n function $dispose() {\n scope.stop();\n subscriptions = [];\n actionSubscriptions = [];\n pinia._s.delete($id);\n }\n /**\n * Wraps an action to handle subscriptions.\n *\n * @param name - name of the action\n * @param action - action to wrap\n * @returns a wrapped action to handle subscriptions\n */\n function wrapAction(name, action) {\n return function () {\n setActivePinia(pinia);\n const args = Array.from(arguments);\n const afterCallbackList = [];\n const onErrorCallbackList = [];\n function after(callback) {\n afterCallbackList.push(callback);\n }\n function onError(callback) {\n onErrorCallbackList.push(callback);\n }\n // @ts-expect-error\n triggerSubscriptions(actionSubscriptions, {\n args,\n name,\n store,\n after,\n onError,\n });\n let ret;\n try {\n ret = action.apply(this && this.$id === $id ? this : store, args);\n // handle sync errors\n }\n catch (error) {\n triggerSubscriptions(onErrorCallbackList, error);\n throw error;\n }\n if (ret instanceof Promise) {\n return ret\n .then((value) => {\n triggerSubscriptions(afterCallbackList, value);\n return value;\n })\n .catch((error) => {\n triggerSubscriptions(onErrorCallbackList, error);\n return Promise.reject(error);\n });\n }\n // trigger after callbacks\n triggerSubscriptions(afterCallbackList, ret);\n return ret;\n };\n }\n const _hmrPayload = /*#__PURE__*/ markRaw({\n actions: {},\n getters: {},\n state: [],\n hotState,\n });\n const partialStore = {\n _p: pinia,\n // _s: scope,\n $id,\n $onAction: addSubscription.bind(null, actionSubscriptions),\n $patch,\n $reset,\n $subscribe(callback, options = {}) {\n const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());\n const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {\n if (options.flush === 'sync' ? isSyncListening : isListening) {\n callback({\n storeId: $id,\n type: MutationType.direct,\n events: debuggerEvents,\n }, state);\n }\n }, assign({}, $subscribeOptions, options)));\n return removeSubscription;\n },\n $dispose,\n };\n /* istanbul ignore if */\n if (isVue2) {\n // start as non ready\n partialStore._r = false;\n }\n const store = reactive((process.env.NODE_ENV !== 'production') || USE_DEVTOOLS\n ? assign({\n _hmrPayload,\n _customProperties: markRaw(new Set()), // devtools custom properties\n }, partialStore\n // must be added later\n // setupStore\n )\n : partialStore);\n // store the partial store now so the setup of stores can instantiate each other before they are finished without\n // creating infinite loops.\n pinia._s.set($id, store);\n const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;\n // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped\n const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(setup)));\n // overwrite existing actions to support $onAction\n for (const key in setupStore) {\n const prop = setupStore[key];\n if ((isRef(prop) && !isComputed(prop)) || isReactive(prop)) {\n // mark it as a piece of state to be serialized\n if ((process.env.NODE_ENV !== 'production') && hot) {\n set(hotState.value, key, toRef(setupStore, key));\n // createOptionStore directly sets the state in pinia.state.value so we\n // can just skip that\n }\n else if (!isOptionsStore) {\n // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created\n if (initialState && shouldHydrate(prop)) {\n if (isRef(prop)) {\n prop.value = initialState[key];\n }\n else {\n // probably a reactive object, lets recursively assign\n // @ts-expect-error: prop is unknown\n mergeReactiveObjects(prop, initialState[key]);\n }\n }\n // transfer the ref to the pinia state to keep everything in sync\n /* istanbul ignore if */\n if (isVue2) {\n set(pinia.state.value[$id], key, prop);\n }\n else {\n pinia.state.value[$id][key] = prop;\n }\n }\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production')) {\n _hmrPayload.state.push(key);\n }\n // action\n }\n else if (typeof prop === 'function') {\n // @ts-expect-error: we are overriding the function we avoid wrapping if\n const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : wrapAction(key, prop);\n // this a hot module replacement store because the hotUpdate method needs\n // to do it with the right context\n /* istanbul ignore if */\n if (isVue2) {\n set(setupStore, key, actionValue);\n }\n else {\n // @ts-expect-error\n setupStore[key] = actionValue;\n }\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production')) {\n _hmrPayload.actions[key] = prop;\n }\n // list actions so they can be used in plugins\n // @ts-expect-error\n optionsForPlugin.actions[key] = prop;\n }\n else if ((process.env.NODE_ENV !== 'production')) {\n // add getters for devtools\n if (isComputed(prop)) {\n _hmrPayload.getters[key] = isOptionsStore\n ? // @ts-expect-error\n options.getters[key]\n : prop;\n if (IS_CLIENT) {\n const getters = setupStore._getters ||\n // @ts-expect-error: same\n (setupStore._getters = markRaw([]));\n getters.push(key);\n }\n }\n }\n }\n // add the state, getters, and action properties\n /* istanbul ignore if */\n if (isVue2) {\n Object.keys(setupStore).forEach((key) => {\n set(store, key, setupStore[key]);\n });\n }\n else {\n assign(store, setupStore);\n // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.\n // Make `storeToRefs()` work with `reactive()` #799\n assign(toRaw(store), setupStore);\n }\n // use this instead of a computed with setter to be able to create it anywhere\n // without linking the computed lifespan to wherever the store is first\n // created.\n Object.defineProperty(store, '$state', {\n get: () => ((process.env.NODE_ENV !== 'production') && hot ? hotState.value : pinia.state.value[$id]),\n set: (state) => {\n /* istanbul ignore if */\n if ((process.env.NODE_ENV !== 'production') && hot) {\n throw new Error('cannot set hotState');\n }\n $patch(($state) => {\n assign($state, state);\n });\n },\n });\n // add the hotUpdate before plugins to allow them to override it\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production')) {\n store._hotUpdate = markRaw((newStore) => {\n store._hotUpdating = true;\n newStore._hmrPayload.state.forEach((stateKey) => {\n if (stateKey in store.$state) {\n const newStateTarget = newStore.$state[stateKey];\n const oldStateSource = store.$state[stateKey];\n if (typeof newStateTarget === 'object' &&\n isPlainObject(newStateTarget) &&\n isPlainObject(oldStateSource)) {\n patchObject(newStateTarget, oldStateSource);\n }\n else {\n // transfer the ref\n newStore.$state[stateKey] = oldStateSource;\n }\n }\n // patch direct access properties to allow store.stateProperty to work as\n // store.$state.stateProperty\n set(store, stateKey, toRef(newStore.$state, stateKey));\n });\n // remove deleted state properties\n Object.keys(store.$state).forEach((stateKey) => {\n if (!(stateKey in newStore.$state)) {\n del(store, stateKey);\n }\n });\n // avoid devtools logging this as a mutation\n isListening = false;\n isSyncListening = false;\n pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState');\n isSyncListening = true;\n nextTick().then(() => {\n isListening = true;\n });\n for (const actionName in newStore._hmrPayload.actions) {\n const action = newStore[actionName];\n set(store, actionName, wrapAction(actionName, action));\n }\n // TODO: does this work in both setup and option store?\n for (const getterName in newStore._hmrPayload.getters) {\n const getter = newStore._hmrPayload.getters[getterName];\n const getterValue = isOptionsStore\n ? // special handling of options api\n computed(() => {\n setActivePinia(pinia);\n return getter.call(store, store);\n })\n : getter;\n set(store, getterName, getterValue);\n }\n // remove deleted getters\n Object.keys(store._hmrPayload.getters).forEach((key) => {\n if (!(key in newStore._hmrPayload.getters)) {\n del(store, key);\n }\n });\n // remove old actions\n Object.keys(store._hmrPayload.actions).forEach((key) => {\n if (!(key in newStore._hmrPayload.actions)) {\n del(store, key);\n }\n });\n // update the values used in devtools and to allow deleting new properties later on\n store._hmrPayload = newStore._hmrPayload;\n store._getters = newStore._getters;\n store._hotUpdating = false;\n });\n }\n if (USE_DEVTOOLS) {\n const nonEnumerable = {\n writable: true,\n configurable: true,\n // avoid warning on devtools trying to display this property\n enumerable: false,\n };\n ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {\n Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));\n });\n }\n /* istanbul ignore if */\n if (isVue2) {\n // mark the store as ready before plugins\n store._r = true;\n }\n // apply all plugins\n pinia._p.forEach((extender) => {\n /* istanbul ignore else */\n if (USE_DEVTOOLS) {\n const extensions = scope.run(() => extender({\n store,\n app: pinia._a,\n pinia,\n options: optionsForPlugin,\n }));\n Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));\n assign(store, extensions);\n }\n else {\n assign(store, scope.run(() => extender({\n store,\n app: pinia._a,\n pinia,\n options: optionsForPlugin,\n })));\n }\n });\n if ((process.env.NODE_ENV !== 'production') &&\n store.$state &&\n typeof store.$state === 'object' &&\n typeof store.$state.constructor === 'function' &&\n !store.$state.constructor.toString().includes('[native code]')) {\n console.warn(`[🍍]: The \"state\" must be a plain object. It cannot be\\n` +\n `\\tstate: () => new MyClass()\\n` +\n `Found in store \"${store.$id}\".`);\n }\n // only apply hydrate to option stores with an initial state in pinia\n if (initialState &&\n isOptionsStore &&\n options.hydrate) {\n options.hydrate(store.$state, initialState);\n }\n isListening = true;\n isSyncListening = true;\n return store;\n}\nfunction defineStore(\n// TODO: add proper types from above\nidOrOptions, setup, setupOptions) {\n let id;\n let options;\n const isSetupStore = typeof setup === 'function';\n if (typeof idOrOptions === 'string') {\n id = idOrOptions;\n // the option store setup will contain the actual options in this case\n options = isSetupStore ? setupOptions : setup;\n }\n else {\n options = idOrOptions;\n id = idOrOptions.id;\n if ((process.env.NODE_ENV !== 'production') && typeof id !== 'string') {\n throw new Error(`[🍍]: \"defineStore()\" must be passed a store id as its first argument.`);\n }\n }\n function useStore(pinia, hot) {\n const hasContext = hasInjectionContext();\n pinia =\n // in test mode, ignore the argument provided as we can always retrieve a\n // pinia instance with getActivePinia()\n ((process.env.NODE_ENV === 'test') && activePinia && activePinia._testing ? null : pinia) ||\n (hasContext ? inject(piniaSymbol, null) : null);\n if (pinia)\n setActivePinia(pinia);\n if ((process.env.NODE_ENV !== 'production') && !activePinia) {\n throw new Error(`[🍍]: \"getActivePinia()\" was called but there was no active Pinia. Are you trying to use a store before calling \"app.use(pinia)\"?\\n` +\n `See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.\\n` +\n `This will fail in production.`);\n }\n pinia = activePinia;\n if (!pinia._s.has(id)) {\n // creating the store registers it in `pinia._s`\n if (isSetupStore) {\n createSetupStore(id, setup, options, pinia);\n }\n else {\n createOptionsStore(id, options, pinia);\n }\n /* istanbul ignore else */\n if ((process.env.NODE_ENV !== 'production')) {\n // @ts-expect-error: not the right inferred type\n useStore._pinia = pinia;\n }\n }\n const store = pinia._s.get(id);\n if ((process.env.NODE_ENV !== 'production') && hot) {\n const hotId = '__hot:' + id;\n const newStore = isSetupStore\n ? createSetupStore(hotId, setup, options, pinia, true)\n : createOptionsStore(hotId, assign({}, options), pinia, true);\n hot._hotUpdate(newStore);\n // cleanup the state properties and the store from the cache\n delete pinia.state.value[hotId];\n pinia._s.delete(hotId);\n }\n if ((process.env.NODE_ENV !== 'production') && IS_CLIENT) {\n const currentInstance = getCurrentInstance();\n // save stores in instances to access them devtools\n if (currentInstance &&\n currentInstance.proxy &&\n // avoid adding stores that are just built for hot module replacement\n !hot) {\n const vm = currentInstance.proxy;\n const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});\n cache[id] = store;\n }\n }\n // StoreGeneric cannot be casted towards Store\n return store;\n }\n useStore.$id = id;\n return useStore;\n}\n\nlet mapStoreSuffix = 'Store';\n/**\n * Changes the suffix added by `mapStores()`. Can be set to an empty string.\n * Defaults to `\"Store\"`. Make sure to extend the MapStoresCustomization\n * interface if you are using TypeScript.\n *\n * @param suffix - new suffix\n */\nfunction setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS\n) {\n mapStoreSuffix = suffix;\n}\n/**\n * Allows using stores without the composition API (`setup()`) by generating an\n * object to be spread in the `computed` field of a component. It accepts a list\n * of store definitions.\n *\n * @example\n * ```js\n * export default {\n * computed: {\n * // other computed properties\n * ...mapStores(useUserStore, useCartStore)\n * },\n *\n * created() {\n * this.userStore // store with id \"user\"\n * this.cartStore // store with id \"cart\"\n * }\n * }\n * ```\n *\n * @param stores - list of stores to map to an object\n */\nfunction mapStores(...stores) {\n if ((process.env.NODE_ENV !== 'production') && Array.isArray(stores[0])) {\n console.warn(`[🍍]: Directly pass all stores to \"mapStores()\" without putting them in an array:\\n` +\n `Replace\\n` +\n `\\tmapStores([useAuthStore, useCartStore])\\n` +\n `with\\n` +\n `\\tmapStores(useAuthStore, useCartStore)\\n` +\n `This will fail in production if not fixed.`);\n stores = stores[0];\n }\n return stores.reduce((reduced, useStore) => {\n // @ts-expect-error: $id is added by defineStore\n reduced[useStore.$id + mapStoreSuffix] = function () {\n return useStore(this.$pinia);\n };\n return reduced;\n }, {});\n}\n/**\n * Allows using state and getters from one store without using the composition\n * API (`setup()`) by generating an object to be spread in the `computed` field\n * of a component.\n *\n * @param useStore - store to map from\n * @param keysOrMapper - array or object\n */\nfunction mapState(useStore, keysOrMapper) {\n return Array.isArray(keysOrMapper)\n ? keysOrMapper.reduce((reduced, key) => {\n reduced[key] = function () {\n return useStore(this.$pinia)[key];\n };\n return reduced;\n }, {})\n : Object.keys(keysOrMapper).reduce((reduced, key) => {\n // @ts-expect-error\n reduced[key] = function () {\n const store = useStore(this.$pinia);\n const storeKey = keysOrMapper[key];\n // for some reason TS is unable to infer the type of storeKey to be a\n // function\n return typeof storeKey === 'function'\n ? storeKey.call(this, store)\n : store[storeKey];\n };\n return reduced;\n }, {});\n}\n/**\n * Alias for `mapState()`. You should use `mapState()` instead.\n * @deprecated use `mapState()` instead.\n */\nconst mapGetters = mapState;\n/**\n * Allows directly using actions from your store without using the composition\n * API (`setup()`) by generating an object to be spread in the `methods` field\n * of a component.\n *\n * @param useStore - store to map from\n * @param keysOrMapper - array or object\n */\nfunction mapActions(useStore, keysOrMapper) {\n return Array.isArray(keysOrMapper)\n ? keysOrMapper.reduce((reduced, key) => {\n // @ts-expect-error\n reduced[key] = function (...args) {\n return useStore(this.$pinia)[key](...args);\n };\n return reduced;\n }, {})\n : Object.keys(keysOrMapper).reduce((reduced, key) => {\n // @ts-expect-error\n reduced[key] = function (...args) {\n return useStore(this.$pinia)[keysOrMapper[key]](...args);\n };\n return reduced;\n }, {});\n}\n/**\n * Allows using state and getters from one store without using the composition\n * API (`setup()`) by generating an object to be spread in the `computed` field\n * of a component.\n *\n * @param useStore - store to map from\n * @param keysOrMapper - array or object\n */\nfunction mapWritableState(useStore, keysOrMapper) {\n return Array.isArray(keysOrMapper)\n ? keysOrMapper.reduce((reduced, key) => {\n // @ts-ignore\n reduced[key] = {\n get() {\n return useStore(this.$pinia)[key];\n },\n set(value) {\n // it's easier to type it here as any\n return (useStore(this.$pinia)[key] = value);\n },\n };\n return reduced;\n }, {})\n : Object.keys(keysOrMapper).reduce((reduced, key) => {\n // @ts-ignore\n reduced[key] = {\n get() {\n return useStore(this.$pinia)[keysOrMapper[key]];\n },\n set(value) {\n // it's easier to type it here as any\n return (useStore(this.$pinia)[keysOrMapper[key]] = value);\n },\n };\n return reduced;\n }, {});\n}\n\n/**\n * Creates an object of references with all the state, getters, and plugin-added\n * state properties of the store. Similar to `toRefs()` but specifically\n * designed for Pinia stores so methods and non reactive properties are\n * completely ignored.\n *\n * @param store - store to extract the refs from\n */\nfunction storeToRefs(store) {\n // See https://github.com/vuejs/pinia/issues/852\n // It's easier to just use toRefs() even if it includes more stuff\n if (isVue2) {\n // @ts-expect-error: toRefs include methods and others\n return toRefs(store);\n }\n else {\n store = toRaw(store);\n const refs = {};\n for (const key in store) {\n const value = store[key];\n if (isRef(value) || isReactive(value)) {\n // @ts-expect-error: the key is state or getter\n refs[key] =\n // ---\n toRef(store, key);\n }\n }\n return refs;\n }\n}\n\n/**\n * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need\n * this plugin if you are using Nuxt.js**. Use the `buildModule` instead:\n * https://pinia.vuejs.org/ssr/nuxt.html.\n *\n * @example\n * ```js\n * import Vue from 'vue'\n * import { PiniaVuePlugin, createPinia } from 'pinia'\n *\n * Vue.use(PiniaVuePlugin)\n * const pinia = createPinia()\n *\n * new Vue({\n * el: '#app',\n * // ...\n * pinia,\n * })\n * ```\n *\n * @param _Vue - `Vue` imported from 'vue'.\n */\nconst PiniaVuePlugin = function (_Vue) {\n // Equivalent of\n // app.config.globalProperties.$pinia = pinia\n _Vue.mixin({\n beforeCreate() {\n const options = this.$options;\n if (options.pinia) {\n const pinia = options.pinia;\n // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/main/src/apis/inject.ts#L31\n /* istanbul ignore else */\n if (!this._provided) {\n const provideCache = {};\n Object.defineProperty(this, '_provided', {\n get: () => provideCache,\n set: (v) => Object.assign(provideCache, v),\n });\n }\n this._provided[piniaSymbol] = pinia;\n // propagate the pinia instance in an SSR friendly way\n // avoid adding it to nuxt twice\n /* istanbul ignore else */\n if (!this.$pinia) {\n this.$pinia = pinia;\n }\n pinia._a = this;\n if (IS_CLIENT) {\n // this allows calling useStore() outside of a component setup after\n // installing pinia's plugin\n setActivePinia(pinia);\n }\n if (USE_DEVTOOLS) {\n registerPiniaDevtools(pinia._a, pinia);\n }\n }\n else if (!this.$pinia && options.parent && options.parent.$pinia) {\n this.$pinia = options.parent.$pinia;\n }\n },\n destroyed() {\n delete this._pStores;\n },\n });\n};\n\nexport { MutationType, PiniaVuePlugin, acceptHMRUpdate, createPinia, defineStore, getActivePinia, mapActions, mapGetters, mapState, mapStores, mapWritableState, setActivePinia, setMapStoreSuffix, skipHydrate, storeToRefs };\n","// We should consider moving to https://primevue.org/dynamicdialog/ once everything is in Vue.\r\n// Currently we need to bridge between legacy app code and Vue app with a Pinia store.\r\n\r\nimport { defineStore } from 'pinia'\r\nimport { type Component, markRaw } from 'vue'\r\n\r\ninterface DialogState {\r\n isVisible: boolean\r\n title: string\r\n headerComponent: Component | null\r\n component: Component | null\r\n props: Record\r\n}\r\n\r\nexport const useDialogStore = defineStore('dialog', {\r\n state: (): DialogState => ({\r\n isVisible: false,\r\n title: '',\r\n headerComponent: null,\r\n component: null,\r\n props: {}\r\n }),\r\n\r\n actions: {\r\n showDialog(options: {\r\n title?: string\r\n headerComponent?: Component\r\n component: Component\r\n props?: Record\r\n }) {\r\n this.title = options.title\r\n this.headerComponent = markRaw(options.headerComponent)\r\n this.component = markRaw(options.component)\r\n this.props = options.props || {}\r\n this.isVisible = true\r\n },\r\n\r\n closeDialog() {\r\n this.isVisible = false\r\n }\r\n }\r\n})\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'BlankIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"rect\", {\n width: \"1\",\n height: \"1\",\n fill: \"currentColor\",\n \"fill-opacity\": \"0\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'CheckIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M4.86199 11.5948C4.78717 11.5923 4.71366 11.5745 4.64596 11.5426C4.57826 11.5107 4.51779 11.4652 4.46827 11.4091L0.753985 7.69483C0.683167 7.64891 0.623706 7.58751 0.580092 7.51525C0.536478 7.44299 0.509851 7.36177 0.502221 7.27771C0.49459 7.19366 0.506156 7.10897 0.536046 7.03004C0.565935 6.95111 0.613367 6.88 0.674759 6.82208C0.736151 6.76416 0.8099 6.72095 0.890436 6.69571C0.970973 6.67046 1.05619 6.66385 1.13966 6.67635C1.22313 6.68886 1.30266 6.72017 1.37226 6.76792C1.44186 6.81567 1.4997 6.8786 1.54141 6.95197L4.86199 10.2503L12.6397 2.49483C12.7444 2.42694 12.8689 2.39617 12.9932 2.40745C13.1174 2.41873 13.2343 2.47141 13.3251 2.55705C13.4159 2.64268 13.4753 2.75632 13.4938 2.87973C13.5123 3.00315 13.4888 3.1292 13.4271 3.23768L5.2557 11.4091C5.20618 11.4652 5.14571 11.5107 5.07801 11.5426C5.01031 11.5745 4.9368 11.5923 4.86199 11.5948Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'SearchIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M2.67602 11.0265C3.6661 11.688 4.83011 12.0411 6.02086 12.0411C6.81149 12.0411 7.59438 11.8854 8.32483 11.5828C8.87005 11.357 9.37808 11.0526 9.83317 10.6803L12.9769 13.8241C13.0323 13.8801 13.0983 13.9245 13.171 13.9548C13.2438 13.985 13.3219 14.0003 13.4007 14C13.4795 14.0003 13.5575 13.985 13.6303 13.9548C13.7031 13.9245 13.7691 13.8801 13.8244 13.8241C13.9367 13.7116 13.9998 13.5592 13.9998 13.4003C13.9998 13.2414 13.9367 13.089 13.8244 12.9765L10.6807 9.8328C11.053 9.37773 11.3573 8.86972 11.5831 8.32452C11.8857 7.59408 12.0414 6.81119 12.0414 6.02056C12.0414 4.8298 11.6883 3.66579 11.0268 2.67572C10.3652 1.68564 9.42494 0.913972 8.32483 0.45829C7.22472 0.00260857 6.01418 -0.116618 4.84631 0.115686C3.67844 0.34799 2.60568 0.921393 1.76369 1.76338C0.921698 2.60537 0.348296 3.67813 0.115991 4.84601C-0.116313 6.01388 0.00291375 7.22441 0.458595 8.32452C0.914277 9.42464 1.68595 10.3649 2.67602 11.0265ZM3.35565 2.0158C4.14456 1.48867 5.07206 1.20731 6.02086 1.20731C7.29317 1.20731 8.51338 1.71274 9.41304 2.6124C10.3127 3.51206 10.8181 4.73226 10.8181 6.00457C10.8181 6.95337 10.5368 7.88088 10.0096 8.66978C9.48251 9.45868 8.73328 10.0736 7.85669 10.4367C6.98011 10.7997 6.01554 10.8947 5.08496 10.7096C4.15439 10.5245 3.2996 10.0676 2.62869 9.39674C1.95778 8.72583 1.50089 7.87104 1.31579 6.94046C1.13068 6.00989 1.22568 5.04532 1.58878 4.16874C1.95187 3.29215 2.56675 2.54292 3.35565 2.0158Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-iconfield {\\n position: relative;\\n}\\n\\n.p-inputicon {\\n position: absolute;\\n top: 50%;\\n margin-top: calc(-1 * (\".concat(dt('icon.size'), \" / 2));\\n color: \").concat(dt('iconfield.icon.color'), \";\\n}\\n\\n.p-iconfield .p-inputicon:first-child {\\n left: \").concat(dt('form.field.padding.x'), \";\\n}\\n\\n.p-iconfield .p-inputicon:last-child {\\n right: \").concat(dt('form.field.padding.x'), \";\\n}\\n\\n.p-iconfield .p-inputtext:last-child {\\n padding-left: calc((\").concat(dt('form.field.padding.x'), \" * 2) + \").concat(dt('icon.size'), \");\\n}\\n\\n.p-iconfield .p-inputtext:first-child {\\n padding-right: calc((\").concat(dt('form.field.padding.x'), \" * 2) + \").concat(dt('icon.size'), \");\\n}\\n\");\n};\nvar classes = {\n root: 'p-iconfield'\n};\nvar IconFieldStyle = BaseStyle.extend({\n name: 'iconfield',\n theme: theme,\n classes: classes\n});\n\nexport { IconFieldStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport IconFieldStyle from 'primevue/iconfield/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseIconField',\n \"extends\": BaseComponent,\n style: IconFieldStyle,\n provide: function provide() {\n return {\n $pcIconField: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'IconField',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: 'p-inputicon'\n};\nvar InputIconStyle = BaseStyle.extend({\n name: 'inputicon',\n classes: classes\n});\n\nexport { InputIconStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport InputIconStyle from 'primevue/inputicon/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseInputIcon',\n \"extends\": BaseComponent,\n style: InputIconStyle,\n props: {\n \"class\": null\n },\n provide: function provide() {\n return {\n $pcInputIcon: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'InputIcon',\n \"extends\": script$1,\n inheritAttrs: false,\n computed: {\n containerClass: function containerClass() {\n return [this.cx('root'), this[\"class\"]];\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": $options.containerClass\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-inputtext {\\n font-family: inherit;\\n font-feature-settings: inherit;\\n font-size: 1rem;\\n color: \".concat(dt('inputtext.color'), \";\\n background: \").concat(dt('inputtext.background'), \";\\n padding: \").concat(dt('inputtext.padding.y'), \" \").concat(dt('inputtext.padding.x'), \";\\n border: 1px solid \").concat(dt('inputtext.border.color'), \";\\n transition: background \").concat(dt('inputtext.transition.duration'), \", color \").concat(dt('inputtext.transition.duration'), \", border-color \").concat(dt('inputtext.transition.duration'), \", outline-color \").concat(dt('inputtext.transition.duration'), \", box-shadow \").concat(dt('inputtext.transition.duration'), \";\\n appearance: none;\\n border-radius: \").concat(dt('inputtext.border.radius'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('inputtext.shadow'), \";\\n}\\n\\n.p-inputtext:enabled:hover {\\n border-color: \").concat(dt('inputtext.hover.border.color'), \";\\n}\\n\\n.p-inputtext:enabled:focus {\\n border-color: \").concat(dt('inputtext.focus.border.color'), \";\\n box-shadow: \").concat(dt('inputtext.focus.ring.shadow'), \";\\n outline: \").concat(dt('inputtext.focus.ring.width'), \" \").concat(dt('inputtext.focus.ring.style'), \" \").concat(dt('inputtext.focus.ring.color'), \";\\n outline-offset: \").concat(dt('inputtext.focus.ring.offset'), \";\\n}\\n\\n.p-inputtext.p-invalid {\\n border-color: \").concat(dt('inputtext.invalid.border.color'), \";\\n}\\n\\n.p-inputtext.p-variant-filled {\\n background: \").concat(dt('inputtext.filled.background'), \";\\n}\\n\\n.p-inputtext.p-variant-filled:enabled:focus {\\n background: \").concat(dt('inputtext.filled.focus.background'), \";\\n}\\n\\n.p-inputtext:disabled {\\n opacity: 1;\\n background: \").concat(dt('inputtext.disabled.background'), \";\\n color: \").concat(dt('inputtext.disabled.color'), \";\\n}\\n\\n.p-inputtext::placeholder {\\n color: \").concat(dt('inputtext.placeholder.color'), \";\\n}\\n\\n.p-inputtext-sm {\\n font-size: \").concat(dt('inputtext.sm.font.size'), \";\\n padding: \").concat(dt('inputtext.sm.padding.y'), \" \").concat(dt('inputtext.sm.padding.x'), \";\\n}\\n\\n.p-inputtext-lg {\\n font-size: \").concat(dt('inputtext.lg.font.size'), \";\\n padding: \").concat(dt('inputtext.lg.padding.y'), \" \").concat(dt('inputtext.lg.padding.x'), \";\\n}\\n\\n.p-inputtext-fluid {\\n width: 100%;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-inputtext p-component', {\n 'p-filled': instance.filled,\n 'p-inputtext-sm': props.size === 'small',\n 'p-inputtext-lg': props.size === 'large',\n 'p-invalid': props.invalid,\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled',\n 'p-inputtext-fluid': props.fluid\n }];\n }\n};\nvar InputTextStyle = BaseStyle.extend({\n name: 'inputtext',\n theme: theme,\n classes: classes\n});\n\nexport { InputTextStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport InputTextStyle from 'primevue/inputtext/style';\nimport { openBlock, createElementBlock, mergeProps } from 'vue';\n\nvar script$1 = {\n name: 'BaseInputText',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n size: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n fluid: {\n type: Boolean,\n \"default\": false\n }\n },\n style: InputTextStyle,\n provide: function provide() {\n return {\n $pcInputText: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'InputText',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n filled: this.filled,\n disabled: this.$attrs.disabled || this.$attrs.disabled === ''\n }\n });\n },\n onInput: function onInput(event) {\n this.$emit('update:modelValue', event.target.value);\n }\n },\n computed: {\n filled: function filled() {\n return this.modelValue != null && this.modelValue.toString().length > 0;\n }\n }\n};\n\nvar _hoisted_1 = [\"value\", \"aria-invalid\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"input\", mergeProps({\n type: \"text\",\n \"class\": _ctx.cx('root'),\n value: _ctx.modelValue,\n \"aria-invalid\": _ctx.invalid || undefined,\n onInput: _cache[0] || (_cache[0] = function () {\n return $options.onInput && $options.onInput.apply($options, arguments);\n })\n }, $options.getPTOptions('root')), null, 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-virtualscroller {\\n position: relative;\\n overflow: auto;\\n contain: strict;\\n transform: translateZ(0);\\n will-change: scroll-position;\\n outline: 0 none;\\n}\\n\\n.p-virtualscroller-content {\\n position: absolute;\\n top: 0;\\n left: 0;\\n min-height: 100%;\\n min-width: 100%;\\n will-change: transform;\\n}\\n\\n.p-virtualscroller-spacer {\\n position: absolute;\\n top: 0;\\n left: 0;\\n height: 1px;\\n width: 1px;\\n transform-origin: 0 0;\\n pointer-events: none;\\n}\\n\\n.p-virtualscroller-loader {\\n position: sticky;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n background: \".concat(dt('virtualscroller.loader.mask.background'), \";\\n color: \").concat(dt('virtualscroller.loader.mask.color'), \";\\n}\\n\\n.p-virtualscroller-loader-mask {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n}\\n\\n.p-virtualscroller-loading-icon {\\n font-size: \").concat(dt('virtualscroller.loader.icon.size'), \";\\n width: \").concat(dt('virtualscroller.loader.icon.size'), \";\\n height: \").concat(dt('virtualscroller.loader.icon.size'), \";\\n}\\n\\n.p-virtualscroller-horizontal > .p-virtualscroller-content {\\n display: flex;\\n}\\n\\n.p-virtualscroller-inline .p-virtualscroller-content {\\n position: static;\\n}\\n\");\n};\nvar VirtualScrollerStyle = BaseStyle.extend({\n name: 'virtualscroller',\n theme: theme\n});\n\nexport { VirtualScrollerStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { isVisible, getWidth, getHeight, findSingle } from '@primeuix/utils/dom';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport VirtualScrollerStyle from 'primevue/virtualscroller/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, renderSlot, createElementVNode, Fragment, renderList, createCommentVNode, createVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseVirtualScroller',\n \"extends\": BaseComponent,\n props: {\n id: {\n type: String,\n \"default\": null\n },\n style: null,\n \"class\": null,\n items: {\n type: Array,\n \"default\": null\n },\n itemSize: {\n type: [Number, Array],\n \"default\": 0\n },\n scrollHeight: null,\n scrollWidth: null,\n orientation: {\n type: String,\n \"default\": 'vertical'\n },\n numToleratedItems: {\n type: Number,\n \"default\": null\n },\n delay: {\n type: Number,\n \"default\": 0\n },\n resizeDelay: {\n type: Number,\n \"default\": 10\n },\n lazy: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n loaderDisabled: {\n type: Boolean,\n \"default\": false\n },\n columns: {\n type: Array,\n \"default\": null\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n showSpacer: {\n type: Boolean,\n \"default\": true\n },\n showLoader: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n inline: {\n type: Boolean,\n \"default\": false\n },\n step: {\n type: Number,\n \"default\": 0\n },\n appendOnly: {\n type: Boolean,\n \"default\": false\n },\n autoSize: {\n type: Boolean,\n \"default\": false\n }\n },\n style: VirtualScrollerStyle,\n provide: function provide() {\n return {\n $pcVirtualScroller: this,\n $parentInstance: this\n };\n },\n beforeMount: function beforeMount() {\n var _this$$primevueConfig;\n VirtualScrollerStyle.loadCSS({\n nonce: (_this$$primevueConfig = this.$primevueConfig) === null || _this$$primevueConfig === void 0 || (_this$$primevueConfig = _this$$primevueConfig.csp) === null || _this$$primevueConfig === void 0 ? void 0 : _this$$primevueConfig.nonce\n });\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script = {\n name: 'VirtualScroller',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:numToleratedItems', 'scroll', 'scroll-index-change', 'lazy-load'],\n data: function data() {\n var both = this.isBoth();\n return {\n first: both ? {\n rows: 0,\n cols: 0\n } : 0,\n last: both ? {\n rows: 0,\n cols: 0\n } : 0,\n page: both ? {\n rows: 0,\n cols: 0\n } : 0,\n numItemsInViewport: both ? {\n rows: 0,\n cols: 0\n } : 0,\n lastScrollPos: both ? {\n top: 0,\n left: 0\n } : 0,\n d_numToleratedItems: this.numToleratedItems,\n d_loading: this.loading,\n loaderArr: [],\n spacerStyle: {},\n contentStyle: {}\n };\n },\n element: null,\n content: null,\n lastScrollPos: null,\n scrollTimeout: null,\n resizeTimeout: null,\n defaultWidth: 0,\n defaultHeight: 0,\n defaultContentWidth: 0,\n defaultContentHeight: 0,\n isRangeChanged: false,\n lazyLoadState: {},\n resizeListener: null,\n initialized: false,\n watch: {\n numToleratedItems: function numToleratedItems(newValue) {\n this.d_numToleratedItems = newValue;\n },\n loading: function loading(newValue, oldValue) {\n if (this.lazy && newValue !== oldValue && newValue !== this.d_loading) {\n this.d_loading = newValue;\n }\n },\n items: function items(newValue, oldValue) {\n if (!oldValue || oldValue.length !== (newValue || []).length) {\n this.init();\n this.calculateAutoSize();\n }\n },\n itemSize: function itemSize() {\n this.init();\n this.calculateAutoSize();\n },\n orientation: function orientation() {\n this.lastScrollPos = this.isBoth() ? {\n top: 0,\n left: 0\n } : 0;\n },\n scrollHeight: function scrollHeight() {\n this.init();\n this.calculateAutoSize();\n },\n scrollWidth: function scrollWidth() {\n this.init();\n this.calculateAutoSize();\n }\n },\n mounted: function mounted() {\n this.viewInit();\n this.lastScrollPos = this.isBoth() ? {\n top: 0,\n left: 0\n } : 0;\n this.lazyLoadState = this.lazyLoadState || {};\n },\n updated: function updated() {\n !this.initialized && this.viewInit();\n },\n unmounted: function unmounted() {\n this.unbindResizeListener();\n this.initialized = false;\n },\n methods: {\n viewInit: function viewInit() {\n if (isVisible(this.element)) {\n this.setContentEl(this.content);\n this.init();\n this.calculateAutoSize();\n this.bindResizeListener();\n this.defaultWidth = getWidth(this.element);\n this.defaultHeight = getHeight(this.element);\n this.defaultContentWidth = getWidth(this.content);\n this.defaultContentHeight = getHeight(this.content);\n this.initialized = true;\n }\n },\n init: function init() {\n if (!this.disabled) {\n this.setSize();\n this.calculateOptions();\n this.setSpacerSize();\n }\n },\n isVertical: function isVertical() {\n return this.orientation === 'vertical';\n },\n isHorizontal: function isHorizontal() {\n return this.orientation === 'horizontal';\n },\n isBoth: function isBoth() {\n return this.orientation === 'both';\n },\n scrollTo: function scrollTo(options) {\n //this.lastScrollPos = this.both ? { top: 0, left: 0 } : 0;\n this.element && this.element.scrollTo(options);\n },\n scrollToIndex: function scrollToIndex(index) {\n var _this = this;\n var behavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto';\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var valid = both ? index.every(function (i) {\n return i > -1;\n }) : index > -1;\n if (valid) {\n var first = this.first;\n var _this$element = this.element,\n _this$element$scrollT = _this$element.scrollTop,\n scrollTop = _this$element$scrollT === void 0 ? 0 : _this$element$scrollT,\n _this$element$scrollL = _this$element.scrollLeft,\n scrollLeft = _this$element$scrollL === void 0 ? 0 : _this$element$scrollL;\n var _this$calculateNumIte = this.calculateNumItems(),\n numToleratedItems = _this$calculateNumIte.numToleratedItems;\n var contentPos = this.getContentPosition();\n var itemSize = this.itemSize;\n var calculateFirst = function calculateFirst() {\n var _index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var _numT = arguments.length > 1 ? arguments[1] : undefined;\n return _index <= _numT ? 0 : _index;\n };\n var calculateCoord = function calculateCoord(_first, _size, _cpos) {\n return _first * _size + _cpos;\n };\n var scrollTo = function scrollTo() {\n var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return _this.scrollTo({\n left: left,\n top: top,\n behavior: behavior\n });\n };\n var newFirst = both ? {\n rows: 0,\n cols: 0\n } : 0;\n var isRangeChanged = false,\n isScrollChanged = false;\n if (both) {\n newFirst = {\n rows: calculateFirst(index[0], numToleratedItems[0]),\n cols: calculateFirst(index[1], numToleratedItems[1])\n };\n scrollTo(calculateCoord(newFirst.cols, itemSize[1], contentPos.left), calculateCoord(newFirst.rows, itemSize[0], contentPos.top));\n isScrollChanged = this.lastScrollPos.top !== scrollTop || this.lastScrollPos.left !== scrollLeft;\n isRangeChanged = newFirst.rows !== first.rows || newFirst.cols !== first.cols;\n } else {\n newFirst = calculateFirst(index, numToleratedItems);\n horizontal ? scrollTo(calculateCoord(newFirst, itemSize, contentPos.left), scrollTop) : scrollTo(scrollLeft, calculateCoord(newFirst, itemSize, contentPos.top));\n isScrollChanged = this.lastScrollPos !== (horizontal ? scrollLeft : scrollTop);\n isRangeChanged = newFirst !== first;\n }\n this.isRangeChanged = isRangeChanged;\n isScrollChanged && (this.first = newFirst);\n }\n },\n scrollInView: function scrollInView(index, to) {\n var _this2 = this;\n var behavior = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'auto';\n if (to) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var valid = both ? index.every(function (i) {\n return i > -1;\n }) : index > -1;\n if (valid) {\n var _this$getRenderedRang = this.getRenderedRange(),\n first = _this$getRenderedRang.first,\n viewport = _this$getRenderedRang.viewport;\n var scrollTo = function scrollTo() {\n var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return _this2.scrollTo({\n left: left,\n top: top,\n behavior: behavior\n });\n };\n var isToStart = to === 'to-start';\n var isToEnd = to === 'to-end';\n if (isToStart) {\n if (both) {\n if (viewport.first.rows - first.rows > index[0]) {\n scrollTo(viewport.first.cols * this.itemSize[1], (viewport.first.rows - 1) * this.itemSize[0]);\n } else if (viewport.first.cols - first.cols > index[1]) {\n scrollTo((viewport.first.cols - 1) * this.itemSize[1], viewport.first.rows * this.itemSize[0]);\n }\n } else {\n if (viewport.first - first > index) {\n var pos = (viewport.first - 1) * this.itemSize;\n horizontal ? scrollTo(pos, 0) : scrollTo(0, pos);\n }\n }\n } else if (isToEnd) {\n if (both) {\n if (viewport.last.rows - first.rows <= index[0] + 1) {\n scrollTo(viewport.first.cols * this.itemSize[1], (viewport.first.rows + 1) * this.itemSize[0]);\n } else if (viewport.last.cols - first.cols <= index[1] + 1) {\n scrollTo((viewport.first.cols + 1) * this.itemSize[1], viewport.first.rows * this.itemSize[0]);\n }\n } else {\n if (viewport.last - first <= index + 1) {\n var _pos2 = (viewport.first + 1) * this.itemSize;\n horizontal ? scrollTo(_pos2, 0) : scrollTo(0, _pos2);\n }\n }\n }\n }\n } else {\n this.scrollToIndex(index, behavior);\n }\n },\n getRenderedRange: function getRenderedRange() {\n var calculateFirstInViewport = function calculateFirstInViewport(_pos, _size) {\n return Math.floor(_pos / (_size || _pos));\n };\n var firstInViewport = this.first;\n var lastInViewport = 0;\n if (this.element) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var _this$element2 = this.element,\n scrollTop = _this$element2.scrollTop,\n scrollLeft = _this$element2.scrollLeft;\n if (both) {\n firstInViewport = {\n rows: calculateFirstInViewport(scrollTop, this.itemSize[0]),\n cols: calculateFirstInViewport(scrollLeft, this.itemSize[1])\n };\n lastInViewport = {\n rows: firstInViewport.rows + this.numItemsInViewport.rows,\n cols: firstInViewport.cols + this.numItemsInViewport.cols\n };\n } else {\n var scrollPos = horizontal ? scrollLeft : scrollTop;\n firstInViewport = calculateFirstInViewport(scrollPos, this.itemSize);\n lastInViewport = firstInViewport + this.numItemsInViewport;\n }\n }\n return {\n first: this.first,\n last: this.last,\n viewport: {\n first: firstInViewport,\n last: lastInViewport\n }\n };\n },\n calculateNumItems: function calculateNumItems() {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var itemSize = this.itemSize;\n var contentPos = this.getContentPosition();\n var contentWidth = this.element ? this.element.offsetWidth - contentPos.left : 0;\n var contentHeight = this.element ? this.element.offsetHeight - contentPos.top : 0;\n var calculateNumItemsInViewport = function calculateNumItemsInViewport(_contentSize, _itemSize) {\n return Math.ceil(_contentSize / (_itemSize || _contentSize));\n };\n var calculateNumToleratedItems = function calculateNumToleratedItems(_numItems) {\n return Math.ceil(_numItems / 2);\n };\n var numItemsInViewport = both ? {\n rows: calculateNumItemsInViewport(contentHeight, itemSize[0]),\n cols: calculateNumItemsInViewport(contentWidth, itemSize[1])\n } : calculateNumItemsInViewport(horizontal ? contentWidth : contentHeight, itemSize);\n var numToleratedItems = this.d_numToleratedItems || (both ? [calculateNumToleratedItems(numItemsInViewport.rows), calculateNumToleratedItems(numItemsInViewport.cols)] : calculateNumToleratedItems(numItemsInViewport));\n return {\n numItemsInViewport: numItemsInViewport,\n numToleratedItems: numToleratedItems\n };\n },\n calculateOptions: function calculateOptions() {\n var _this3 = this;\n var both = this.isBoth();\n var first = this.first;\n var _this$calculateNumIte2 = this.calculateNumItems(),\n numItemsInViewport = _this$calculateNumIte2.numItemsInViewport,\n numToleratedItems = _this$calculateNumIte2.numToleratedItems;\n var calculateLast = function calculateLast(_first, _num, _numT) {\n var _isCols = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n return _this3.getLast(_first + _num + (_first < _numT ? 2 : 3) * _numT, _isCols);\n };\n var last = both ? {\n rows: calculateLast(first.rows, numItemsInViewport.rows, numToleratedItems[0]),\n cols: calculateLast(first.cols, numItemsInViewport.cols, numToleratedItems[1], true)\n } : calculateLast(first, numItemsInViewport, numToleratedItems);\n this.last = last;\n this.numItemsInViewport = numItemsInViewport;\n this.d_numToleratedItems = numToleratedItems;\n this.$emit('update:numToleratedItems', this.d_numToleratedItems);\n if (this.showLoader) {\n this.loaderArr = both ? Array.from({\n length: numItemsInViewport.rows\n }).map(function () {\n return Array.from({\n length: numItemsInViewport.cols\n });\n }) : Array.from({\n length: numItemsInViewport\n });\n }\n if (this.lazy) {\n Promise.resolve().then(function () {\n var _this3$items;\n _this3.lazyLoadState = {\n first: _this3.step ? both ? {\n rows: 0,\n cols: first.cols\n } : 0 : first,\n last: Math.min(_this3.step ? _this3.step : last, ((_this3$items = _this3.items) === null || _this3$items === void 0 ? void 0 : _this3$items.length) || 0)\n };\n _this3.$emit('lazy-load', _this3.lazyLoadState);\n });\n }\n },\n calculateAutoSize: function calculateAutoSize() {\n var _this4 = this;\n if (this.autoSize && !this.d_loading) {\n Promise.resolve().then(function () {\n if (_this4.content) {\n var both = _this4.isBoth();\n var horizontal = _this4.isHorizontal();\n var vertical = _this4.isVertical();\n _this4.content.style.minHeight = _this4.content.style.minWidth = 'auto';\n _this4.content.style.position = 'relative';\n _this4.element.style.contain = 'none';\n\n /*const [contentWidth, contentHeight] = [getWidth(this.content), getHeight(this.content)];\n contentWidth !== this.defaultContentWidth && (this.element.style.width = '');\n contentHeight !== this.defaultContentHeight && (this.element.style.height = '');*/\n\n var _ref = [getWidth(_this4.element), getHeight(_this4.element)],\n width = _ref[0],\n height = _ref[1];\n (both || horizontal) && (_this4.element.style.width = width < _this4.defaultWidth ? width + 'px' : _this4.scrollWidth || _this4.defaultWidth + 'px');\n (both || vertical) && (_this4.element.style.height = height < _this4.defaultHeight ? height + 'px' : _this4.scrollHeight || _this4.defaultHeight + 'px');\n _this4.content.style.minHeight = _this4.content.style.minWidth = '';\n _this4.content.style.position = '';\n _this4.element.style.contain = '';\n }\n });\n }\n },\n getLast: function getLast() {\n var _ref2, _this$items;\n var last = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var isCols = arguments.length > 1 ? arguments[1] : undefined;\n return this.items ? Math.min(isCols ? ((_ref2 = this.columns || this.items[0]) === null || _ref2 === void 0 ? void 0 : _ref2.length) || 0 : ((_this$items = this.items) === null || _this$items === void 0 ? void 0 : _this$items.length) || 0, last) : 0;\n },\n getContentPosition: function getContentPosition() {\n if (this.content) {\n var style = getComputedStyle(this.content);\n var left = parseFloat(style.paddingLeft) + Math.max(parseFloat(style.left) || 0, 0);\n var right = parseFloat(style.paddingRight) + Math.max(parseFloat(style.right) || 0, 0);\n var top = parseFloat(style.paddingTop) + Math.max(parseFloat(style.top) || 0, 0);\n var bottom = parseFloat(style.paddingBottom) + Math.max(parseFloat(style.bottom) || 0, 0);\n return {\n left: left,\n right: right,\n top: top,\n bottom: bottom,\n x: left + right,\n y: top + bottom\n };\n }\n return {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0,\n x: 0,\n y: 0\n };\n },\n setSize: function setSize() {\n var _this5 = this;\n if (this.element) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var parentElement = this.element.parentElement;\n var width = this.scrollWidth || \"\".concat(this.element.offsetWidth || parentElement.offsetWidth, \"px\");\n var height = this.scrollHeight || \"\".concat(this.element.offsetHeight || parentElement.offsetHeight, \"px\");\n var setProp = function setProp(_name, _value) {\n return _this5.element.style[_name] = _value;\n };\n if (both || horizontal) {\n setProp('height', height);\n setProp('width', width);\n } else {\n setProp('height', height);\n }\n }\n },\n setSpacerSize: function setSpacerSize() {\n var _this6 = this;\n var items = this.items;\n if (items) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var contentPos = this.getContentPosition();\n var setProp = function setProp(_name, _value, _size) {\n var _cpos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n return _this6.spacerStyle = _objectSpread(_objectSpread({}, _this6.spacerStyle), _defineProperty({}, \"\".concat(_name), (_value || []).length * _size + _cpos + 'px'));\n };\n if (both) {\n setProp('height', items, this.itemSize[0], contentPos.y);\n setProp('width', this.columns || items[1], this.itemSize[1], contentPos.x);\n } else {\n horizontal ? setProp('width', this.columns || items, this.itemSize, contentPos.x) : setProp('height', items, this.itemSize, contentPos.y);\n }\n }\n },\n setContentPosition: function setContentPosition(pos) {\n var _this7 = this;\n if (this.content && !this.appendOnly) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var first = pos ? pos.first : this.first;\n var calculateTranslateVal = function calculateTranslateVal(_first, _size) {\n return _first * _size;\n };\n var setTransform = function setTransform() {\n var _x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var _y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return _this7.contentStyle = _objectSpread(_objectSpread({}, _this7.contentStyle), {\n transform: \"translate3d(\".concat(_x, \"px, \").concat(_y, \"px, 0)\")\n });\n };\n if (both) {\n setTransform(calculateTranslateVal(first.cols, this.itemSize[1]), calculateTranslateVal(first.rows, this.itemSize[0]));\n } else {\n var translateVal = calculateTranslateVal(first, this.itemSize);\n horizontal ? setTransform(translateVal, 0) : setTransform(0, translateVal);\n }\n }\n },\n onScrollPositionChange: function onScrollPositionChange(event) {\n var _this8 = this;\n var target = event.target;\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n var contentPos = this.getContentPosition();\n var calculateScrollPos = function calculateScrollPos(_pos, _cpos) {\n return _pos ? _pos > _cpos ? _pos - _cpos : _pos : 0;\n };\n var calculateCurrentIndex = function calculateCurrentIndex(_pos, _size) {\n return Math.floor(_pos / (_size || _pos));\n };\n var calculateTriggerIndex = function calculateTriggerIndex(_currentIndex, _first, _last, _num, _numT, _isScrollDownOrRight) {\n return _currentIndex <= _numT ? _numT : _isScrollDownOrRight ? _last - _num - _numT : _first + _numT - 1;\n };\n var calculateFirst = function calculateFirst(_currentIndex, _triggerIndex, _first, _last, _num, _numT, _isScrollDownOrRight) {\n if (_currentIndex <= _numT) return 0;else return Math.max(0, _isScrollDownOrRight ? _currentIndex < _triggerIndex ? _first : _currentIndex - _numT : _currentIndex > _triggerIndex ? _first : _currentIndex - 2 * _numT);\n };\n var calculateLast = function calculateLast(_currentIndex, _first, _last, _num, _numT, _isCols) {\n var lastValue = _first + _num + 2 * _numT;\n if (_currentIndex >= _numT) {\n lastValue += _numT + 1;\n }\n return _this8.getLast(lastValue, _isCols);\n };\n var scrollTop = calculateScrollPos(target.scrollTop, contentPos.top);\n var scrollLeft = calculateScrollPos(target.scrollLeft, contentPos.left);\n var newFirst = both ? {\n rows: 0,\n cols: 0\n } : 0;\n var newLast = this.last;\n var isRangeChanged = false;\n var newScrollPos = this.lastScrollPos;\n if (both) {\n var isScrollDown = this.lastScrollPos.top <= scrollTop;\n var isScrollRight = this.lastScrollPos.left <= scrollLeft;\n if (!this.appendOnly || this.appendOnly && (isScrollDown || isScrollRight)) {\n var currentIndex = {\n rows: calculateCurrentIndex(scrollTop, this.itemSize[0]),\n cols: calculateCurrentIndex(scrollLeft, this.itemSize[1])\n };\n var triggerIndex = {\n rows: calculateTriggerIndex(currentIndex.rows, this.first.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0], isScrollDown),\n cols: calculateTriggerIndex(currentIndex.cols, this.first.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], isScrollRight)\n };\n newFirst = {\n rows: calculateFirst(currentIndex.rows, triggerIndex.rows, this.first.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0], isScrollDown),\n cols: calculateFirst(currentIndex.cols, triggerIndex.cols, this.first.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], isScrollRight)\n };\n newLast = {\n rows: calculateLast(currentIndex.rows, newFirst.rows, this.last.rows, this.numItemsInViewport.rows, this.d_numToleratedItems[0]),\n cols: calculateLast(currentIndex.cols, newFirst.cols, this.last.cols, this.numItemsInViewport.cols, this.d_numToleratedItems[1], true)\n };\n isRangeChanged = newFirst.rows !== this.first.rows || newLast.rows !== this.last.rows || newFirst.cols !== this.first.cols || newLast.cols !== this.last.cols || this.isRangeChanged;\n newScrollPos = {\n top: scrollTop,\n left: scrollLeft\n };\n }\n } else {\n var scrollPos = horizontal ? scrollLeft : scrollTop;\n var isScrollDownOrRight = this.lastScrollPos <= scrollPos;\n if (!this.appendOnly || this.appendOnly && isScrollDownOrRight) {\n var _currentIndex2 = calculateCurrentIndex(scrollPos, this.itemSize);\n var _triggerIndex2 = calculateTriggerIndex(_currentIndex2, this.first, this.last, this.numItemsInViewport, this.d_numToleratedItems, isScrollDownOrRight);\n newFirst = calculateFirst(_currentIndex2, _triggerIndex2, this.first, this.last, this.numItemsInViewport, this.d_numToleratedItems, isScrollDownOrRight);\n newLast = calculateLast(_currentIndex2, newFirst, this.last, this.numItemsInViewport, this.d_numToleratedItems);\n isRangeChanged = newFirst !== this.first || newLast !== this.last || this.isRangeChanged;\n newScrollPos = scrollPos;\n }\n }\n return {\n first: newFirst,\n last: newLast,\n isRangeChanged: isRangeChanged,\n scrollPos: newScrollPos\n };\n },\n onScrollChange: function onScrollChange(event) {\n var _this$onScrollPositio = this.onScrollPositionChange(event),\n first = _this$onScrollPositio.first,\n last = _this$onScrollPositio.last,\n isRangeChanged = _this$onScrollPositio.isRangeChanged,\n scrollPos = _this$onScrollPositio.scrollPos;\n if (isRangeChanged) {\n var newState = {\n first: first,\n last: last\n };\n this.setContentPosition(newState);\n this.first = first;\n this.last = last;\n this.lastScrollPos = scrollPos;\n this.$emit('scroll-index-change', newState);\n if (this.lazy && this.isPageChanged(first)) {\n var _this$items2, _this$items3;\n var lazyLoadState = {\n first: this.step ? Math.min(this.getPageByFirst(first) * this.step, (((_this$items2 = this.items) === null || _this$items2 === void 0 ? void 0 : _this$items2.length) || 0) - this.step) : first,\n last: Math.min(this.step ? (this.getPageByFirst(first) + 1) * this.step : last, ((_this$items3 = this.items) === null || _this$items3 === void 0 ? void 0 : _this$items3.length) || 0)\n };\n var isLazyStateChanged = this.lazyLoadState.first !== lazyLoadState.first || this.lazyLoadState.last !== lazyLoadState.last;\n isLazyStateChanged && this.$emit('lazy-load', lazyLoadState);\n this.lazyLoadState = lazyLoadState;\n }\n }\n },\n onScroll: function onScroll(event) {\n var _this9 = this;\n this.$emit('scroll', event);\n if (this.delay) {\n if (this.scrollTimeout) {\n clearTimeout(this.scrollTimeout);\n }\n if (this.isPageChanged()) {\n if (!this.d_loading && this.showLoader) {\n var _this$onScrollPositio2 = this.onScrollPositionChange(event),\n isRangeChanged = _this$onScrollPositio2.isRangeChanged;\n var changed = isRangeChanged || (this.step ? this.isPageChanged() : false);\n changed && (this.d_loading = true);\n }\n this.scrollTimeout = setTimeout(function () {\n _this9.onScrollChange(event);\n if (_this9.d_loading && _this9.showLoader && (!_this9.lazy || _this9.loading === undefined)) {\n _this9.d_loading = false;\n _this9.page = _this9.getPageByFirst();\n }\n }, this.delay);\n }\n } else {\n this.onScrollChange(event);\n }\n },\n onResize: function onResize() {\n var _this10 = this;\n if (this.resizeTimeout) {\n clearTimeout(this.resizeTimeout);\n }\n this.resizeTimeout = setTimeout(function () {\n if (isVisible(_this10.element)) {\n var both = _this10.isBoth();\n var vertical = _this10.isVertical();\n var horizontal = _this10.isHorizontal();\n var _ref3 = [getWidth(_this10.element), getHeight(_this10.element)],\n width = _ref3[0],\n height = _ref3[1];\n var isDiffWidth = width !== _this10.defaultWidth,\n isDiffHeight = height !== _this10.defaultHeight;\n var reinit = both ? isDiffWidth || isDiffHeight : horizontal ? isDiffWidth : vertical ? isDiffHeight : false;\n if (reinit) {\n _this10.d_numToleratedItems = _this10.numToleratedItems;\n _this10.defaultWidth = width;\n _this10.defaultHeight = height;\n _this10.defaultContentWidth = getWidth(_this10.content);\n _this10.defaultContentHeight = getHeight(_this10.content);\n _this10.init();\n }\n }\n }, this.resizeDelay);\n },\n bindResizeListener: function bindResizeListener() {\n if (!this.resizeListener) {\n this.resizeListener = this.onResize.bind(this);\n window.addEventListener('resize', this.resizeListener);\n window.addEventListener('orientationchange', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n window.removeEventListener('orientationchange', this.resizeListener);\n this.resizeListener = null;\n }\n },\n getOptions: function getOptions(renderedIndex) {\n var count = (this.items || []).length;\n var index = this.isBoth() ? this.first.rows + renderedIndex : this.first + renderedIndex;\n return {\n index: index,\n count: count,\n first: index === 0,\n last: index === count - 1,\n even: index % 2 === 0,\n odd: index % 2 !== 0\n };\n },\n getLoaderOptions: function getLoaderOptions(index, extOptions) {\n var count = this.loaderArr.length;\n return _objectSpread({\n index: index,\n count: count,\n first: index === 0,\n last: index === count - 1,\n even: index % 2 === 0,\n odd: index % 2 !== 0\n }, extOptions);\n },\n getPageByFirst: function getPageByFirst(first) {\n return Math.floor(((first !== null && first !== void 0 ? first : this.first) + this.d_numToleratedItems * 4) / (this.step || 1));\n },\n isPageChanged: function isPageChanged(first) {\n return this.step ? this.page !== this.getPageByFirst(first !== null && first !== void 0 ? first : this.first) : true;\n },\n setContentEl: function setContentEl(el) {\n this.content = el || this.content || findSingle(this.element, '[data-pc-section=\"content\"]');\n },\n elementRef: function elementRef(el) {\n this.element = el;\n },\n contentRef: function contentRef(el) {\n this.content = el;\n }\n },\n computed: {\n containerClass: function containerClass() {\n return ['p-virtualscroller', this[\"class\"], {\n 'p-virtualscroller-inline': this.inline,\n 'p-virtualscroller-both p-both-scroll': this.isBoth(),\n 'p-virtualscroller-horizontal p-horizontal-scroll': this.isHorizontal()\n }];\n },\n contentClass: function contentClass() {\n return ['p-virtualscroller-content', {\n 'p-virtualscroller-loading': this.d_loading\n }];\n },\n loaderClass: function loaderClass() {\n return ['p-virtualscroller-loader', {\n 'p-virtualscroller-loader-mask': !this.$slots.loader\n }];\n },\n loadedItems: function loadedItems() {\n var _this11 = this;\n if (this.items && !this.d_loading) {\n if (this.isBoth()) return this.items.slice(this.appendOnly ? 0 : this.first.rows, this.last.rows).map(function (item) {\n return _this11.columns ? item : item.slice(_this11.appendOnly ? 0 : _this11.first.cols, _this11.last.cols);\n });else if (this.isHorizontal() && this.columns) return this.items;else return this.items.slice(this.appendOnly ? 0 : this.first, this.last);\n }\n return [];\n },\n loadedRows: function loadedRows() {\n return this.d_loading ? this.loaderDisabled ? this.loaderArr : [] : this.loadedItems;\n },\n loadedColumns: function loadedColumns() {\n if (this.columns) {\n var both = this.isBoth();\n var horizontal = this.isHorizontal();\n if (both || horizontal) {\n return this.d_loading && this.loaderDisabled ? both ? this.loaderArr[0] : this.loaderArr : this.columns.slice(both ? this.first.cols : this.first, both ? this.last.cols : this.last);\n }\n }\n return this.columns;\n }\n },\n components: {\n SpinnerIcon: SpinnerIcon\n }\n};\n\nvar _hoisted_1 = [\"tabindex\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n return !_ctx.disabled ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.elementRef,\n \"class\": $options.containerClass,\n tabindex: _ctx.tabindex,\n style: _ctx.style,\n onScroll: _cache[0] || (_cache[0] = function () {\n return $options.onScroll && $options.onScroll.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"content\", {\n styleClass: $options.contentClass,\n items: $options.loadedItems,\n getItemOptions: $options.getOptions,\n loading: $data.d_loading,\n getLoaderOptions: $options.getLoaderOptions,\n itemSize: _ctx.itemSize,\n rows: $options.loadedRows,\n columns: $options.loadedColumns,\n contentRef: $options.contentRef,\n spacerStyle: $data.spacerStyle,\n contentStyle: $data.contentStyle,\n vertical: $options.isVertical(),\n horizontal: $options.isHorizontal(),\n both: $options.isBoth()\n }, function () {\n return [createElementVNode(\"div\", mergeProps({\n ref: $options.contentRef,\n \"class\": $options.contentClass,\n style: $data.contentStyle\n }, _ctx.ptm('content')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.loadedItems, function (item, index) {\n return renderSlot(_ctx.$slots, \"item\", {\n key: index,\n item: item,\n options: $options.getOptions(index)\n });\n }), 128))], 16)];\n }), _ctx.showSpacer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": \"p-virtualscroller-spacer\",\n style: $data.spacerStyle\n }, _ctx.ptm('spacer')), null, 16)) : createCommentVNode(\"\", true), !_ctx.loaderDisabled && _ctx.showLoader && $data.d_loading ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": $options.loaderClass\n }, _ctx.ptm('loader')), [_ctx.$slots && _ctx.$slots.loader ? (openBlock(true), createElementBlock(Fragment, {\n key: 0\n }, renderList($data.loaderArr, function (_, index) {\n return renderSlot(_ctx.$slots, \"loader\", {\n key: index,\n options: $options.getLoaderOptions(index, $options.isBoth() && {\n numCols: _ctx.d_numItemsInViewport.cols\n })\n });\n }), 128)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"loadingicon\", {}, function () {\n return [createVNode(_component_SpinnerIcon, mergeProps({\n spin: \"\",\n \"class\": \"p-virtualscroller-loading-icon\"\n }, _ctx.ptm('loadingIcon')), null, 16)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_1)) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [renderSlot(_ctx.$slots, \"default\"), renderSlot(_ctx.$slots, \"content\", {\n items: _ctx.items,\n rows: _ctx.items,\n columns: $options.loadedColumns\n })], 64));\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-listbox {\\n background: \".concat(dt('listbox.background'), \";\\n color: \").concat(dt('listbox.color'), \";\\n border: 1px solid \").concat(dt('listbox.border.color'), \";\\n border-radius: \").concat(dt('listbox.border.radius'), \";\\n transition: background \").concat(dt('listbox.transition.duration'), \", color \").concat(dt('listbox.transition.duration'), \", border-color \").concat(dt('listbox.transition.duration'), \",\\n box-shadow \").concat(dt('listbox.transition.duration'), \", outline-color \").concat(dt('listbox.transition.duration'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('listbox.shadow'), \";\\n}\\n\\n.p-listbox.p-focus {\\n border-color: \").concat(dt('listbox.focus.border.color'), \";\\n box-shadow: \").concat(dt('listbox.focus.ring.shadow'), \";\\n outline: \").concat(dt('listbox.focus.ring.width'), \" \").concat(dt('listbox.focus.ring.style'), \" \").concat(dt('listbox.focus.ring.color'), \";\\n outline-offset: \").concat(dt('listbox.focus.ring.offset'), \";\\n}\\n\\n.p-listbox.p-disabled {\\n opacity: 1;\\n background: \").concat(dt('listbox.disabled.background'), \";\\n color: \").concat(dt('listbox.disabled.color'), \";\\n}\\n\\n.p-listbox.p-disabled .p-listbox-option {\\n color: \").concat(dt('listbox.disabled.color'), \";\\n}\\n\\n.p-listbox.p-invalid {\\n border-color: \").concat(dt('listbox.invalid.border.color'), \";\\n}\\n\\n.p-listbox-header {\\n padding: \").concat(dt('listbox.list.header.padding'), \";\\n}\\n\\n.p-listbox-filter {\\n width: 100%;\\n}\\n\\n.p-listbox-list-container {\\n overflow: auto;\\n}\\n\\n.p-listbox-list {\\n list-style-type: none;\\n margin: 0;\\n padding: \").concat(dt('listbox.list.padding'), \";\\n outline: 0 none;\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('listbox.list.gap'), \";\\n}\\n\\n.p-listbox-option {\\n display: flex;\\n align-items: center;\\n cursor: pointer;\\n position: relative;\\n overflow: hidden;\\n padding: \").concat(dt('listbox.option.padding'), \";\\n border: 0 none;\\n border-radius: \").concat(dt('listbox.option.border.radius'), \";\\n color: \").concat(dt('listbox.option.color'), \";\\n transition: background \").concat(dt('listbox.transition.duration'), \", color \").concat(dt('listbox.transition.duration'), \", border-color \").concat(dt('listbox.transition.duration'), \",\\n box-shadow \").concat(dt('listbox.transition.duration'), \", outline-color \").concat(dt('listbox.transition.duration'), \";\\n}\\n\\n.p-listbox-striped li:nth-child(even of .p-listbox-option) {\\n background: \").concat(dt('listbox.option.striped.background'), \";\\n}\\n\\n.p-listbox .p-listbox-list .p-listbox-option.p-listbox-option-selected {\\n background: \").concat(dt('listbox.option.selected.background'), \";\\n color: \").concat(dt('listbox.option.selected.color'), \";\\n}\\n\\n.p-listbox:not(.p-disabled) .p-listbox-option.p-listbox-option-selected.p-focus {\\n background: \").concat(dt('listbox.option.selected.focus.background'), \";\\n color: \").concat(dt('listbox.option.selected.focus.color'), \";\\n}\\n\\n.p-listbox:not(.p-disabled) .p-listbox-option:not(.p-listbox-option-selected):not(.p-disabled).p-focus {\\n background: \").concat(dt('listbox.option.focus.background'), \";\\n color: \").concat(dt('listbox.option.focus.color'), \";\\n}\\n\\n.p-listbox:not(.p-disabled) .p-listbox-option:not(.p-listbox-option-selected):not(.p-disabled):hover {\\n background: \").concat(dt('listbox.option.focus.background'), \";\\n color: \").concat(dt('listbox.option.focus.color'), \";\\n}\\n\\n.p-listbox-option-check-icon {\\n position: relative;\\n margin-inline-start: \").concat(dt('listbox.checkmark.gutter.start'), \";\\n margin-inline-end: \").concat(dt('listbox.checkmark.gutter.end'), \";\\n color: \").concat(dt('listbox.checkmark.color'), \";\\n}\\n\\n.p-listbox-option-group {\\n margin: 0;\\n padding: \").concat(dt('listbox.option.group.padding'), \";\\n color: \").concat(dt('listbox.option.group.color'), \";\\n background: \").concat(dt('listbox.option.group.background'), \";\\n font-weight: \").concat(dt('listbox.option.group.font.weight'), \";\\n}\\n\\n.p-listbox-empty-message {\\n padding: \").concat(dt('listbox.empty.message.padding'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-listbox p-component', {\n 'p-listbox-striped': props.striped,\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid\n }];\n },\n header: 'p-listbox-header',\n pcFilter: 'p-listbox-filter',\n listContainer: 'p-listbox-list-container',\n list: 'p-listbox-list',\n optionGroup: 'p-listbox-option-group',\n option: function option(_ref3) {\n var instance = _ref3.instance,\n props = _ref3.props,\n _option = _ref3.option,\n index = _ref3.index,\n getItemOptions = _ref3.getItemOptions;\n return ['p-listbox-option', {\n 'p-listbox-option-selected': instance.isSelected(_option) && props.highlightOnSelect,\n 'p-focus': instance.focusedOptionIndex === instance.getOptionIndex(index, getItemOptions),\n 'p-disabled': instance.isOptionDisabled(_option)\n }];\n },\n optionCheckIcon: 'p-listbox-option-check-icon',\n optionBlankIcon: 'p-listbox-option-blank-icon',\n emptyMessage: 'p-listbox-empty-message'\n};\nvar ListboxStyle = BaseStyle.extend({\n name: 'listbox',\n theme: theme,\n classes: classes\n});\n\nexport { ListboxStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { FilterService } from '@primevue/core/api';\nimport { UniqueComponentId } from '@primevue/core/utils';\nimport { focus, getFirstFocusableElement, isElement, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isPrintableCharacter, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport BlankIcon from '@primevue/icons/blank';\nimport CheckIcon from '@primevue/icons/check';\nimport SearchIcon from '@primevue/icons/search';\nimport IconField from 'primevue/iconfield';\nimport InputIcon from 'primevue/inputicon';\nimport InputText from 'primevue/inputtext';\nimport Ripple from 'primevue/ripple';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ListboxStyle from 'primevue/listbox/style';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, createElementVNode, normalizeClass, renderSlot, createCommentVNode, createVNode, withCtx, createBlock, normalizeProps, toDisplayString, createSlots, Fragment, renderList, createTextVNode, withDirectives } from 'vue';\n\nvar script$1 = {\n name: 'BaseListbox',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n options: Array,\n optionLabel: null,\n optionValue: null,\n optionDisabled: null,\n optionGroupLabel: null,\n optionGroupChildren: null,\n listStyle: null,\n scrollHeight: {\n type: String,\n \"default\": '14rem'\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n dataKey: null,\n multiple: {\n type: Boolean,\n \"default\": false\n },\n metaKeySelection: {\n type: Boolean,\n \"default\": false\n },\n filter: Boolean,\n filterPlaceholder: String,\n filterLocale: String,\n filterMatchMode: {\n type: String,\n \"default\": 'contains'\n },\n filterFields: {\n type: Array,\n \"default\": null\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n autoOptionFocus: {\n type: Boolean,\n \"default\": true\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n focusOnHover: {\n type: Boolean,\n \"default\": true\n },\n highlightOnSelect: {\n type: Boolean,\n \"default\": true\n },\n checkmark: {\n type: Boolean,\n \"default\": false\n },\n filterMessage: {\n type: String,\n \"default\": null\n },\n selectionMessage: {\n type: String,\n \"default\": null\n },\n emptySelectionMessage: {\n type: String,\n \"default\": null\n },\n emptyFilterMessage: {\n type: String,\n \"default\": null\n },\n emptyMessage: {\n type: String,\n \"default\": null\n },\n filterIcon: {\n type: String,\n \"default\": undefined\n },\n striped: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n ariaLabel: {\n type: String,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: ListboxStyle,\n provide: function provide() {\n return {\n $pcListbox: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Listbox',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'filter', 'item-dblclick', 'option-dblclick'],\n list: null,\n virtualScroller: null,\n optionTouched: false,\n startRangeIndex: -1,\n searchTimeout: null,\n searchValue: '',\n data: function data() {\n return {\n id: this.$attrs.id,\n filterValue: null,\n focused: false,\n focusedOptionIndex: -1\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n options: function options() {\n this.autoUpdateModel();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n this.autoUpdateModel();\n },\n methods: {\n getOptionIndex: function getOptionIndex(index, fn) {\n return this.virtualScrollerDisabled ? index : fn && fn(index)['index'];\n },\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : typeof option === 'string' ? option : null;\n },\n getOptionValue: function getOptionValue(option) {\n return this.optionValue ? resolveFieldData(option, this.optionValue) : option;\n },\n getOptionRenderKey: function getOptionRenderKey(option, index) {\n return (this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option)) + '_' + index;\n },\n getPTOptions: function getPTOptions(option, itemOptions, index, key) {\n return this.ptm(key, {\n context: {\n selected: this.isSelected(option),\n focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),\n disabled: this.isOptionDisabled(option)\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n isOptionGroup: function isOptionGroup(option) {\n return this.optionGroupLabel && option.optionGroup && option.group;\n },\n getOptionGroupLabel: function getOptionGroupLabel(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupLabel);\n },\n getOptionGroupChildren: function getOptionGroupChildren(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupChildren);\n },\n getAriaPosInset: function getAriaPosInset(index) {\n var _this = this;\n return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function (option) {\n return _this.isOptionGroup(option);\n }).length : index) + 1;\n },\n onFirstHiddenFocus: function onFirstHiddenFocus() {\n focus(this.list);\n var firstFocusableEl = getFirstFocusableElement(this.$el, ':not([data-p-hidden-focusable=\"true\"])');\n this.$refs.lastHiddenFocusableElement.tabIndex = isElement(firstFocusableEl) ? undefined : -1;\n this.$refs.firstHiddenFocusableElement.tabIndex = -1;\n },\n onLastHiddenFocus: function onLastHiddenFocus(event) {\n var relatedTarget = event.relatedTarget;\n if (relatedTarget === this.list) {\n var firstFocusableEl = getFirstFocusableElement(this.$el, ':not([data-p-hidden-focusable=\"true\"])');\n focus(firstFocusableEl);\n this.$refs.firstHiddenFocusableElement.tabIndex = undefined;\n } else {\n focus(this.$refs.firstHiddenFocusableElement);\n }\n this.$refs.lastHiddenFocusableElement.tabIndex = -1;\n },\n onFocusout: function onFocusout(event) {\n if (!this.$el.contains(event.relatedTarget) && this.$refs.lastHiddenFocusableElement && this.$refs.firstHiddenFocusableElement) {\n this.$refs.lastHiddenFocusableElement.tabIndex = this.$refs.firstHiddenFocusableElement.tabIndex = undefined;\n }\n },\n onListFocus: function onListFocus(event) {\n this.focused = true;\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : this.findSelectedOptionIndex();\n this.autoUpdateModel();\n this.$emit('focus', event);\n },\n onListBlur: function onListBlur(event) {\n this.focused = false;\n this.focusedOptionIndex = this.startRangeIndex = -1;\n this.searchValue = '';\n this.$emit('blur', event);\n },\n onListKeyDown: function onListKeyDown(event) {\n var _this2 = this;\n var metaKey = event.metaKey || event.ctrlKey;\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event);\n break;\n case 'Home':\n this.onHomeKey(event);\n break;\n case 'End':\n this.onEndKey(event);\n break;\n case 'PageDown':\n this.onPageDownKey(event);\n break;\n case 'PageUp':\n this.onPageUpKey(event);\n break;\n case 'Enter':\n case 'NumpadEnter':\n case 'Space':\n this.onSpaceKey(event);\n break;\n case 'Tab':\n //NOOP\n break;\n case 'ShiftLeft':\n case 'ShiftRight':\n this.onShiftKey(event);\n break;\n default:\n if (this.multiple && event.code === 'KeyA' && metaKey) {\n var value = this.visibleOptions.filter(function (option) {\n return _this2.isValidOption(option);\n }).map(function (option) {\n return _this2.getOptionValue(option);\n });\n this.updateModel(event, value);\n event.preventDefault();\n break;\n }\n if (!metaKey && isPrintableCharacter(event.key)) {\n this.searchOptions(event, event.key);\n event.preventDefault();\n }\n break;\n }\n },\n onOptionSelect: function onOptionSelect(event, option) {\n var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;\n if (this.disabled || this.isOptionDisabled(option)) {\n return;\n }\n this.multiple ? this.onOptionSelectMultiple(event, option) : this.onOptionSelectSingle(event, option);\n this.optionTouched = false;\n index !== -1 && (this.focusedOptionIndex = index);\n },\n onOptionMouseDown: function onOptionMouseDown(event, index) {\n this.changeFocusedOptionIndex(event, index);\n },\n onOptionMouseMove: function onOptionMouseMove(event, index) {\n if (this.focusOnHover && this.focused) {\n this.changeFocusedOptionIndex(event, index);\n }\n },\n onOptionTouchEnd: function onOptionTouchEnd() {\n if (this.disabled) {\n return;\n }\n this.optionTouched = true;\n },\n onOptionDblClick: function onOptionDblClick(event, item) {\n this.$emit('item-dblclick', {\n originalEvent: event,\n value: item\n });\n this.$emit('option-dblclick', {\n originalEvent: event,\n value: item\n });\n },\n onOptionSelectSingle: function onOptionSelectSingle(event, option) {\n var selected = this.isSelected(option);\n var valueChanged = false;\n var value = null;\n var metaSelection = this.optionTouched ? false : this.metaKeySelection;\n if (metaSelection) {\n var metaKey = event && (event.metaKey || event.ctrlKey);\n if (selected) {\n if (metaKey) {\n value = null;\n valueChanged = true;\n }\n } else {\n value = this.getOptionValue(option);\n valueChanged = true;\n }\n } else {\n value = selected ? null : this.getOptionValue(option);\n valueChanged = true;\n }\n if (valueChanged) {\n this.updateModel(event, value);\n }\n },\n onOptionSelectMultiple: function onOptionSelectMultiple(event, option) {\n var selected = this.isSelected(option);\n var value = null;\n var metaSelection = this.optionTouched ? false : this.metaKeySelection;\n if (metaSelection) {\n var metaKey = event.metaKey || event.ctrlKey;\n if (selected) {\n value = metaKey ? this.removeOption(option) : [this.getOptionValue(option)];\n } else {\n value = metaKey ? this.modelValue || [] : [];\n value = [].concat(_toConsumableArray(value), [this.getOptionValue(option)]);\n }\n } else {\n value = selected ? this.removeOption(option) : [].concat(_toConsumableArray(this.modelValue || []), [this.getOptionValue(option)]);\n }\n this.updateModel(event, value);\n },\n onOptionSelectRange: function onOptionSelectRange(event) {\n var _this3 = this;\n var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;\n var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;\n start === -1 && (start = this.findNearestSelectedOptionIndex(end, true));\n end === -1 && (end = this.findNearestSelectedOptionIndex(start));\n if (start !== -1 && end !== -1) {\n var rangeStart = Math.min(start, end);\n var rangeEnd = Math.max(start, end);\n var value = this.visibleOptions.slice(rangeStart, rangeEnd + 1).filter(function (option) {\n return _this3.isValidOption(option);\n }).map(function (option) {\n return _this3.getOptionValue(option);\n });\n this.updateModel(event, value);\n }\n },\n onFilterChange: function onFilterChange(event) {\n this.$emit('filter', {\n originalEvent: event,\n value: event.target.value\n });\n this.focusedOptionIndex = this.startRangeIndex = -1;\n },\n onFilterBlur: function onFilterBlur() {\n this.focusedOptionIndex = this.startRangeIndex = -1;\n },\n onFilterKeyDown: function onFilterKeyDown(event) {\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event);\n break;\n case 'ArrowLeft':\n case 'ArrowRight':\n this.onArrowLeftKey(event, true);\n break;\n case 'Home':\n this.onHomeKey(event, true);\n break;\n case 'End':\n this.onEndKey(event, true);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'ShiftLeft':\n case 'ShiftRight':\n this.onShiftKey(event);\n break;\n }\n },\n onArrowDownKey: function onArrowDownKey(event) {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.findFirstFocusedOptionIndex();\n if (this.multiple && event.shiftKey) {\n this.onOptionSelectRange(event, this.startRangeIndex, optionIndex);\n }\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event) {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.findLastFocusedOptionIndex();\n if (this.multiple && event.shiftKey) {\n this.onOptionSelectRange(event, optionIndex, this.startRangeIndex);\n }\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n },\n onArrowLeftKey: function onArrowLeftKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n pressedInInputText && (this.focusedOptionIndex = -1);\n },\n onHomeKey: function onHomeKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(0, event.target.selectionStart);\n } else {\n target.setSelectionRange(0, 0);\n this.focusedOptionIndex = -1;\n }\n } else {\n var metaKey = event.metaKey || event.ctrlKey;\n var optionIndex = this.findFirstOptionIndex();\n if (this.multiple && event.shiftKey && metaKey) {\n this.onOptionSelectRange(event, optionIndex, this.startRangeIndex);\n }\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n event.preventDefault();\n },\n onEndKey: function onEndKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(event.target.selectionStart, target.value.length);\n } else {\n var len = target.value.length;\n target.setSelectionRange(len, len);\n this.focusedOptionIndex = -1;\n }\n } else {\n var metaKey = event.metaKey || event.ctrlKey;\n var optionIndex = this.findLastOptionIndex();\n if (this.multiple && event.shiftKey && metaKey) {\n this.onOptionSelectRange(event, this.startRangeIndex, optionIndex);\n }\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView(0);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView(this.visibleOptions.length - 1);\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event) {\n if (this.focusedOptionIndex !== -1) {\n if (this.multiple && event.shiftKey) this.onOptionSelectRange(event, this.focusedOptionIndex);else this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n },\n onSpaceKey: function onSpaceKey(event) {\n event.preventDefault();\n this.onEnterKey(event);\n },\n onShiftKey: function onShiftKey() {\n this.startRangeIndex = this.focusedOptionIndex;\n },\n isOptionMatched: function isOptionMatched(option) {\n var _this$getOptionLabel;\n return this.isValidOption(option) && typeof this.getOptionLabel(option) === 'string' && ((_this$getOptionLabel = this.getOptionLabel(option)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.filterLocale).startsWith(this.searchValue.toLocaleLowerCase(this.filterLocale)));\n },\n isValidOption: function isValidOption(option) {\n return isNotEmpty(option) && !(this.isOptionDisabled(option) || this.isOptionGroup(option));\n },\n isValidSelectedOption: function isValidSelectedOption(option) {\n return this.isValidOption(option) && this.isSelected(option);\n },\n isEquals: function isEquals(value1, value2) {\n return equals(value1, value2, this.equalityKey);\n },\n isSelected: function isSelected(option) {\n var _this4 = this;\n var optionValue = this.getOptionValue(option);\n if (this.multiple) return (this.modelValue || []).some(function (value) {\n return _this4.isEquals(value, optionValue);\n });else return this.isEquals(this.modelValue, optionValue);\n },\n findFirstOptionIndex: function findFirstOptionIndex() {\n var _this5 = this;\n return this.visibleOptions.findIndex(function (option) {\n return _this5.isValidOption(option);\n });\n },\n findLastOptionIndex: function findLastOptionIndex() {\n var _this6 = this;\n return findLastIndex(this.visibleOptions, function (option) {\n return _this6.isValidOption(option);\n });\n },\n findNextOptionIndex: function findNextOptionIndex(index) {\n var _this7 = this;\n var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this7.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;\n },\n findPrevOptionIndex: function findPrevOptionIndex(index) {\n var _this8 = this;\n var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this8.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findSelectedOptionIndex: function findSelectedOptionIndex() {\n var _this9 = this;\n if (this.hasSelectedOption) {\n if (this.multiple) {\n var _loop = function _loop() {\n var value = _this9.modelValue[index];\n var matchedOptionIndex = _this9.visibleOptions.findIndex(function (option) {\n return _this9.isValidSelectedOption(option) && _this9.isEquals(value, _this9.getOptionValue(option));\n });\n if (matchedOptionIndex > -1) return {\n v: matchedOptionIndex\n };\n },\n _ret;\n for (var index = this.modelValue.length - 1; index >= 0; index--) {\n _ret = _loop();\n if (_ret) return _ret.v;\n }\n } else {\n return this.visibleOptions.findIndex(function (option) {\n return _this9.isValidSelectedOption(option);\n });\n }\n }\n return -1;\n },\n findFirstSelectedOptionIndex: function findFirstSelectedOptionIndex() {\n var _this10 = this;\n return this.hasSelectedOption ? this.visibleOptions.findIndex(function (option) {\n return _this10.isValidSelectedOption(option);\n }) : -1;\n },\n findLastSelectedOptionIndex: function findLastSelectedOptionIndex() {\n var _this11 = this;\n return this.hasSelectedOption ? findLastIndex(this.visibleOptions, function (option) {\n return _this11.isValidSelectedOption(option);\n }) : -1;\n },\n findNextSelectedOptionIndex: function findNextSelectedOptionIndex(index) {\n var _this12 = this;\n var matchedOptionIndex = this.hasSelectedOption && index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this12.isValidSelectedOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : -1;\n },\n findPrevSelectedOptionIndex: function findPrevSelectedOptionIndex(index) {\n var _this13 = this;\n var matchedOptionIndex = this.hasSelectedOption && index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this13.isValidSelectedOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : -1;\n },\n findNearestSelectedOptionIndex: function findNearestSelectedOptionIndex(index) {\n var firstCheckUp = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n var matchedOptionIndex = -1;\n if (this.hasSelectedOption) {\n if (firstCheckUp) {\n matchedOptionIndex = this.findPrevSelectedOptionIndex(index);\n matchedOptionIndex = matchedOptionIndex === -1 ? this.findNextSelectedOptionIndex(index) : matchedOptionIndex;\n } else {\n matchedOptionIndex = this.findNextSelectedOptionIndex(index);\n matchedOptionIndex = matchedOptionIndex === -1 ? this.findPrevSelectedOptionIndex(index) : matchedOptionIndex;\n }\n }\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findFirstFocusedOptionIndex: function findFirstFocusedOptionIndex() {\n var selectedIndex = this.findFirstSelectedOptionIndex();\n return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;\n },\n findLastFocusedOptionIndex: function findLastFocusedOptionIndex() {\n var selectedIndex = this.findLastSelectedOptionIndex();\n return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;\n },\n searchOptions: function searchOptions(event, _char) {\n var _this14 = this;\n this.searchValue = (this.searchValue || '') + _char;\n var optionIndex = -1;\n if (isNotEmpty(this.searchValue)) {\n if (this.focusedOptionIndex !== -1) {\n optionIndex = this.visibleOptions.slice(this.focusedOptionIndex).findIndex(function (option) {\n return _this14.isOptionMatched(option);\n });\n optionIndex = optionIndex === -1 ? this.visibleOptions.slice(0, this.focusedOptionIndex).findIndex(function (option) {\n return _this14.isOptionMatched(option);\n }) : optionIndex + this.focusedOptionIndex;\n } else {\n optionIndex = this.visibleOptions.findIndex(function (option) {\n return _this14.isOptionMatched(option);\n });\n }\n if (optionIndex === -1 && this.focusedOptionIndex === -1) {\n optionIndex = this.findFirstFocusedOptionIndex();\n }\n if (optionIndex !== -1) {\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n }\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(function () {\n _this14.searchValue = '';\n _this14.searchTimeout = null;\n }, 500);\n },\n removeOption: function removeOption(option) {\n var _this15 = this;\n return this.modelValue.filter(function (val) {\n return !equals(val, _this15.getOptionValue(option), _this15.equalityKey);\n });\n },\n changeFocusedOptionIndex: function changeFocusedOptionIndex(event, index) {\n if (this.focusedOptionIndex !== index) {\n this.focusedOptionIndex = index;\n this.scrollInView();\n if (this.selectOnFocus && !this.multiple) {\n this.onOptionSelect(event, this.visibleOptions[index]);\n }\n }\n },\n scrollInView: function scrollInView() {\n var _this16 = this;\n var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n this.$nextTick(function () {\n var id = index !== -1 ? \"\".concat(_this16.id, \"_\").concat(index) : _this16.focusedOptionId;\n var element = findSingle(_this16.list, \"li[id=\\\"\".concat(id, \"\\\"]\"));\n if (element) {\n element.scrollIntoView && element.scrollIntoView({\n block: 'nearest',\n inline: 'nearest',\n behavior: 'smooth'\n });\n } else if (!_this16.virtualScrollerDisabled) {\n _this16.virtualScroller && _this16.virtualScroller.scrollToIndex(index !== -1 ? index : _this16.focusedOptionIndex);\n }\n });\n },\n autoUpdateModel: function autoUpdateModel() {\n if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption && !this.multiple && this.focused) {\n this.focusedOptionIndex = this.findFirstFocusedOptionIndex();\n this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex]);\n }\n },\n updateModel: function updateModel(event, value) {\n this.$emit('update:modelValue', value);\n this.$emit('change', {\n originalEvent: event,\n value: value\n });\n },\n flatOptions: function flatOptions(options) {\n var _this17 = this;\n return (options || []).reduce(function (result, option, index) {\n result.push({\n optionGroup: option,\n group: true,\n index: index\n });\n var optionGroupChildren = _this17.getOptionGroupChildren(option);\n optionGroupChildren && optionGroupChildren.forEach(function (o) {\n return result.push(o);\n });\n return result;\n }, []);\n },\n listRef: function listRef(el, contentRef) {\n this.list = el;\n contentRef && contentRef(el); // For VirtualScroller\n },\n virtualScrollerRef: function virtualScrollerRef(el) {\n this.virtualScroller = el;\n }\n },\n computed: {\n visibleOptions: function visibleOptions() {\n var options = this.optionGroupLabel ? this.flatOptions(this.options) : this.options || [];\n return this.filterValue ? FilterService.filter(options, this.searchFields, this.filterValue, this.filterMatchMode, this.filterLocale) : options;\n },\n hasSelectedOption: function hasSelectedOption() {\n return isNotEmpty(this.modelValue);\n },\n equalityKey: function equalityKey() {\n return this.optionValue ? null : this.dataKey;\n },\n searchFields: function searchFields() {\n return this.filterFields || [this.optionLabel];\n },\n filterResultMessageText: function filterResultMessageText() {\n return isNotEmpty(this.visibleOptions) ? this.filterMessageText.replaceAll('{0}', this.visibleOptions.length) : this.emptyFilterMessageText;\n },\n filterMessageText: function filterMessageText() {\n return this.filterMessage || this.$primevue.config.locale.searchMessage || '';\n },\n emptyFilterMessageText: function emptyFilterMessageText() {\n return this.emptyFilterMessage || this.$primevue.config.locale.emptySearchMessage || this.$primevue.config.locale.emptyFilterMessage || '';\n },\n emptyMessageText: function emptyMessageText() {\n return this.emptyMessage || this.$primevue.config.locale.emptyMessage || '';\n },\n selectionMessageText: function selectionMessageText() {\n return this.selectionMessage || this.$primevue.config.locale.selectionMessage || '';\n },\n emptySelectionMessageText: function emptySelectionMessageText() {\n return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || '';\n },\n selectedMessageText: function selectedMessageText() {\n return this.hasSelectedOption ? this.selectionMessageText.replaceAll('{0}', this.multiple ? this.modelValue.length : '1') : this.emptySelectionMessageText;\n },\n focusedOptionId: function focusedOptionId() {\n return this.focusedOptionIndex !== -1 ? \"\".concat(this.id, \"_\").concat(this.focusedOptionIndex) : null;\n },\n ariaSetSize: function ariaSetSize() {\n var _this18 = this;\n return this.visibleOptions.filter(function (option) {\n return !_this18.isOptionGroup(option);\n }).length;\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n InputText: InputText,\n VirtualScroller: VirtualScroller,\n InputIcon: InputIcon,\n IconField: IconField,\n SearchIcon: SearchIcon,\n CheckIcon: CheckIcon,\n BlankIcon: BlankIcon\n }\n};\n\nvar _hoisted_1 = [\"id\"];\nvar _hoisted_2 = [\"tabindex\"];\nvar _hoisted_3 = [\"id\", \"aria-multiselectable\", \"aria-label\", \"aria-labelledby\", \"aria-activedescendant\", \"aria-disabled\"];\nvar _hoisted_4 = [\"id\"];\nvar _hoisted_5 = [\"id\", \"aria-label\", \"aria-selected\", \"aria-disabled\", \"aria-setsize\", \"aria-posinset\", \"onClick\", \"onMousedown\", \"onMousemove\", \"onDblclick\", \"data-p-selected\", \"data-p-focused\", \"data-p-disabled\"];\nvar _hoisted_6 = [\"tabindex\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_SearchIcon = resolveComponent(\"SearchIcon\");\n var _component_InputIcon = resolveComponent(\"InputIcon\");\n var _component_IconField = resolveComponent(\"IconField\");\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_BlankIcon = resolveComponent(\"BlankIcon\");\n var _component_VirtualScroller = resolveComponent(\"VirtualScroller\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n id: $data.id,\n \"class\": _ctx.cx('root'),\n onFocusout: _cache[7] || (_cache[7] = function () {\n return $options.onFocusout && $options.onFocusout.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [createElementVNode(\"span\", mergeProps({\n ref: \"firstHiddenFocusableElement\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFirstHiddenFocus && $options.onFirstHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenFirstFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16, _hoisted_2), _ctx.$slots.header ? (openBlock(), createElementBlock(\"div\", {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('header'))\n }, [renderSlot(_ctx.$slots, \"header\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n })], 2)) : createCommentVNode(\"\", true), _ctx.filter ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [createVNode(_component_IconField, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterContainer')), {\n \"default\": withCtx(function () {\n return [createVNode(_component_InputText, {\n modelValue: $data.filterValue,\n \"onUpdate:modelValue\": _cache[1] || (_cache[1] = function ($event) {\n return $data.filterValue = $event;\n }),\n type: \"text\",\n \"class\": normalizeClass(_ctx.cx('pcFilter')),\n placeholder: _ctx.filterPlaceholder,\n role: \"searchbox\",\n autocomplete: \"off\",\n disabled: _ctx.disabled,\n unstyled: _ctx.unstyled,\n \"aria-owns\": $data.id + '_list',\n \"aria-activedescendant\": $options.focusedOptionId,\n tabindex: !_ctx.disabled && !$data.focused ? _ctx.tabindex : -1,\n onInput: $options.onFilterChange,\n onBlur: $options.onFilterBlur,\n onKeydown: $options.onFilterKeyDown,\n pt: _ctx.ptm('pcFilter')\n }, null, 8, [\"modelValue\", \"class\", \"placeholder\", \"disabled\", \"unstyled\", \"aria-owns\", \"aria-activedescendant\", \"tabindex\", \"onInput\", \"onBlur\", \"onKeydown\", \"pt\"]), createVNode(_component_InputIcon, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterIconContainer')), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"filtericon\", {}, function () {\n return [_ctx.filterIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.filterIcon\n }, _ctx.ptm('filterIcon')), null, 16)) : (openBlock(), createBlock(_component_SearchIcon, normalizeProps(mergeProps({\n key: 1\n }, _ctx.ptm('filterIcon'))), null, 16))];\n })];\n }),\n _: 3\n }, 16, [\"unstyled\"])];\n }),\n _: 3\n }, 16, [\"unstyled\"]), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenFilterResult'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.filterResultMessageText), 17)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('listContainer'),\n style: [{\n 'max-height': $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }, _ctx.listStyle]\n }, _ctx.ptm('listContainer')), [createVNode(_component_VirtualScroller, mergeProps({\n ref: $options.virtualScrollerRef\n }, _ctx.virtualScrollerOptions, {\n items: $options.visibleOptions,\n style: [{\n height: _ctx.scrollHeight\n }, _ctx.listStyle],\n tabindex: -1,\n disabled: $options.virtualScrollerDisabled,\n pt: _ctx.ptm('virtualScroller')\n }), createSlots({\n content: withCtx(function (_ref) {\n var styleClass = _ref.styleClass,\n contentRef = _ref.contentRef,\n items = _ref.items,\n getItemOptions = _ref.getItemOptions,\n contentStyle = _ref.contentStyle,\n itemSize = _ref.itemSize;\n return [createElementVNode(\"ul\", mergeProps({\n ref: function ref(el) {\n return $options.listRef(el, contentRef);\n },\n id: $data.id + '_list',\n \"class\": [_ctx.cx('list'), styleClass],\n style: contentStyle,\n tabindex: -1,\n role: \"listbox\",\n \"aria-multiselectable\": _ctx.multiple,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-disabled\": _ctx.disabled,\n onFocus: _cache[3] || (_cache[3] = function () {\n return $options.onListFocus && $options.onListFocus.apply($options, arguments);\n }),\n onBlur: _cache[4] || (_cache[4] = function () {\n return $options.onListBlur && $options.onListBlur.apply($options, arguments);\n }),\n onKeydown: _cache[5] || (_cache[5] = function () {\n return $options.onListKeyDown && $options.onListKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('list')), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function (option, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getOptionRenderKey(option, $options.getOptionIndex(i, getItemOptions))\n }, [$options.isOptionGroup(option) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('optionGroup'),\n role: \"option\",\n ref_for: true\n }, _ctx.ptm('optionGroup')), [renderSlot(_ctx.$slots, \"optiongroup\", {\n option: option.optionGroup,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionGroupLabel(option.optionGroup)), 1)];\n })], 16, _hoisted_4)) : withDirectives((openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('option', {\n option: option,\n index: i,\n getItemOptions: getItemOptions\n }),\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": $options.isSelected(option),\n \"aria-disabled\": $options.isOptionDisabled(option),\n \"aria-setsize\": $options.ariaSetSize,\n \"aria-posinset\": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),\n onClick: function onClick($event) {\n return $options.onOptionSelect($event, option, $options.getOptionIndex(i, getItemOptions));\n },\n onMousedown: function onMousedown($event) {\n return $options.onOptionMouseDown($event, $options.getOptionIndex(i, getItemOptions));\n },\n onMousemove: function onMousemove($event) {\n return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));\n },\n onTouchend: _cache[2] || (_cache[2] = function ($event) {\n return $options.onOptionTouchEnd();\n }),\n onDblclick: function onDblclick($event) {\n return $options.onOptionDblClick($event, option);\n },\n ref_for: true\n }, $options.getPTOptions(option, getItemOptions, i, 'option'), {\n \"data-p-selected\": $options.isSelected(option),\n \"data-p-focused\": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),\n \"data-p-disabled\": $options.isOptionDisabled(option)\n }), [_ctx.checkmark ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [$options.isSelected(option) ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 0,\n \"class\": _ctx.cx('optionCheckIcon'),\n ref_for: true\n }, _ctx.ptm('optionCheckIcon')), null, 16, [\"class\"])) : (openBlock(), createBlock(_component_BlankIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('optionBlankIcon'),\n ref_for: true\n }, _ctx.ptm('optionBlankIcon')), null, 16, [\"class\"]))], 64)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"option\", {\n option: option,\n selected: $options.isSelected(option),\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionLabel(option)), 1)];\n })], 16, _hoisted_5)), [[_directive_ripple]])], 64);\n }), 128)), $data.filterValue && (!items || items && items.length === 0) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage')), [renderSlot(_ctx.$slots, \"emptyfilter\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyFilterMessageText), 1)];\n })], 16)) : !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage')), [renderSlot(_ctx.$slots, \"empty\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyMessageText), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_3)];\n }),\n _: 2\n }, [_ctx.$slots.loader ? {\n name: \"loader\",\n fn: withCtx(function (_ref2) {\n var options = _ref2.options;\n return [renderSlot(_ctx.$slots, \"loader\", {\n options: options\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"items\", \"style\", \"disabled\", \"pt\"])], 16), renderSlot(_ctx.$slots, \"footer\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n }), !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenEmptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.emptyMessageText), 17)) : createCommentVNode(\"\", true), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSelectedMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.selectedMessageText), 17), createElementVNode(\"span\", mergeProps({\n ref: \"lastHiddenFocusableElement\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n onFocus: _cache[6] || (_cache[6] = function () {\n return $options.onLastHiddenFocus && $options.onLastHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenLastFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16, _hoisted_6)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-tabs {\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-tablist {\\n position: relative;\\n}\\n\\n.p-tabs-scrollable > .p-tablist {\\n overflow: hidden;\\n}\\n\\n.p-tablist-viewport {\\n overflow-x: auto;\\n overflow-y: hidden;\\n scroll-behavior: smooth;\\n scrollbar-width: none;\\n overscroll-behavior: contain auto;\\n}\\n\\n.p-tablist-viewport::-webkit-scrollbar {\\n display: none;\\n}\\n\\n.p-tablist-tab-list {\\n position: relative;\\n display: flex;\\n background: \".concat(dt('tabs.tablist.background'), \";\\n border-style: solid;\\n border-color: \").concat(dt('tabs.tablist.border.color'), \";\\n border-width: \").concat(dt('tabs.tablist.border.width'), \";\\n}\\n\\n.p-tablist-nav-button {\\n all: unset;\\n position: absolute;\\n top: 0;\\n z-index: 2;\\n height: 100%;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n background: \").concat(dt('tabs.nav.button.background'), \";\\n color: \").concat(dt('tabs.nav.button.color'), \";\\n width: \").concat(dt('tabs.nav.button.width'), \";\\n transition: color \").concat(dt('tabs.transition.duration'), \", outline-color \").concat(dt('tabs.transition.duration'), \", box-shadow \").concat(dt('tabs.transition.duration'), \";\\n box-shadow: \").concat(dt('tabs.nav.button.shadow'), \";\\n outline-color: transparent;\\n cursor: pointer;\\n}\\n\\n.p-tablist-nav-button:focus-visible {\\n z-index: 1;\\n box-shadow: \").concat(dt('tabs.nav.button.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.nav.button.focus.ring.width'), \" \").concat(dt('tabs.nav.button.focus.ring.style'), \" \").concat(dt('tabs.nav.button.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.nav.button.focus.ring.offset'), \";\\n}\\n\\n.p-tablist-nav-button:hover {\\n color: \").concat(dt('tabs.nav.button.hover.color'), \";\\n}\\n\\n.p-tablist-prev-button {\\n left: 0;\\n}\\n\\n.p-tablist-next-button {\\n right: 0;\\n}\\n\\n.p-tab {\\n cursor: pointer;\\n user-select: none;\\n position: relative;\\n border-style: solid;\\n white-space: nowrap;\\n background: \").concat(dt('tabs.tab.background'), \";\\n border-width: \").concat(dt('tabs.tab.border.width'), \";\\n border-color: \").concat(dt('tabs.tab.border.color'), \";\\n color: \").concat(dt('tabs.tab.color'), \";\\n padding: \").concat(dt('tabs.tab.padding'), \";\\n font-weight: \").concat(dt('tabs.tab.font.weight'), \";\\n transition: background \").concat(dt('tabs.transition.duration'), \", border-color \").concat(dt('tabs.transition.duration'), \", color \").concat(dt('tabs.transition.duration'), \", outline-color \").concat(dt('tabs.transition.duration'), \", box-shadow \").concat(dt('tabs.transition.duration'), \";\\n margin: \").concat(dt('tabs.tab.margin'), \";\\n outline-color: transparent;\\n}\\n\\n.p-tab:not(.p-disabled):focus-visible {\\n z-index: 1;\\n box-shadow: \").concat(dt('tabs.tab.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.tab.focus.ring.width'), \" \").concat(dt('tabs.tab.focus.ring.style'), \" \").concat(dt('tabs.tab.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.tab.focus.ring.offset'), \";\\n}\\n\\n.p-tab:not(.p-tab-active):not(.p-disabled):hover {\\n background: \").concat(dt('tabs.tab.hover.background'), \";\\n border-color: \").concat(dt('tabs.tab.hover.border.color'), \";\\n color: \").concat(dt('tabs.tab.hover.color'), \";\\n}\\n\\n.p-tab-active {\\n background: \").concat(dt('tabs.tab.active.background'), \";\\n border-color: \").concat(dt('tabs.tab.active.border.color'), \";\\n color: \").concat(dt('tabs.tab.active.color'), \";\\n}\\n\\n.p-tabpanels {\\n background: \").concat(dt('tabs.tabpanel.background'), \";\\n color: \").concat(dt('tabs.tabpanel.color'), \";\\n padding: \").concat(dt('tabs.tabpanel.padding'), \";\\n outline: 0 none;\\n}\\n\\n.p-tabpanel:focus-visible {\\n box-shadow: \").concat(dt('tabs.tabpanel.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.tabpanel.focus.ring.width'), \" \").concat(dt('tabs.tabpanel.focus.ring.style'), \" \").concat(dt('tabs.tabpanel.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.tabpanel.focus.ring.offset'), \";\\n}\\n\\n.p-tablist-active-bar {\\n z-index: 1;\\n display: block;\\n position: absolute;\\n bottom: \").concat(dt('tabs.active.bar.bottom'), \";\\n height: \").concat(dt('tabs.active.bar.height'), \";\\n background: \").concat(dt('tabs.active.bar.background'), \";\\n transition: 250ms cubic-bezier(0.35, 0, 0.25, 1);\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-tabs p-component', {\n 'p-tabs-scrollable': props.scrollable\n }];\n }\n};\nvar TabsStyle = BaseStyle.extend({\n name: 'tabs',\n theme: theme,\n classes: classes\n});\n\nexport { TabsStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TabsStyle from 'primevue/tabs/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseTabs',\n \"extends\": BaseComponent,\n props: {\n value: {\n type: String,\n \"default\": undefined\n },\n lazy: {\n type: Boolean,\n \"default\": false\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n showNavigators: {\n type: Boolean,\n \"default\": true\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n }\n },\n style: TabsStyle,\n provide: function provide() {\n return {\n $pcTabs: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Tabs',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:value'],\n data: function data() {\n return {\n id: this.$attrs.id,\n d_value: this.value\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n value: function value(newValue) {\n this.d_value = newValue;\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n },\n methods: {\n updateValue: function updateValue(newValue) {\n if (this.d_value !== newValue) {\n this.d_value = newValue;\n this.$emit('update:value', newValue);\n }\n },\n isVertical: function isVertical() {\n return this.orientation === 'vertical';\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: 'p-tabpanels'\n};\nvar TabPanelsStyle = BaseStyle.extend({\n name: 'tabpanels',\n classes: classes\n});\n\nexport { TabPanelsStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport TabPanelsStyle from 'primevue/tabpanels/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseTabPanels',\n \"extends\": BaseComponent,\n props: {},\n style: TabPanelsStyle,\n provide: function provide() {\n return {\n $pcTabPanels: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'TabPanels',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"presentation\"\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: function root(_ref) {\n var instance = _ref.instance;\n return ['p-tabpanel', {\n 'p-tabpanel-active': instance.active\n }];\n }\n};\nvar TabPanelStyle = BaseStyle.extend({\n name: 'tabpanel',\n classes: classes\n});\n\nexport { TabPanelStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { equals } from '@primeuix/utils/object';\nimport { mergeProps, renderSlot, openBlock, createElementBlock, Fragment, withDirectives, createBlock, resolveDynamicComponent, withCtx, vShow, createCommentVNode, normalizeClass } from 'vue';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TabPanelStyle from 'primevue/tabpanel/style';\n\nvar script$1 = {\n name: 'BaseTabPanel',\n \"extends\": BaseComponent,\n props: {\n // in Tabs\n value: {\n type: String,\n \"default\": undefined\n },\n as: {\n type: String,\n \"default\": 'DIV'\n },\n asChild: {\n type: Boolean,\n \"default\": false\n },\n // in TabView\n header: null,\n headerStyle: null,\n headerClass: null,\n headerProps: null,\n headerActionProps: null,\n contentStyle: null,\n contentClass: null,\n contentProps: null,\n disabled: Boolean\n },\n style: TabPanelStyle,\n provide: function provide() {\n return {\n $pcTabPanel: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'TabPanel',\n \"extends\": script$1,\n inheritAttrs: false,\n inject: ['$pcTabs'],\n computed: {\n active: function active() {\n var _this$$pcTabs;\n return equals((_this$$pcTabs = this.$pcTabs) === null || _this$$pcTabs === void 0 ? void 0 : _this$$pcTabs.d_value, this.value);\n },\n id: function id() {\n var _this$$pcTabs2;\n return \"\".concat((_this$$pcTabs2 = this.$pcTabs) === null || _this$$pcTabs2 === void 0 ? void 0 : _this$$pcTabs2.id, \"_tabpanel_\").concat(this.value);\n },\n ariaLabelledby: function ariaLabelledby() {\n var _this$$pcTabs3;\n return \"\".concat((_this$$pcTabs3 = this.$pcTabs) === null || _this$$pcTabs3 === void 0 ? void 0 : _this$$pcTabs3.id, \"_tab_\").concat(this.value);\n },\n attrs: function attrs() {\n return mergeProps(this.a11yAttrs, this.ptmi('root', this.ptParams));\n },\n a11yAttrs: function a11yAttrs() {\n var _this$$pcTabs4;\n return {\n id: this.id,\n tabindex: (_this$$pcTabs4 = this.$pcTabs) === null || _this$$pcTabs4 === void 0 ? void 0 : _this$$pcTabs4.tabindex,\n role: 'tabpanel',\n 'aria-labelledby': this.ariaLabelledby,\n 'data-pc-name': 'tabpanel',\n 'data-p-active': this.active\n };\n },\n ptParams: function ptParams() {\n return {\n context: {\n active: this.active\n }\n };\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _$options$$pcTabs, _$options$$pcTabs2;\n return !$options.$pcTabs ? renderSlot(_ctx.$slots, \"default\", {\n key: 0\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [!_ctx.asChild ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [((_$options$$pcTabs = $options.$pcTabs) !== null && _$options$$pcTabs !== void 0 && _$options$$pcTabs.lazy ? $options.active : true) ? withDirectives((openBlock(), createBlock(resolveDynamicComponent(_ctx.as), mergeProps({\n key: 0,\n \"class\": _ctx.cx('root')\n }, $options.attrs), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"class\"])), [[vShow, (_$options$$pcTabs2 = $options.$pcTabs) !== null && _$options$$pcTabs2 !== void 0 && _$options$$pcTabs2.lazy ? true : $options.active]]) : createCommentVNode(\"\", true)], 64)) : renderSlot(_ctx.$slots, \"default\", {\n key: 1,\n \"class\": normalizeClass(_ctx.cx('root')),\n active: $options.active,\n a11yAttrs: $options.a11yAttrs\n })], 64));\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-divider-horizontal {\\n display: flex;\\n width: 100%;\\n position: relative;\\n align-items: center;\\n margin: \".concat(dt('divider.horizontal.margin'), \";\\n padding: \").concat(dt('divider.horizontal.padding'), \";\\n}\\n\\n.p-divider-horizontal:before {\\n position: absolute;\\n display: block;\\n top: 50%;\\n left: 0;\\n width: 100%;\\n content: \\\"\\\";\\n border-top: 1px solid \").concat(dt('divider.border.color'), \";\\n}\\n\\n.p-divider-horizontal .p-divider-content {\\n padding: \").concat(dt('divider.horizontal.content.padding'), \";\\n}\\n\\n.p-divider-vertical {\\n min-height: 100%;\\n margin: 0 1rem;\\n display: flex;\\n position: relative;\\n justify-content: center;\\n margin: \").concat(dt('divider.vertical.margin'), \";\\n padding: \").concat(dt('divider.vertical.padding'), \";\\n}\\n\\n.p-divider-vertical:before {\\n position: absolute;\\n display: block;\\n top: 0;\\n left: 50%;\\n height: 100%;\\n content: \\\"\\\";\\n border-left: 1px solid \").concat(dt('divider.border.color'), \";\\n}\\n\\n.p-divider.p-divider-vertical .p-divider-content {\\n padding: \").concat(dt('divider.vertical.content.padding'), \";\\n}\\n\\n.p-divider-content {\\n z-index: 1;\\n background: \").concat(dt('divider.content.background'), \";\\n color: \").concat(dt('divider.content.color'), \";\\n}\\n\\n.p-divider-solid.p-divider-horizontal:before {\\n border-top-style: solid;\\n}\\n\\n.p-divider-solid.p-divider-vertical:before {\\n border-left-style: solid;\\n}\\n\\n.p-divider-dashed.p-divider-horizontal:before {\\n border-top-style: dashed;\\n}\\n\\n.p-divider-dashed.p-divider-vertical:before {\\n border-left-style: dashed;\\n}\\n\\n.p-divider-dotted.p-divider-horizontal:before {\\n border-top-style: dotted;\\n}\\n\\n.p-divider-dotted.p-divider-vertical:before {\\n border-left-style: dotted;\\n}\\n\");\n};\n\n/* Position */\nvar inlineStyles = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return {\n justifyContent: props.layout === 'horizontal' ? props.align === 'center' || props.align === null ? 'center' : props.align === 'left' ? 'flex-start' : props.align === 'right' ? 'flex-end' : null : null,\n alignItems: props.layout === 'vertical' ? props.align === 'center' || props.align === null ? 'center' : props.align === 'top' ? 'flex-start' : props.align === 'bottom' ? 'flex-end' : null : null\n };\n }\n};\nvar classes = {\n root: function root(_ref3) {\n var props = _ref3.props;\n return ['p-divider p-component', 'p-divider-' + props.layout, 'p-divider-' + props.type, {\n 'p-divider-left': props.layout === 'horizontal' && (!props.align || props.align === 'left')\n }, {\n 'p-divider-center': props.layout === 'horizontal' && props.align === 'center'\n }, {\n 'p-divider-right': props.layout === 'horizontal' && props.align === 'right'\n }, {\n 'p-divider-top': props.layout === 'vertical' && props.align === 'top'\n }, {\n 'p-divider-center': props.layout === 'vertical' && (!props.align || props.align === 'center')\n }, {\n 'p-divider-bottom': props.layout === 'vertical' && props.align === 'bottom'\n }];\n },\n content: 'p-divider-content'\n};\nvar DividerStyle = BaseStyle.extend({\n name: 'divider',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { DividerStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport DividerStyle from 'primevue/divider/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseDivider',\n \"extends\": BaseComponent,\n props: {\n align: {\n type: String,\n \"default\": null\n },\n layout: {\n type: String,\n \"default\": 'horizontal'\n },\n type: {\n type: String,\n \"default\": 'solid'\n }\n },\n style: DividerStyle,\n provide: function provide() {\n return {\n $pcDivider: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Divider',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nvar _hoisted_1 = [\"aria-orientation\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n role: \"separator\",\n \"aria-orientation\": _ctx.layout\n }, _ctx.ptmi('root')), [_ctx.$slots[\"default\"] ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('content')\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"default\")], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M3.58659 4.5007C3.68513 4.50023 3.78277 4.51945 3.87379 4.55723C3.9648 4.59501 4.04735 4.65058 4.11659 4.7207L7.11659 7.7207L10.1166 4.7207C10.2619 4.65055 10.4259 4.62911 10.5843 4.65956C10.7427 4.69002 10.8871 4.77074 10.996 4.88976C11.1049 5.00877 11.1726 5.15973 11.1889 5.32022C11.2052 5.48072 11.1693 5.6422 11.0866 5.7807L7.58659 9.2807C7.44597 9.42115 7.25534 9.50004 7.05659 9.50004C6.85784 9.50004 6.66722 9.42115 6.52659 9.2807L3.02659 5.7807C2.88614 5.64007 2.80725 5.44945 2.80725 5.2507C2.80725 5.05195 2.88614 4.86132 3.02659 4.7207C3.09932 4.64685 3.18675 4.58911 3.28322 4.55121C3.37969 4.51331 3.48305 4.4961 3.58659 4.5007Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleUpIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M10.4134 9.49931C10.3148 9.49977 10.2172 9.48055 10.1262 9.44278C10.0352 9.405 9.95263 9.34942 9.88338 9.27931L6.88338 6.27931L3.88338 9.27931C3.73811 9.34946 3.57409 9.3709 3.41567 9.34044C3.25724 9.30999 3.11286 9.22926 3.00395 9.11025C2.89504 8.99124 2.82741 8.84028 2.8111 8.67978C2.79478 8.51928 2.83065 8.35781 2.91338 8.21931L6.41338 4.71931C6.55401 4.57886 6.74463 4.49997 6.94338 4.49997C7.14213 4.49997 7.33276 4.57886 7.47338 4.71931L10.9734 8.21931C11.1138 8.35994 11.1927 8.55056 11.1927 8.74931C11.1927 8.94806 11.1138 9.13868 10.9734 9.27931C10.9007 9.35315 10.8132 9.41089 10.7168 9.44879C10.6203 9.48669 10.5169 9.5039 10.4134 9.49931Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-inputnumber {\\n display: inline-flex;\\n position: relative;\\n}\\n\\n.p-inputnumber-button {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex: 0 0 auto;\\n cursor: pointer;\\n background: \".concat(dt('inputnumber.button.background'), \";\\n color: \").concat(dt('inputnumber.button.color'), \";\\n width: \").concat(dt('inputnumber.button.width'), \";\\n transition: background \").concat(dt('inputnumber.transition.duration'), \", color \").concat(dt('inputnumber.transition.duration'), \", border-color \").concat(dt('inputnumber.transition.duration'), \", outline-color \").concat(dt('inputnumber.transition.duration'), \";\\n}\\n\\n.p-inputnumber-button:hover {\\n background: \").concat(dt('inputnumber.button.hover.background'), \";\\n color: \").concat(dt('inputnumber.button.hover.color'), \";\\n}\\n\\n.p-inputnumber-button:active {\\n background: \").concat(dt('inputnumber.button.active.background'), \";\\n color: \").concat(dt('inputnumber.button.active.color'), \";\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button {\\n position: relative;\\n border: 0 none;\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button-group {\\n display: flex;\\n flex-direction: column;\\n position: absolute;\\n top: 1px;\\n right: 1px;\\n height: calc(100% - 2px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-increment-button {\\n padding: 0;\\n border-top-right-radius: calc(\").concat(dt('inputnumber.button.border.radius'), \" - 1px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-decrement-button {\\n padding: 0;\\n border-bottom-right-radius: calc(\").concat(dt('inputnumber.button.border.radius'), \" - 1px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button {\\n flex: 1 1 auto;\\n border: 0 none;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button {\\n border: 1px solid \").concat(dt('inputnumber.button.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button:hover {\\n border-color: \").concat(dt('inputnumber.button.hover.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button:active {\\n border-color: \").concat(dt('inputnumber.button.active.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-increment-button {\\n order: 3;\\n border-top-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-left: 0 none;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-input {\\n order: 2;\\n border-radius: 0;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-decrement-button {\\n order: 1;\\n border-top-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-right: 0 none;\\n}\\n\\n.p-inputnumber-vertical {\\n flex-direction: column;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button {\\n border: 1px solid \").concat(dt('inputnumber.button.border.color'), \";\\n padding: \").concat(dt('inputnumber.button.vertical.padding'), \"; 0;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button:hover {\\n border-color: \").concat(dt('inputnumber.button.hover.border.color'), \";\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button:active {\\n border-color: \").concat(dt('inputnumber.button.active.border.color'), \";\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-increment-button {\\n order: 1;\\n border-top-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-top-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n width: 100%;\\n border-bottom: 0 none;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-input {\\n order: 2;\\n border-radius: 0;\\n text-align: center;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-decrement-button {\\n order: 3;\\n border-bottom-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n width: 100%;\\n border-top: 0 none;\\n}\\n\\n.p-inputnumber-input {\\n flex: 1 1 auto;\\n}\\n\\n.p-inputnumber-fluid {\\n width: 100%;\\n}\\n\\n.p-inputnumber-fluid .p-inputnumber-input {\\n width: 1%;\\n}\\n\\n.p-inputnumber-fluid.p-inputnumber-vertical .p-inputnumber-input {\\n width: 100%;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-inputnumber p-component p-inputwrapper', {\n 'p-inputwrapper-filled': instance.filled || props.allowEmpty === false,\n 'p-inputwrapper-focus': instance.focused,\n 'p-inputnumber-stacked': props.showButtons && props.buttonLayout === 'stacked',\n 'p-inputnumber-horizontal': props.showButtons && props.buttonLayout === 'horizontal',\n 'p-inputnumber-vertical': props.showButtons && props.buttonLayout === 'vertical',\n 'p-inputnumber-fluid': instance.fluid\n }];\n },\n pcInput: 'p-inputnumber-input',\n buttonGroup: 'p-inputnumber-button-group',\n incrementButton: function incrementButton(_ref3) {\n var instance = _ref3.instance,\n props = _ref3.props;\n return ['p-inputnumber-button p-inputnumber-increment-button', {\n 'p-disabled': props.showButtons && props.max !== null && instance.maxBoundry()\n }];\n },\n decrementButton: function decrementButton(_ref4) {\n var instance = _ref4.instance,\n props = _ref4.props;\n return ['p-inputnumber-button p-inputnumber-decrement-button', {\n 'p-disabled': props.showButtons && props.min !== null && instance.minBoundry()\n }];\n }\n};\nvar InputNumberStyle = BaseStyle.extend({\n name: 'inputnumber',\n theme: theme,\n classes: classes\n});\n\nexport { InputNumberStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getSelection, clearSelection } from '@primeuix/utils/dom';\nimport { isNotEmpty } from '@primeuix/utils/object';\nimport AngleDownIcon from '@primevue/icons/angledown';\nimport AngleUpIcon from '@primevue/icons/angleup';\nimport InputText from 'primevue/inputtext';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport InputNumberStyle from 'primevue/inputnumber/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, createVNode, normalizeClass, normalizeStyle, renderSlot, createElementVNode, toHandlers, createBlock, resolveDynamicComponent, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseInputNumber',\n \"extends\": BaseComponent,\n props: {\n modelValue: {\n type: Number,\n \"default\": null\n },\n format: {\n type: Boolean,\n \"default\": true\n },\n showButtons: {\n type: Boolean,\n \"default\": false\n },\n buttonLayout: {\n type: String,\n \"default\": 'stacked'\n },\n incrementButtonClass: {\n type: String,\n \"default\": null\n },\n decrementButtonClass: {\n type: String,\n \"default\": null\n },\n incrementButtonIcon: {\n type: String,\n \"default\": undefined\n },\n incrementIcon: {\n type: String,\n \"default\": undefined\n },\n decrementButtonIcon: {\n type: String,\n \"default\": undefined\n },\n decrementIcon: {\n type: String,\n \"default\": undefined\n },\n locale: {\n type: String,\n \"default\": undefined\n },\n localeMatcher: {\n type: String,\n \"default\": undefined\n },\n mode: {\n type: String,\n \"default\": 'decimal'\n },\n prefix: {\n type: String,\n \"default\": null\n },\n suffix: {\n type: String,\n \"default\": null\n },\n currency: {\n type: String,\n \"default\": undefined\n },\n currencyDisplay: {\n type: String,\n \"default\": undefined\n },\n useGrouping: {\n type: Boolean,\n \"default\": true\n },\n minFractionDigits: {\n type: Number,\n \"default\": undefined\n },\n maxFractionDigits: {\n type: Number,\n \"default\": undefined\n },\n roundingMode: {\n type: String,\n \"default\": 'halfExpand',\n validator: function validator(value) {\n return ['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven'].includes(value);\n }\n },\n min: {\n type: Number,\n \"default\": null\n },\n max: {\n type: Number,\n \"default\": null\n },\n step: {\n type: Number,\n \"default\": 1\n },\n allowEmpty: {\n type: Boolean,\n \"default\": true\n },\n highlightOnFocus: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n placeholder: {\n type: String,\n \"default\": null\n },\n fluid: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: InputNumberStyle,\n provide: function provide() {\n return {\n $pcInputNumber: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'InputNumber',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'input', 'focus', 'blur'],\n numberFormat: null,\n _numeral: null,\n _decimal: null,\n _group: null,\n _minusSign: null,\n _currency: null,\n _suffix: null,\n _prefix: null,\n _index: null,\n groupChar: '',\n isSpecialChar: null,\n prefixChar: null,\n suffixChar: null,\n timer: null,\n data: function data() {\n return {\n d_modelValue: this.modelValue,\n focused: false\n };\n },\n watch: {\n modelValue: function modelValue(newValue) {\n this.d_modelValue = newValue;\n },\n locale: function locale(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n localeMatcher: function localeMatcher(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n mode: function mode(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n currency: function currency(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n currencyDisplay: function currencyDisplay(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n useGrouping: function useGrouping(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n minFractionDigits: function minFractionDigits(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n maxFractionDigits: function maxFractionDigits(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n suffix: function suffix(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n prefix: function prefix(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n }\n },\n created: function created() {\n this.constructParser();\n },\n methods: {\n getOptions: function getOptions() {\n return {\n localeMatcher: this.localeMatcher,\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n useGrouping: this.useGrouping,\n minimumFractionDigits: this.minFractionDigits,\n maximumFractionDigits: this.maxFractionDigits,\n roundingMode: this.roundingMode\n };\n },\n constructParser: function constructParser() {\n this.numberFormat = new Intl.NumberFormat(this.locale, this.getOptions());\n var numerals = _toConsumableArray(new Intl.NumberFormat(this.locale, {\n useGrouping: false\n }).format(9876543210)).reverse();\n var index = new Map(numerals.map(function (d, i) {\n return [d, i];\n }));\n this._numeral = new RegExp(\"[\".concat(numerals.join(''), \"]\"), 'g');\n this._group = this.getGroupingExpression();\n this._minusSign = this.getMinusSignExpression();\n this._currency = this.getCurrencyExpression();\n this._decimal = this.getDecimalExpression();\n this._suffix = this.getSuffixExpression();\n this._prefix = this.getPrefixExpression();\n this._index = function (d) {\n return index.get(d);\n };\n },\n updateConstructParser: function updateConstructParser(newValue, oldValue) {\n if (newValue !== oldValue) {\n this.constructParser();\n }\n },\n escapeRegExp: function escapeRegExp(text) {\n return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n },\n getDecimalExpression: function getDecimalExpression() {\n var formatter = new Intl.NumberFormat(this.locale, _objectSpread(_objectSpread({}, this.getOptions()), {}, {\n useGrouping: false\n }));\n return new RegExp(\"[\".concat(formatter.format(1.1).replace(this._currency, '').trim().replace(this._numeral, ''), \"]\"), 'g');\n },\n getGroupingExpression: function getGroupingExpression() {\n var formatter = new Intl.NumberFormat(this.locale, {\n useGrouping: true\n });\n this.groupChar = formatter.format(1000000).trim().replace(this._numeral, '').charAt(0);\n return new RegExp(\"[\".concat(this.groupChar, \"]\"), 'g');\n },\n getMinusSignExpression: function getMinusSignExpression() {\n var formatter = new Intl.NumberFormat(this.locale, {\n useGrouping: false\n });\n return new RegExp(\"[\".concat(formatter.format(-1).trim().replace(this._numeral, ''), \"]\"), 'g');\n },\n getCurrencyExpression: function getCurrencyExpression() {\n if (this.currency) {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: 'currency',\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n roundingMode: this.roundingMode\n });\n return new RegExp(\"[\".concat(formatter.format(1).replace(/\\s/g, '').replace(this._numeral, '').replace(this._group, ''), \"]\"), 'g');\n }\n return new RegExp(\"[]\", 'g');\n },\n getPrefixExpression: function getPrefixExpression() {\n if (this.prefix) {\n this.prefixChar = this.prefix;\n } else {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay\n });\n this.prefixChar = formatter.format(1).split('1')[0];\n }\n return new RegExp(\"\".concat(this.escapeRegExp(this.prefixChar || '')), 'g');\n },\n getSuffixExpression: function getSuffixExpression() {\n if (this.suffix) {\n this.suffixChar = this.suffix;\n } else {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n roundingMode: this.roundingMode\n });\n this.suffixChar = formatter.format(1).split('1')[1];\n }\n return new RegExp(\"\".concat(this.escapeRegExp(this.suffixChar || '')), 'g');\n },\n formatValue: function formatValue(value) {\n if (value != null) {\n if (value === '-') {\n // Minus sign\n return value;\n }\n if (this.format) {\n var formatter = new Intl.NumberFormat(this.locale, this.getOptions());\n var formattedValue = formatter.format(value);\n if (this.prefix) {\n formattedValue = this.prefix + formattedValue;\n }\n if (this.suffix) {\n formattedValue = formattedValue + this.suffix;\n }\n return formattedValue;\n }\n return value.toString();\n }\n return '';\n },\n parseValue: function parseValue(text) {\n var filteredText = text.replace(this._suffix, '').replace(this._prefix, '').trim().replace(/\\s/g, '').replace(this._currency, '').replace(this._group, '').replace(this._minusSign, '-').replace(this._decimal, '.').replace(this._numeral, this._index);\n if (filteredText) {\n if (filteredText === '-')\n // Minus sign\n return filteredText;\n var parsedValue = +filteredText;\n return isNaN(parsedValue) ? null : parsedValue;\n }\n return null;\n },\n repeat: function repeat(event, interval, dir) {\n var _this = this;\n if (this.readonly) {\n return;\n }\n var i = interval || 500;\n this.clearTimer();\n this.timer = setTimeout(function () {\n _this.repeat(event, 40, dir);\n }, i);\n this.spin(event, dir);\n },\n spin: function spin(event, dir) {\n if (this.$refs.input) {\n var step = this.step * dir;\n var currentValue = this.parseValue(this.$refs.input.$el.value) || 0;\n var newValue = this.validateValue(currentValue + step);\n this.updateInput(newValue, null, 'spin');\n this.updateModel(event, newValue);\n this.handleOnInput(event, currentValue, newValue);\n }\n },\n onUpButtonMouseDown: function onUpButtonMouseDown(event) {\n if (!this.disabled) {\n this.$refs.input.$el.focus();\n this.repeat(event, null, 1);\n event.preventDefault();\n }\n },\n onUpButtonMouseUp: function onUpButtonMouseUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonMouseLeave: function onUpButtonMouseLeave() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonKeyUp: function onUpButtonKeyUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonKeyDown: function onUpButtonKeyDown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.repeat(event, null, 1);\n }\n },\n onDownButtonMouseDown: function onDownButtonMouseDown(event) {\n if (!this.disabled) {\n this.$refs.input.$el.focus();\n this.repeat(event, null, -1);\n event.preventDefault();\n }\n },\n onDownButtonMouseUp: function onDownButtonMouseUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonMouseLeave: function onDownButtonMouseLeave() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonKeyUp: function onDownButtonKeyUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonKeyDown: function onDownButtonKeyDown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.repeat(event, null, -1);\n }\n },\n onUserInput: function onUserInput() {\n if (this.isSpecialChar) {\n this.$refs.input.$el.value = this.lastValue;\n }\n this.isSpecialChar = false;\n },\n onInputKeyDown: function onInputKeyDown(event) {\n if (this.readonly) {\n return;\n }\n if (event.altKey || event.ctrlKey || event.metaKey) {\n this.isSpecialChar = true;\n this.lastValue = this.$refs.input.$el.value;\n return;\n }\n this.lastValue = event.target.value;\n var selectionStart = event.target.selectionStart;\n var selectionEnd = event.target.selectionEnd;\n var inputValue = event.target.value;\n var newValueStr = null;\n switch (event.code) {\n case 'ArrowUp':\n this.spin(event, 1);\n event.preventDefault();\n break;\n case 'ArrowDown':\n this.spin(event, -1);\n event.preventDefault();\n break;\n case 'ArrowLeft':\n if (!this.isNumeralChar(inputValue.charAt(selectionStart - 1))) {\n event.preventDefault();\n }\n break;\n case 'ArrowRight':\n if (!this.isNumeralChar(inputValue.charAt(selectionStart))) {\n event.preventDefault();\n }\n break;\n case 'Tab':\n case 'Enter':\n case 'NumpadEnter':\n newValueStr = this.validateValue(this.parseValue(inputValue));\n this.$refs.input.$el.value = this.formatValue(newValueStr);\n this.$refs.input.$el.setAttribute('aria-valuenow', newValueStr);\n this.updateModel(event, newValueStr);\n break;\n case 'Backspace':\n {\n event.preventDefault();\n if (selectionStart === selectionEnd) {\n var deleteChar = inputValue.charAt(selectionStart - 1);\n var _this$getDecimalCharI = this.getDecimalCharIndexes(inputValue),\n decimalCharIndex = _this$getDecimalCharI.decimalCharIndex,\n decimalCharIndexWithoutPrefix = _this$getDecimalCharI.decimalCharIndexWithoutPrefix;\n if (this.isNumeralChar(deleteChar)) {\n var decimalLength = this.getDecimalLength(inputValue);\n if (this._group.test(deleteChar)) {\n this._group.lastIndex = 0;\n newValueStr = inputValue.slice(0, selectionStart - 2) + inputValue.slice(selectionStart - 1);\n } else if (this._decimal.test(deleteChar)) {\n this._decimal.lastIndex = 0;\n if (decimalLength) {\n this.$refs.input.$el.setSelectionRange(selectionStart - 1, selectionStart - 1);\n } else {\n newValueStr = inputValue.slice(0, selectionStart - 1) + inputValue.slice(selectionStart);\n }\n } else if (decimalCharIndex > 0 && selectionStart > decimalCharIndex) {\n var insertedText = this.isDecimalMode() && (this.minFractionDigits || 0) < decimalLength ? '' : '0';\n newValueStr = inputValue.slice(0, selectionStart - 1) + insertedText + inputValue.slice(selectionStart);\n } else if (decimalCharIndexWithoutPrefix === 1) {\n newValueStr = inputValue.slice(0, selectionStart - 1) + '0' + inputValue.slice(selectionStart);\n newValueStr = this.parseValue(newValueStr) > 0 ? newValueStr : '';\n } else {\n newValueStr = inputValue.slice(0, selectionStart - 1) + inputValue.slice(selectionStart);\n }\n }\n this.updateValue(event, newValueStr, null, 'delete-single');\n } else {\n newValueStr = this.deleteRange(inputValue, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, null, 'delete-range');\n }\n break;\n }\n case 'Delete':\n event.preventDefault();\n if (selectionStart === selectionEnd) {\n var _deleteChar = inputValue.charAt(selectionStart);\n var _this$getDecimalCharI2 = this.getDecimalCharIndexes(inputValue),\n _decimalCharIndex = _this$getDecimalCharI2.decimalCharIndex,\n _decimalCharIndexWithoutPrefix = _this$getDecimalCharI2.decimalCharIndexWithoutPrefix;\n if (this.isNumeralChar(_deleteChar)) {\n var _decimalLength = this.getDecimalLength(inputValue);\n if (this._group.test(_deleteChar)) {\n this._group.lastIndex = 0;\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 2);\n } else if (this._decimal.test(_deleteChar)) {\n this._decimal.lastIndex = 0;\n if (_decimalLength) {\n this.$refs.input.$el.setSelectionRange(selectionStart + 1, selectionStart + 1);\n } else {\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 1);\n }\n } else if (_decimalCharIndex > 0 && selectionStart > _decimalCharIndex) {\n var _insertedText = this.isDecimalMode() && (this.minFractionDigits || 0) < _decimalLength ? '' : '0';\n newValueStr = inputValue.slice(0, selectionStart) + _insertedText + inputValue.slice(selectionStart + 1);\n } else if (_decimalCharIndexWithoutPrefix === 1) {\n newValueStr = inputValue.slice(0, selectionStart) + '0' + inputValue.slice(selectionStart + 1);\n newValueStr = this.parseValue(newValueStr) > 0 ? newValueStr : '';\n } else {\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 1);\n }\n }\n this.updateValue(event, newValueStr, null, 'delete-back-single');\n } else {\n newValueStr = this.deleteRange(inputValue, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, null, 'delete-range');\n }\n break;\n case 'Home':\n event.preventDefault();\n if (isNotEmpty(this.min)) {\n this.updateModel(event, this.min);\n }\n break;\n case 'End':\n event.preventDefault();\n if (isNotEmpty(this.max)) {\n this.updateModel(event, this.max);\n }\n break;\n }\n },\n onInputKeyPress: function onInputKeyPress(event) {\n if (this.readonly) {\n return;\n }\n var _char = event.key;\n var isDecimalSign = this.isDecimalSign(_char);\n var isMinusSign = this.isMinusSign(_char);\n if (event.code !== 'Enter') {\n event.preventDefault();\n }\n if (Number(_char) >= 0 && Number(_char) <= 9 || isMinusSign || isDecimalSign) {\n this.insert(event, _char, {\n isDecimalSign: isDecimalSign,\n isMinusSign: isMinusSign\n });\n }\n },\n onPaste: function onPaste(event) {\n event.preventDefault();\n var data = (event.clipboardData || window['clipboardData']).getData('Text');\n if (data) {\n var filteredData = this.parseValue(data);\n if (filteredData != null) {\n this.insert(event, filteredData.toString());\n }\n }\n },\n allowMinusSign: function allowMinusSign() {\n return this.min === null || this.min < 0;\n },\n isMinusSign: function isMinusSign(_char2) {\n if (this._minusSign.test(_char2) || _char2 === '-') {\n this._minusSign.lastIndex = 0;\n return true;\n }\n return false;\n },\n isDecimalSign: function isDecimalSign(_char3) {\n if (this._decimal.test(_char3)) {\n this._decimal.lastIndex = 0;\n return true;\n }\n return false;\n },\n isDecimalMode: function isDecimalMode() {\n return this.mode === 'decimal';\n },\n getDecimalCharIndexes: function getDecimalCharIndexes(val) {\n var decimalCharIndex = val.search(this._decimal);\n this._decimal.lastIndex = 0;\n var filteredVal = val.replace(this._prefix, '').trim().replace(/\\s/g, '').replace(this._currency, '');\n var decimalCharIndexWithoutPrefix = filteredVal.search(this._decimal);\n this._decimal.lastIndex = 0;\n return {\n decimalCharIndex: decimalCharIndex,\n decimalCharIndexWithoutPrefix: decimalCharIndexWithoutPrefix\n };\n },\n getCharIndexes: function getCharIndexes(val) {\n var decimalCharIndex = val.search(this._decimal);\n this._decimal.lastIndex = 0;\n var minusCharIndex = val.search(this._minusSign);\n this._minusSign.lastIndex = 0;\n var suffixCharIndex = val.search(this._suffix);\n this._suffix.lastIndex = 0;\n var currencyCharIndex = val.search(this._currency);\n this._currency.lastIndex = 0;\n return {\n decimalCharIndex: decimalCharIndex,\n minusCharIndex: minusCharIndex,\n suffixCharIndex: suffixCharIndex,\n currencyCharIndex: currencyCharIndex\n };\n },\n insert: function insert(event, text) {\n var sign = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n isDecimalSign: false,\n isMinusSign: false\n };\n var minusCharIndexOnText = text.search(this._minusSign);\n this._minusSign.lastIndex = 0;\n if (!this.allowMinusSign() && minusCharIndexOnText !== -1) {\n return;\n }\n var selectionStart = this.$refs.input.$el.selectionStart;\n var selectionEnd = this.$refs.input.$el.selectionEnd;\n var inputValue = this.$refs.input.$el.value.trim();\n var _this$getCharIndexes = this.getCharIndexes(inputValue),\n decimalCharIndex = _this$getCharIndexes.decimalCharIndex,\n minusCharIndex = _this$getCharIndexes.minusCharIndex,\n suffixCharIndex = _this$getCharIndexes.suffixCharIndex,\n currencyCharIndex = _this$getCharIndexes.currencyCharIndex;\n var newValueStr;\n if (sign.isMinusSign) {\n if (selectionStart === 0) {\n newValueStr = inputValue;\n if (minusCharIndex === -1 || selectionEnd !== 0) {\n newValueStr = this.insertText(inputValue, text, 0, selectionEnd);\n }\n this.updateValue(event, newValueStr, text, 'insert');\n }\n } else if (sign.isDecimalSign) {\n if (decimalCharIndex > 0 && selectionStart === decimalCharIndex) {\n this.updateValue(event, inputValue, text, 'insert');\n } else if (decimalCharIndex > selectionStart && decimalCharIndex < selectionEnd) {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, 'insert');\n } else if (decimalCharIndex === -1 && this.maxFractionDigits) {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, 'insert');\n }\n } else {\n var maxFractionDigits = this.numberFormat.resolvedOptions().maximumFractionDigits;\n var operation = selectionStart !== selectionEnd ? 'range-insert' : 'insert';\n if (decimalCharIndex > 0 && selectionStart > decimalCharIndex) {\n if (selectionStart + text.length - (decimalCharIndex + 1) <= maxFractionDigits) {\n var charIndex = currencyCharIndex >= selectionStart ? currencyCharIndex - 1 : suffixCharIndex >= selectionStart ? suffixCharIndex : inputValue.length;\n newValueStr = inputValue.slice(0, selectionStart) + text + inputValue.slice(selectionStart + text.length, charIndex) + inputValue.slice(charIndex);\n this.updateValue(event, newValueStr, text, operation);\n }\n } else {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, operation);\n }\n }\n },\n insertText: function insertText(value, text, start, end) {\n var textSplit = text === '.' ? text : text.split('.');\n if (textSplit.length === 2) {\n var decimalCharIndex = value.slice(start, end).search(this._decimal);\n this._decimal.lastIndex = 0;\n return decimalCharIndex > 0 ? value.slice(0, start) + this.formatValue(text) + value.slice(end) : this.formatValue(text) || value;\n } else if (end - start === value.length) {\n return this.formatValue(text);\n } else if (start === 0) {\n return text + value.slice(end);\n } else if (end === value.length) {\n return value.slice(0, start) + text;\n } else {\n return value.slice(0, start) + text + value.slice(end);\n }\n },\n deleteRange: function deleteRange(value, start, end) {\n var newValueStr;\n if (end - start === value.length) newValueStr = '';else if (start === 0) newValueStr = value.slice(end);else if (end === value.length) newValueStr = value.slice(0, start);else newValueStr = value.slice(0, start) + value.slice(end);\n return newValueStr;\n },\n initCursor: function initCursor() {\n var selectionStart = this.$refs.input.$el.selectionStart;\n var inputValue = this.$refs.input.$el.value;\n var valueLength = inputValue.length;\n var index = null;\n\n // remove prefix\n var prefixLength = (this.prefixChar || '').length;\n inputValue = inputValue.replace(this._prefix, '');\n selectionStart = selectionStart - prefixLength;\n var _char4 = inputValue.charAt(selectionStart);\n if (this.isNumeralChar(_char4)) {\n return selectionStart + prefixLength;\n }\n\n //left\n var i = selectionStart - 1;\n while (i >= 0) {\n _char4 = inputValue.charAt(i);\n if (this.isNumeralChar(_char4)) {\n index = i + prefixLength;\n break;\n } else {\n i--;\n }\n }\n if (index !== null) {\n this.$refs.input.$el.setSelectionRange(index + 1, index + 1);\n } else {\n i = selectionStart;\n while (i < valueLength) {\n _char4 = inputValue.charAt(i);\n if (this.isNumeralChar(_char4)) {\n index = i + prefixLength;\n break;\n } else {\n i++;\n }\n }\n if (index !== null) {\n this.$refs.input.$el.setSelectionRange(index, index);\n }\n }\n return index || 0;\n },\n onInputClick: function onInputClick() {\n var currentValue = this.$refs.input.$el.value;\n if (!this.readonly && currentValue !== getSelection()) {\n this.initCursor();\n }\n },\n isNumeralChar: function isNumeralChar(_char5) {\n if (_char5.length === 1 && (this._numeral.test(_char5) || this._decimal.test(_char5) || this._group.test(_char5) || this._minusSign.test(_char5))) {\n this.resetRegex();\n return true;\n }\n return false;\n },\n resetRegex: function resetRegex() {\n this._numeral.lastIndex = 0;\n this._decimal.lastIndex = 0;\n this._group.lastIndex = 0;\n this._minusSign.lastIndex = 0;\n },\n updateValue: function updateValue(event, valueStr, insertedValueStr, operation) {\n var currentValue = this.$refs.input.$el.value;\n var newValue = null;\n if (valueStr != null) {\n newValue = this.parseValue(valueStr);\n newValue = !newValue && !this.allowEmpty ? 0 : newValue;\n this.updateInput(newValue, insertedValueStr, operation, valueStr);\n this.handleOnInput(event, currentValue, newValue);\n }\n },\n handleOnInput: function handleOnInput(event, currentValue, newValue) {\n if (this.isValueChanged(currentValue, newValue)) {\n this.$emit('input', {\n originalEvent: event,\n value: newValue,\n formattedValue: currentValue\n });\n }\n },\n isValueChanged: function isValueChanged(currentValue, newValue) {\n if (newValue === null && currentValue !== null) {\n return true;\n }\n if (newValue != null) {\n var parsedCurrentValue = typeof currentValue === 'string' ? this.parseValue(currentValue) : currentValue;\n return newValue !== parsedCurrentValue;\n }\n return false;\n },\n validateValue: function validateValue(value) {\n if (value === '-' || value == null) {\n return null;\n }\n if (this.min != null && value < this.min) {\n return this.min;\n }\n if (this.max != null && value > this.max) {\n return this.max;\n }\n return value;\n },\n updateInput: function updateInput(value, insertedValueStr, operation, valueStr) {\n insertedValueStr = insertedValueStr || '';\n var inputValue = this.$refs.input.$el.value;\n var newValue = this.formatValue(value);\n var currentLength = inputValue.length;\n if (newValue !== valueStr) {\n newValue = this.concatValues(newValue, valueStr);\n }\n if (currentLength === 0) {\n this.$refs.input.$el.value = newValue;\n this.$refs.input.$el.setSelectionRange(0, 0);\n var index = this.initCursor();\n var selectionEnd = index + insertedValueStr.length;\n this.$refs.input.$el.setSelectionRange(selectionEnd, selectionEnd);\n } else {\n var selectionStart = this.$refs.input.$el.selectionStart;\n var _selectionEnd = this.$refs.input.$el.selectionEnd;\n this.$refs.input.$el.value = newValue;\n var newLength = newValue.length;\n if (operation === 'range-insert') {\n var startValue = this.parseValue((inputValue || '').slice(0, selectionStart));\n var startValueStr = startValue !== null ? startValue.toString() : '';\n var startExpr = startValueStr.split('').join(\"(\".concat(this.groupChar, \")?\"));\n var sRegex = new RegExp(startExpr, 'g');\n sRegex.test(newValue);\n var tExpr = insertedValueStr.split('').join(\"(\".concat(this.groupChar, \")?\"));\n var tRegex = new RegExp(tExpr, 'g');\n tRegex.test(newValue.slice(sRegex.lastIndex));\n _selectionEnd = sRegex.lastIndex + tRegex.lastIndex;\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n } else if (newLength === currentLength) {\n if (operation === 'insert' || operation === 'delete-back-single') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd + 1, _selectionEnd + 1);\n } else if (operation === 'delete-single') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd - 1, _selectionEnd - 1);\n } else if (operation === 'delete-range' || operation === 'spin') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n }\n } else if (operation === 'delete-back-single') {\n var prevChar = inputValue.charAt(_selectionEnd - 1);\n var nextChar = inputValue.charAt(_selectionEnd);\n var diff = currentLength - newLength;\n var isGroupChar = this._group.test(nextChar);\n if (isGroupChar && diff === 1) {\n _selectionEnd += 1;\n } else if (!isGroupChar && this.isNumeralChar(prevChar)) {\n _selectionEnd += -1 * diff + 1;\n }\n this._group.lastIndex = 0;\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n } else if (inputValue === '-' && operation === 'insert') {\n this.$refs.input.$el.setSelectionRange(0, 0);\n var _index = this.initCursor();\n var _selectionEnd2 = _index + insertedValueStr.length + 1;\n this.$refs.input.$el.setSelectionRange(_selectionEnd2, _selectionEnd2);\n } else {\n _selectionEnd = _selectionEnd + (newLength - currentLength);\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n }\n }\n this.$refs.input.$el.setAttribute('aria-valuenow', value);\n },\n concatValues: function concatValues(val1, val2) {\n if (val1 && val2) {\n var decimalCharIndex = val2.search(this._decimal);\n this._decimal.lastIndex = 0;\n if (this.suffixChar) {\n return decimalCharIndex !== -1 ? val1.replace(this.suffixChar, '').split(this._decimal)[0] + val2.replace(this.suffixChar, '').slice(decimalCharIndex) + this.suffixChar : val1;\n } else {\n return decimalCharIndex !== -1 ? val1.split(this._decimal)[0] + val2.slice(decimalCharIndex) : val1;\n }\n }\n return val1;\n },\n getDecimalLength: function getDecimalLength(value) {\n if (value) {\n var valueSplit = value.split(this._decimal);\n if (valueSplit.length === 2) {\n return valueSplit[1].replace(this._suffix, '').trim().replace(/\\s/g, '').replace(this._currency, '').length;\n }\n }\n return 0;\n },\n updateModel: function updateModel(event, value) {\n this.d_modelValue = value;\n this.$emit('update:modelValue', value);\n },\n onInputFocus: function onInputFocus(event) {\n this.focused = true;\n if (!this.disabled && !this.readonly && this.$refs.input.$el.value !== getSelection() && this.highlightOnFocus) {\n event.target.select();\n }\n this.$emit('focus', event);\n },\n onInputBlur: function onInputBlur(event) {\n this.focused = false;\n var input = event.target;\n var newValue = this.validateValue(this.parseValue(input.value));\n this.$emit('blur', {\n originalEvent: event,\n value: input.value\n });\n input.value = this.formatValue(newValue);\n input.setAttribute('aria-valuenow', newValue);\n this.updateModel(event, newValue);\n if (!this.disabled && !this.readonly && this.highlightOnFocus) {\n clearSelection();\n }\n },\n clearTimer: function clearTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n },\n maxBoundry: function maxBoundry() {\n return this.d_modelValue >= this.max;\n },\n minBoundry: function minBoundry() {\n return this.d_modelValue <= this.min;\n }\n },\n computed: {\n filled: function filled() {\n return this.modelValue != null && this.modelValue.toString().length > 0;\n },\n upButtonListeners: function upButtonListeners() {\n var _this2 = this;\n return {\n mousedown: function mousedown(event) {\n return _this2.onUpButtonMouseDown(event);\n },\n mouseup: function mouseup(event) {\n return _this2.onUpButtonMouseUp(event);\n },\n mouseleave: function mouseleave(event) {\n return _this2.onUpButtonMouseLeave(event);\n },\n keydown: function keydown(event) {\n return _this2.onUpButtonKeyDown(event);\n },\n keyup: function keyup(event) {\n return _this2.onUpButtonKeyUp(event);\n }\n };\n },\n downButtonListeners: function downButtonListeners() {\n var _this3 = this;\n return {\n mousedown: function mousedown(event) {\n return _this3.onDownButtonMouseDown(event);\n },\n mouseup: function mouseup(event) {\n return _this3.onDownButtonMouseUp(event);\n },\n mouseleave: function mouseleave(event) {\n return _this3.onDownButtonMouseLeave(event);\n },\n keydown: function keydown(event) {\n return _this3.onDownButtonKeyDown(event);\n },\n keyup: function keyup(event) {\n return _this3.onDownButtonKeyUp(event);\n }\n };\n },\n formattedValue: function formattedValue() {\n var val = !this.modelValue && !this.allowEmpty ? 0 : this.modelValue;\n return this.formatValue(val);\n },\n getFormatter: function getFormatter() {\n return this.numberFormat;\n }\n },\n components: {\n InputText: InputText,\n AngleUpIcon: AngleUpIcon,\n AngleDownIcon: AngleDownIcon\n }\n};\n\nvar _hoisted_1 = [\"disabled\"];\nvar _hoisted_2 = [\"disabled\"];\nvar _hoisted_3 = [\"disabled\"];\nvar _hoisted_4 = [\"disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_InputText = resolveComponent(\"InputText\");\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [createVNode(_component_InputText, {\n ref: \"input\",\n id: _ctx.inputId,\n role: \"spinbutton\",\n \"class\": normalizeClass([_ctx.cx('pcInput'), _ctx.inputClass]),\n style: normalizeStyle(_ctx.inputStyle),\n value: $options.formattedValue,\n \"aria-valuemin\": _ctx.min,\n \"aria-valuemax\": _ctx.max,\n \"aria-valuenow\": _ctx.modelValue,\n inputmode: _ctx.mode === 'decimal' && !_ctx.minFractionDigits ? 'numeric' : 'decimal',\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n placeholder: _ctx.placeholder,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n invalid: _ctx.invalid,\n variant: _ctx.variant,\n onInput: $options.onUserInput,\n onKeydown: $options.onInputKeyDown,\n onKeypress: $options.onInputKeyPress,\n onPaste: $options.onPaste,\n onClick: $options.onInputClick,\n onFocus: $options.onInputFocus,\n onBlur: $options.onInputBlur,\n pt: _ctx.ptm('pcInput'),\n unstyled: _ctx.unstyled\n }, null, 8, [\"id\", \"class\", \"style\", \"value\", \"aria-valuemin\", \"aria-valuemax\", \"aria-valuenow\", \"inputmode\", \"disabled\", \"readonly\", \"placeholder\", \"aria-labelledby\", \"aria-label\", \"invalid\", \"variant\", \"onInput\", \"onKeydown\", \"onKeypress\", \"onPaste\", \"onClick\", \"onFocus\", \"onBlur\", \"pt\", \"unstyled\"]), _ctx.showButtons && _ctx.buttonLayout === 'stacked' ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('buttonGroup')\n }, _ctx.ptm('buttonGroup')), [renderSlot(_ctx.$slots, \"incrementbutton\", {\n listeners: $options.upButtonListeners\n }, function () {\n return [createElementVNode(\"button\", mergeProps({\n \"class\": [_ctx.cx('incrementButton'), _ctx.incrementButtonClass]\n }, toHandlers($options.upButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('incrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.incrementicon ? 'incrementicon' : 'incrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.incrementIcon || _ctx.incrementButtonIcon ? 'span' : 'AngleUpIcon'), mergeProps({\n \"class\": [_ctx.incrementIcon, _ctx.incrementButtonIcon]\n }, _ctx.ptm('incrementIcon'), {\n \"data-pc-section\": \"incrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_1)];\n }), renderSlot(_ctx.$slots, \"decrementbutton\", {\n listeners: $options.downButtonListeners\n }, function () {\n return [createElementVNode(\"button\", mergeProps({\n \"class\": [_ctx.cx('decrementButton'), _ctx.decrementButtonClass]\n }, toHandlers($options.downButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('decrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.decrementicon ? 'decrementicon' : 'decrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.decrementIcon || _ctx.decrementButtonIcon ? 'span' : 'AngleDownIcon'), mergeProps({\n \"class\": [_ctx.decrementIcon, _ctx.decrementButtonIcon]\n }, _ctx.ptm('decrementIcon'), {\n \"data-pc-section\": \"decrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_2)];\n })], 16)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"incrementbutton\", {\n listeners: $options.upButtonListeners\n }, function () {\n return [_ctx.showButtons && _ctx.buttonLayout !== 'stacked' ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('incrementButton'), _ctx.incrementButtonClass]\n }, toHandlers($options.upButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('incrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.incrementicon ? 'incrementicon' : 'incrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.incrementIcon || _ctx.incrementButtonIcon ? 'span' : 'AngleUpIcon'), mergeProps({\n \"class\": [_ctx.incrementIcon, _ctx.incrementButtonIcon]\n }, _ctx.ptm('incrementIcon'), {\n \"data-pc-section\": \"incrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_3)) : createCommentVNode(\"\", true)];\n }), renderSlot(_ctx.$slots, \"decrementbutton\", {\n listeners: $options.downButtonListeners\n }, function () {\n return [_ctx.showButtons && _ctx.buttonLayout !== 'stacked' ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('decrementButton'), _ctx.decrementButtonClass]\n }, toHandlers($options.downButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('decrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.decrementicon ? 'decrementicon' : 'decrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.decrementIcon || _ctx.decrementButtonIcon ? 'span' : 'AngleDownIcon'), mergeProps({\n \"class\": [_ctx.decrementIcon, _ctx.decrementButtonIcon]\n }, _ctx.ptm('decrementIcon'), {\n \"data-pc-section\": \"decrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_4)) : createCommentVNode(\"\", true)];\n })], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ChevronDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M7.01744 10.398C6.91269 10.3985 6.8089 10.378 6.71215 10.3379C6.61541 10.2977 6.52766 10.2386 6.45405 10.1641L1.13907 4.84913C1.03306 4.69404 0.985221 4.5065 1.00399 4.31958C1.02276 4.13266 1.10693 3.95838 1.24166 3.82747C1.37639 3.69655 1.55301 3.61742 1.74039 3.60402C1.92777 3.59062 2.11386 3.64382 2.26584 3.75424L7.01744 8.47394L11.769 3.75424C11.9189 3.65709 12.097 3.61306 12.2748 3.62921C12.4527 3.64535 12.6199 3.72073 12.7498 3.84328C12.8797 3.96582 12.9647 4.12842 12.9912 4.30502C13.0177 4.48162 12.9841 4.662 12.8958 4.81724L7.58083 10.1322C7.50996 10.2125 7.42344 10.2775 7.32656 10.3232C7.22968 10.3689 7.12449 10.3944 7.01744 10.398Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'TimesIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { EventBus } from '@primeuix/utils/eventbus';\n\nvar OverlayEventBus = EventBus();\n\nexport { OverlayEventBus as default };\n//# sourceMappingURL=index.mjs.map\n","import { isClient } from '@primeuix/utils/dom';\nimport { renderSlot, openBlock, createBlock, Teleport, createCommentVNode } from 'vue';\n\nvar script = {\n name: 'Portal',\n props: {\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n disabled: {\n type: Boolean,\n \"default\": false\n }\n },\n data: function data() {\n return {\n mounted: false\n };\n },\n mounted: function mounted() {\n this.mounted = isClient();\n },\n computed: {\n inline: function inline() {\n return this.disabled || this.appendTo === 'self';\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return $options.inline ? renderSlot(_ctx.$slots, \"default\", {\n key: 0\n }) : $data.mounted ? (openBlock(), createBlock(Teleport, {\n key: 1,\n to: $props.appendTo\n }, [renderSlot(_ctx.$slots, \"default\")], 8, [\"to\"])) : createCommentVNode(\"\", true);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-select {\\n display: inline-flex;\\n cursor: pointer;\\n position: relative;\\n user-select: none;\\n background: \".concat(dt('select.background'), \";\\n border: 1px solid \").concat(dt('select.border.color'), \";\\n transition: background \").concat(dt('select.transition.duration'), \", color \").concat(dt('select.transition.duration'), \", border-color \").concat(dt('select.transition.duration'), \",\\n outline-color \").concat(dt('select.transition.duration'), \", box-shadow \").concat(dt('select.transition.duration'), \";\\n border-radius: \").concat(dt('select.border.radius'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('select.shadow'), \";\\n}\\n\\n.p-select:not(.p-disabled):hover {\\n border-color: \").concat(dt('select.hover.border.color'), \";\\n}\\n\\n.p-select:not(.p-disabled).p-focus {\\n border-color: \").concat(dt('select.focus.border.color'), \";\\n box-shadow: \").concat(dt('select.focus.ring.shadow'), \";\\n outline: \").concat(dt('select.focus.ring.width'), \" \").concat(dt('select.focus.ring.style'), \" \").concat(dt('select.focus.ring.color'), \";\\n outline-offset: \").concat(dt('select.focus.ring.offset'), \";\\n}\\n\\n.p-select.p-variant-filled {\\n background: \").concat(dt('select.filled.background'), \";\\n}\\n\\n.p-select.p-variant-filled.p-focus {\\n background: \").concat(dt('select.filled.focus.background'), \";\\n}\\n\\n.p-select.p-invalid {\\n border-color: \").concat(dt('select.invalid.border.color'), \";\\n}\\n\\n.p-select.p-disabled {\\n opacity: 1;\\n background: \").concat(dt('select.disabled.background'), \";\\n}\\n\\n.p-select-clear-icon {\\n position: absolute;\\n top: 50%;\\n margin-top: -0.5rem;\\n color: \").concat(dt('select.clear.icon.color'), \";\\n right: \").concat(dt('select.dropdown.width'), \";\\n}\\n\\n.p-select-dropdown {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex-shrink: 0;\\n background: transparent;\\n color: \").concat(dt('select.dropdown.color'), \";\\n width: \").concat(dt('select.dropdown.width'), \";\\n border-top-right-radius: \").concat(dt('select.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('select.border.radius'), \";\\n}\\n\\n.p-select-label {\\n display: block;\\n white-space: nowrap;\\n overflow: hidden;\\n flex: 1 1 auto;\\n width: 1%;\\n padding: \").concat(dt('select.padding.y'), \" \").concat(dt('select.padding.x'), \";\\n text-overflow: ellipsis;\\n cursor: pointer;\\n color: \").concat(dt('select.color'), \";\\n background: transparent;\\n border: 0 none;\\n outline: 0 none;\\n}\\n\\n.p-select-label.p-placeholder {\\n color: \").concat(dt('select.placeholder.color'), \";\\n}\\n\\n.p-select:has(.p-select-clear-icon) .p-select-label {\\n padding-right: calc(1rem + \").concat(dt('select.padding.x'), \");\\n}\\n\\n.p-select.p-disabled .p-select-label {\\n color: \").concat(dt('select.disabled.color'), \";\\n}\\n\\n.p-select-label-empty {\\n overflow: hidden;\\n opacity: 0;\\n}\\n\\ninput.p-select-label {\\n cursor: default;\\n}\\n\\n.p-select .p-select-overlay {\\n min-width: 100%;\\n}\\n\\n.p-select-overlay {\\n position: absolute;\\n top: 0;\\n left: 0;\\n background: \").concat(dt('select.overlay.background'), \";\\n color: \").concat(dt('select.overlay.color'), \";\\n border: 1px solid \").concat(dt('select.overlay.border.color'), \";\\n border-radius: \").concat(dt('select.overlay.border.radius'), \";\\n box-shadow: \").concat(dt('select.overlay.shadow'), \";\\n}\\n\\n.p-select-header {\\n padding: \").concat(dt('select.list.header.padding'), \";\\n}\\n\\n.p-select-filter {\\n width: 100%;\\n}\\n\\n.p-select-list-container {\\n overflow: auto;\\n}\\n\\n.p-select-option-group {\\n cursor: auto;\\n margin: 0;\\n padding: \").concat(dt('select.option.group.padding'), \";\\n background: \").concat(dt('select.option.group.background'), \";\\n color: \").concat(dt('select.option.group.color'), \";\\n font-weight: \").concat(dt('select.option.group.font.weight'), \";\\n}\\n\\n.p-select-list {\\n margin: 0;\\n padding: 0;\\n list-style-type: none;\\n padding: \").concat(dt('select.list.padding'), \";\\n gap: \").concat(dt('select.list.gap'), \";\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-select-option {\\n cursor: pointer;\\n font-weight: normal;\\n white-space: nowrap;\\n position: relative;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n padding: \").concat(dt('select.option.padding'), \";\\n border: 0 none;\\n color: \").concat(dt('select.option.color'), \";\\n background: transparent;\\n transition: background \").concat(dt('select.transition.duration'), \", color \").concat(dt('select.transition.duration'), \", border-color \").concat(dt('select.transition.duration'), \",\\n box-shadow \").concat(dt('select.transition.duration'), \", outline-color \").concat(dt('select.transition.duration'), \";\\n border-radius: \").concat(dt('select.option.border.radius'), \";\\n}\\n\\n.p-select-option:not(.p-select-option-selected):not(.p-disabled).p-focus {\\n background: \").concat(dt('select.option.focus.background'), \";\\n color: \").concat(dt('select.option.focus.color'), \";\\n}\\n\\n.p-select-option.p-select-option-selected {\\n background: \").concat(dt('select.option.selected.background'), \";\\n color: \").concat(dt('select.option.selected.color'), \";\\n}\\n\\n.p-select-option.p-select-option-selected.p-focus {\\n background: \").concat(dt('select.option.selected.focus.background'), \";\\n color: \").concat(dt('select.option.selected.focus.color'), \";\\n}\\n\\n.p-select-option-check-icon {\\n position: relative;\\n margin-inline-start: \").concat(dt('select.checkmark.gutter.start'), \";\\n margin-inline-end: \").concat(dt('select.checkmark.gutter.end'), \";\\n color: \").concat(dt('select.checkmark.color'), \";\\n}\\n\\n.p-select-empty-message {\\n padding: \").concat(dt('select.empty.message.padding'), \";\\n}\\n\\n.p-select-fluid {\\n display: flex;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props,\n state = _ref2.state;\n return ['p-select p-component p-inputwrapper', {\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled',\n 'p-focus': state.focused,\n 'p-inputwrapper-filled': instance.hasSelectedOption,\n 'p-inputwrapper-focus': state.focused || state.overlayVisible,\n 'p-select-open': state.overlayVisible,\n 'p-select-fluid': props.fluid\n }];\n },\n label: function label(_ref3) {\n var instance = _ref3.instance,\n props = _ref3.props;\n return ['p-select-label', {\n 'p-placeholder': !props.editable && instance.label === props.placeholder,\n 'p-select-label-empty': !props.editable && !instance.$slots['value'] && (instance.label === 'p-emptylabel' || instance.label.length === 0)\n }];\n },\n clearIcon: 'p-select-clear-icon',\n dropdown: 'p-select-dropdown',\n loadingicon: 'p-select-loading-icon',\n dropdownIcon: 'p-select-dropdown-icon',\n overlay: 'p-select-overlay p-component',\n header: 'p-select-header',\n pcFilter: 'p-select-filter',\n listContainer: 'p-select-list-container',\n list: 'p-select-list',\n optionGroup: 'p-select-option-group',\n optionGroupLabel: 'p-select-option-group-label',\n option: function option(_ref4) {\n var instance = _ref4.instance,\n props = _ref4.props,\n state = _ref4.state,\n _option = _ref4.option,\n focusedOption = _ref4.focusedOption;\n return ['p-select-option', {\n 'p-select-option-selected': instance.isSelected(_option) && props.highlightOnSelect,\n 'p-focus': state.focusedOptionIndex === focusedOption,\n 'p-disabled': instance.isOptionDisabled(_option)\n }];\n },\n optionLabel: 'p-select-option-label',\n optionCheckIcon: 'p-select-option-check-icon',\n optionBlankIcon: 'p-select-option-blank-icon',\n emptyMessage: 'p-select-empty-message'\n};\nvar SelectStyle = BaseStyle.extend({\n name: 'select',\n theme: theme,\n classes: classes\n});\n\nexport { SelectStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { FilterService } from '@primevue/core/api';\nimport { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { focus, isAndroid, getFirstFocusableElement, getLastFocusableElement, addStyle, relativePosition, getOuterWidth, absolutePosition, isTouchDevice, isVisible, getFocusableElements, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isPrintableCharacter, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport BlankIcon from '@primevue/icons/blank';\nimport CheckIcon from '@primevue/icons/check';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport SearchIcon from '@primevue/icons/search';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport TimesIcon from '@primevue/icons/times';\nimport IconField from 'primevue/iconfield';\nimport InputIcon from 'primevue/inputicon';\nimport InputText from 'primevue/inputtext';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SelectStyle from 'primevue/select/style';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, renderSlot, createTextVNode, toDisplayString, normalizeClass, createBlock, resolveDynamicComponent, createCommentVNode, createElementVNode, createVNode, withCtx, Transition, normalizeProps, createSlots, Fragment, renderList, withDirectives } from 'vue';\n\nvar script$1 = {\n name: 'BaseSelect',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n options: Array,\n optionLabel: [String, Function],\n optionValue: [String, Function],\n optionDisabled: [String, Function],\n optionGroupLabel: [String, Function],\n optionGroupChildren: [String, Function],\n scrollHeight: {\n type: String,\n \"default\": '14rem'\n },\n filter: Boolean,\n filterPlaceholder: String,\n filterLocale: String,\n filterMatchMode: {\n type: String,\n \"default\": 'contains'\n },\n filterFields: {\n type: Array,\n \"default\": null\n },\n editable: Boolean,\n placeholder: {\n type: String,\n \"default\": null\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n dataKey: null,\n showClear: {\n type: Boolean,\n \"default\": false\n },\n fluid: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n labelId: {\n type: String,\n \"default\": null\n },\n labelClass: {\n type: [String, Object],\n \"default\": null\n },\n labelStyle: {\n type: Object,\n \"default\": null\n },\n panelClass: {\n type: [String, Object],\n \"default\": null\n },\n overlayStyle: {\n type: Object,\n \"default\": null\n },\n overlayClass: {\n type: [String, Object],\n \"default\": null\n },\n panelStyle: {\n type: Object,\n \"default\": null\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n clearIcon: {\n type: String,\n \"default\": undefined\n },\n dropdownIcon: {\n type: String,\n \"default\": undefined\n },\n filterIcon: {\n type: String,\n \"default\": undefined\n },\n loadingIcon: {\n type: String,\n \"default\": undefined\n },\n resetFilterOnHide: {\n type: Boolean,\n \"default\": false\n },\n resetFilterOnClear: {\n type: Boolean,\n \"default\": false\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n autoOptionFocus: {\n type: Boolean,\n \"default\": false\n },\n autoFilterFocus: {\n type: Boolean,\n \"default\": false\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n focusOnHover: {\n type: Boolean,\n \"default\": true\n },\n highlightOnSelect: {\n type: Boolean,\n \"default\": true\n },\n checkmark: {\n type: Boolean,\n \"default\": false\n },\n filterMessage: {\n type: String,\n \"default\": null\n },\n selectionMessage: {\n type: String,\n \"default\": null\n },\n emptySelectionMessage: {\n type: String,\n \"default\": null\n },\n emptyFilterMessage: {\n type: String,\n \"default\": null\n },\n emptyMessage: {\n type: String,\n \"default\": null\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n ariaLabel: {\n type: String,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: SelectStyle,\n provide: function provide() {\n return {\n $pcSelect: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script = {\n name: 'Select',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'before-show', 'before-hide', 'show', 'hide', 'filter'],\n outsideClickListener: null,\n scrollHandler: null,\n resizeListener: null,\n labelClickListener: null,\n overlay: null,\n list: null,\n virtualScroller: null,\n searchTimeout: null,\n searchValue: null,\n isModelValueChanged: false,\n data: function data() {\n return {\n id: this.$attrs.id,\n clicked: false,\n focused: false,\n focusedOptionIndex: -1,\n filterValue: null,\n overlayVisible: false\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n modelValue: function modelValue() {\n this.isModelValueChanged = true;\n },\n options: function options() {\n this.autoUpdateModel();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n this.autoUpdateModel();\n this.bindLabelClickListener();\n },\n updated: function updated() {\n if (this.overlayVisible && this.isModelValueChanged) {\n this.scrollInView(this.findSelectedOptionIndex());\n }\n this.isModelValueChanged = false;\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindOutsideClickListener();\n this.unbindResizeListener();\n this.unbindLabelClickListener();\n if (this.scrollHandler) {\n this.scrollHandler.destroy();\n this.scrollHandler = null;\n }\n if (this.overlay) {\n ZIndex.clear(this.overlay);\n this.overlay = null;\n }\n },\n methods: {\n getOptionIndex: function getOptionIndex(index, fn) {\n return this.virtualScrollerDisabled ? index : fn && fn(index)['index'];\n },\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return this.optionValue ? resolveFieldData(option, this.optionValue) : option;\n },\n getOptionRenderKey: function getOptionRenderKey(option, index) {\n return (this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option)) + '_' + index;\n },\n getPTItemOptions: function getPTItemOptions(option, itemOptions, index, key) {\n return this.ptm(key, {\n context: {\n option: option,\n index: index,\n selected: this.isSelected(option),\n focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),\n disabled: this.isOptionDisabled(option)\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n isOptionGroup: function isOptionGroup(option) {\n return this.optionGroupLabel && option.optionGroup && option.group;\n },\n getOptionGroupLabel: function getOptionGroupLabel(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupLabel);\n },\n getOptionGroupChildren: function getOptionGroupChildren(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupChildren);\n },\n getAriaPosInset: function getAriaPosInset(index) {\n var _this = this;\n return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function (option) {\n return _this.isOptionGroup(option);\n }).length : index) + 1;\n },\n show: function show(isFocus) {\n this.$emit('before-show');\n this.overlayVisible = true;\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : this.editable ? -1 : this.findSelectedOptionIndex();\n isFocus && focus(this.$refs.focusInput);\n },\n hide: function hide(isFocus) {\n var _this2 = this;\n var _hide = function _hide() {\n _this2.$emit('before-hide');\n _this2.overlayVisible = false;\n _this2.clicked = false;\n _this2.focusedOptionIndex = -1;\n _this2.searchValue = '';\n _this2.resetFilterOnHide && (_this2.filterValue = null);\n isFocus && focus(_this2.$refs.focusInput);\n };\n setTimeout(function () {\n _hide();\n }, 0); // For ScreenReaders\n },\n onFocus: function onFocus(event) {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n this.focused = true;\n if (this.overlayVisible) {\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : this.editable ? -1 : this.findSelectedOptionIndex();\n this.scrollInView(this.focusedOptionIndex);\n }\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.focused = false;\n this.focusedOptionIndex = -1;\n this.searchValue = '';\n this.$emit('blur', event);\n },\n onKeyDown: function onKeyDown(event) {\n if (this.disabled || isAndroid()) {\n event.preventDefault();\n return;\n }\n var metaKey = event.metaKey || event.ctrlKey;\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event, this.editable);\n break;\n case 'ArrowLeft':\n case 'ArrowRight':\n this.onArrowLeftKey(event, this.editable);\n break;\n case 'Home':\n this.onHomeKey(event, this.editable);\n break;\n case 'End':\n this.onEndKey(event, this.editable);\n break;\n case 'PageDown':\n this.onPageDownKey(event);\n break;\n case 'PageUp':\n this.onPageUpKey(event);\n break;\n case 'Space':\n this.onSpaceKey(event, this.editable);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event);\n break;\n case 'Backspace':\n this.onBackspaceKey(event, this.editable);\n break;\n case 'ShiftLeft':\n case 'ShiftRight':\n //NOOP\n break;\n default:\n if (!metaKey && isPrintableCharacter(event.key)) {\n !this.overlayVisible && this.show();\n !this.editable && this.searchOptions(event, event.key);\n }\n break;\n }\n this.clicked = false;\n },\n onEditableInput: function onEditableInput(event) {\n var value = event.target.value;\n this.searchValue = '';\n var matched = this.searchOptions(event, value);\n !matched && (this.focusedOptionIndex = -1);\n this.updateModel(event, value);\n !this.overlayVisible && isNotEmpty(value) && this.show();\n },\n onContainerClick: function onContainerClick(event) {\n if (this.disabled || this.loading) {\n return;\n }\n if (event.target.tagName === 'INPUT' || event.target.getAttribute('data-pc-section') === 'clearicon' || event.target.closest('[data-pc-section=\"clearicon\"]')) {\n return;\n } else if (!this.overlay || !this.overlay.contains(event.target)) {\n this.overlayVisible ? this.hide(true) : this.show(true);\n }\n this.clicked = true;\n },\n onClearClick: function onClearClick(event) {\n this.updateModel(event, null);\n this.resetFilterOnClear && (this.filterValue = null);\n },\n onFirstHiddenFocus: function onFirstHiddenFocus(event) {\n var focusableEl = event.relatedTarget === this.$refs.focusInput ? getFirstFocusableElement(this.overlay, ':not([data-p-hidden-focusable=\"true\"])') : this.$refs.focusInput;\n focus(focusableEl);\n },\n onLastHiddenFocus: function onLastHiddenFocus(event) {\n var focusableEl = event.relatedTarget === this.$refs.focusInput ? getLastFocusableElement(this.overlay, ':not([data-p-hidden-focusable=\"true\"])') : this.$refs.focusInput;\n focus(focusableEl);\n },\n onOptionSelect: function onOptionSelect(event, option) {\n var isHide = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var value = this.getOptionValue(option);\n this.updateModel(event, value);\n isHide && this.hide(true);\n },\n onOptionMouseMove: function onOptionMouseMove(event, index) {\n if (this.focusOnHover) {\n this.changeFocusedOptionIndex(event, index);\n }\n },\n onFilterChange: function onFilterChange(event) {\n var value = event.target.value;\n this.filterValue = value;\n this.focusedOptionIndex = -1;\n this.$emit('filter', {\n originalEvent: event,\n value: value\n });\n !this.virtualScrollerDisabled && this.virtualScroller.scrollToIndex(0);\n },\n onFilterKeyDown: function onFilterKeyDown(event) {\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event, true);\n break;\n case 'ArrowLeft':\n case 'ArrowRight':\n this.onArrowLeftKey(event, true);\n break;\n case 'Home':\n this.onHomeKey(event, true);\n break;\n case 'End':\n this.onEndKey(event, true);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event, true);\n break;\n }\n },\n onFilterBlur: function onFilterBlur() {\n this.focusedOptionIndex = -1;\n },\n onFilterUpdated: function onFilterUpdated() {\n if (this.overlayVisible) {\n this.alignOverlay();\n }\n },\n onOverlayClick: function onOverlayClick(event) {\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.$el\n });\n },\n onOverlayKeyDown: function onOverlayKeyDown(event) {\n switch (event.code) {\n case 'Escape':\n this.onEscapeKey(event);\n break;\n }\n },\n onArrowDownKey: function onArrowDownKey(event) {\n if (!this.overlayVisible) {\n this.show();\n this.editable && this.changeFocusedOptionIndex(event, this.findSelectedOptionIndex());\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findFirstOptionIndex() : this.findFirstFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (event.altKey && !pressedInInputText) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n event.preventDefault();\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findLastOptionIndex() : this.findLastFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n !this.overlayVisible && this.show();\n event.preventDefault();\n }\n },\n onArrowLeftKey: function onArrowLeftKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n pressedInInputText && (this.focusedOptionIndex = -1);\n },\n onHomeKey: function onHomeKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(0, event.target.selectionStart);\n } else {\n target.setSelectionRange(0, 0);\n this.focusedOptionIndex = -1;\n }\n } else {\n this.changeFocusedOptionIndex(event, this.findFirstOptionIndex());\n !this.overlayVisible && this.show();\n }\n event.preventDefault();\n },\n onEndKey: function onEndKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(event.target.selectionStart, target.value.length);\n } else {\n var len = target.value.length;\n target.setSelectionRange(len, len);\n this.focusedOptionIndex = -1;\n }\n } else {\n this.changeFocusedOptionIndex(event, this.findLastOptionIndex());\n !this.overlayVisible && this.show();\n }\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView(0);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView(this.visibleOptions.length - 1);\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event) {\n if (!this.overlayVisible) {\n this.focusedOptionIndex = -1; // reset\n this.onArrowDownKey(event);\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.hide();\n }\n event.preventDefault();\n },\n onSpaceKey: function onSpaceKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n !pressedInInputText && this.onEnterKey(event);\n },\n onEscapeKey: function onEscapeKey(event) {\n this.overlayVisible && this.hide(true);\n event.preventDefault();\n event.stopPropagation(); //@todo will be changed next versionss\n },\n onTabKey: function onTabKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (!pressedInInputText) {\n if (this.overlayVisible && this.hasFocusableElements()) {\n focus(this.$refs.firstHiddenFocusableElementOnOverlay);\n event.preventDefault();\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide(this.filter);\n }\n }\n },\n onBackspaceKey: function onBackspaceKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n !this.overlayVisible && this.show();\n }\n },\n onOverlayEnter: function onOverlayEnter(el) {\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n addStyle(el, {\n position: 'absolute',\n top: '0',\n left: '0'\n });\n this.alignOverlay();\n this.scrollInView();\n this.autoFilterFocus && focus(this.$refs.filterInput.$el);\n },\n onOverlayAfterEnter: function onOverlayAfterEnter() {\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n this.$emit('show');\n },\n onOverlayLeave: function onOverlayLeave() {\n this.unbindOutsideClickListener();\n this.unbindScrollListener();\n this.unbindResizeListener();\n this.$emit('hide');\n this.overlay = null;\n },\n onOverlayAfterLeave: function onOverlayAfterLeave(el) {\n ZIndex.clear(el);\n },\n alignOverlay: function alignOverlay() {\n if (this.appendTo === 'self') {\n relativePosition(this.overlay, this.$el);\n } else {\n this.overlay.style.minWidth = getOuterWidth(this.$el) + 'px';\n absolutePosition(this.overlay, this.$el);\n }\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this3 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this3.overlayVisible && _this3.overlay && !_this3.$el.contains(event.target) && !_this3.overlay.contains(event.target)) {\n _this3.hide();\n }\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this4 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.container, function () {\n if (_this4.overlayVisible) {\n _this4.hide();\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this5 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this5.overlayVisible && !isTouchDevice()) {\n _this5.hide();\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n },\n bindLabelClickListener: function bindLabelClickListener() {\n var _this6 = this;\n if (!this.editable && !this.labelClickListener) {\n var label = document.querySelector(\"label[for=\\\"\".concat(this.inputId, \"\\\"]\"));\n if (label && isVisible(label)) {\n this.labelClickListener = function () {\n focus(_this6.$refs.focusInput);\n };\n label.addEventListener('click', this.labelClickListener);\n }\n }\n },\n unbindLabelClickListener: function unbindLabelClickListener() {\n if (this.labelClickListener) {\n var label = document.querySelector(\"label[for=\\\"\".concat(this.inputId, \"\\\"]\"));\n if (label && isVisible(label)) {\n label.removeEventListener('click', this.labelClickListener);\n }\n }\n },\n hasFocusableElements: function hasFocusableElements() {\n return getFocusableElements(this.overlay, ':not([data-p-hidden-focusable=\"true\"])').length > 0;\n },\n isOptionMatched: function isOptionMatched(option) {\n var _this$getOptionLabel;\n return this.isValidOption(option) && typeof this.getOptionLabel(option) === 'string' && ((_this$getOptionLabel = this.getOptionLabel(option)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.filterLocale).startsWith(this.searchValue.toLocaleLowerCase(this.filterLocale)));\n },\n isValidOption: function isValidOption(option) {\n return isNotEmpty(option) && !(this.isOptionDisabled(option) || this.isOptionGroup(option));\n },\n isValidSelectedOption: function isValidSelectedOption(option) {\n return this.isValidOption(option) && this.isSelected(option);\n },\n isSelected: function isSelected(option) {\n return this.isValidOption(option) && equals(this.modelValue, this.getOptionValue(option), this.equalityKey);\n },\n findFirstOptionIndex: function findFirstOptionIndex() {\n var _this7 = this;\n return this.visibleOptions.findIndex(function (option) {\n return _this7.isValidOption(option);\n });\n },\n findLastOptionIndex: function findLastOptionIndex() {\n var _this8 = this;\n return findLastIndex(this.visibleOptions, function (option) {\n return _this8.isValidOption(option);\n });\n },\n findNextOptionIndex: function findNextOptionIndex(index) {\n var _this9 = this;\n var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this9.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;\n },\n findPrevOptionIndex: function findPrevOptionIndex(index) {\n var _this10 = this;\n var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this10.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findSelectedOptionIndex: function findSelectedOptionIndex() {\n var _this11 = this;\n return this.hasSelectedOption ? this.visibleOptions.findIndex(function (option) {\n return _this11.isValidSelectedOption(option);\n }) : -1;\n },\n findFirstFocusedOptionIndex: function findFirstFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;\n },\n findLastFocusedOptionIndex: function findLastFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;\n },\n searchOptions: function searchOptions(event, _char) {\n var _this12 = this;\n this.searchValue = (this.searchValue || '') + _char;\n var optionIndex = -1;\n var matched = false;\n if (isNotEmpty(this.searchValue)) {\n if (this.focusedOptionIndex !== -1) {\n optionIndex = this.visibleOptions.slice(this.focusedOptionIndex).findIndex(function (option) {\n return _this12.isOptionMatched(option);\n });\n optionIndex = optionIndex === -1 ? this.visibleOptions.slice(0, this.focusedOptionIndex).findIndex(function (option) {\n return _this12.isOptionMatched(option);\n }) : optionIndex + this.focusedOptionIndex;\n } else {\n optionIndex = this.visibleOptions.findIndex(function (option) {\n return _this12.isOptionMatched(option);\n });\n }\n if (optionIndex !== -1) {\n matched = true;\n }\n if (optionIndex === -1 && this.focusedOptionIndex === -1) {\n optionIndex = this.findFirstFocusedOptionIndex();\n }\n if (optionIndex !== -1) {\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n }\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(function () {\n _this12.searchValue = '';\n _this12.searchTimeout = null;\n }, 500);\n return matched;\n },\n changeFocusedOptionIndex: function changeFocusedOptionIndex(event, index) {\n if (this.focusedOptionIndex !== index) {\n this.focusedOptionIndex = index;\n this.scrollInView();\n if (this.selectOnFocus) {\n this.onOptionSelect(event, this.visibleOptions[index], false);\n }\n }\n },\n scrollInView: function scrollInView() {\n var _this13 = this;\n var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n this.$nextTick(function () {\n var id = index !== -1 ? \"\".concat(_this13.id, \"_\").concat(index) : _this13.focusedOptionId;\n var element = findSingle(_this13.list, \"li[id=\\\"\".concat(id, \"\\\"]\"));\n if (element) {\n element.scrollIntoView && element.scrollIntoView({\n block: 'nearest',\n inline: 'start'\n });\n } else if (!_this13.virtualScrollerDisabled) {\n _this13.virtualScroller && _this13.virtualScroller.scrollToIndex(index !== -1 ? index : _this13.focusedOptionIndex);\n }\n });\n },\n autoUpdateModel: function autoUpdateModel() {\n if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption) {\n this.focusedOptionIndex = this.findFirstFocusedOptionIndex();\n this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex], false);\n }\n },\n updateModel: function updateModel(event, value) {\n this.$emit('update:modelValue', value);\n this.$emit('change', {\n originalEvent: event,\n value: value\n });\n },\n flatOptions: function flatOptions(options) {\n var _this14 = this;\n return (options || []).reduce(function (result, option, index) {\n result.push({\n optionGroup: option,\n group: true,\n index: index\n });\n var optionGroupChildren = _this14.getOptionGroupChildren(option);\n optionGroupChildren && optionGroupChildren.forEach(function (o) {\n return result.push(o);\n });\n return result;\n }, []);\n },\n overlayRef: function overlayRef(el) {\n this.overlay = el;\n },\n listRef: function listRef(el, contentRef) {\n this.list = el;\n contentRef && contentRef(el); // For VirtualScroller\n },\n virtualScrollerRef: function virtualScrollerRef(el) {\n this.virtualScroller = el;\n }\n },\n computed: {\n visibleOptions: function visibleOptions() {\n var _this15 = this;\n var options = this.optionGroupLabel ? this.flatOptions(this.options) : this.options || [];\n if (this.filterValue) {\n var filteredOptions = FilterService.filter(options, this.searchFields, this.filterValue, this.filterMatchMode, this.filterLocale);\n if (this.optionGroupLabel) {\n var optionGroups = this.options || [];\n var filtered = [];\n optionGroups.forEach(function (group) {\n var groupChildren = _this15.getOptionGroupChildren(group);\n var filteredItems = groupChildren.filter(function (item) {\n return filteredOptions.includes(item);\n });\n if (filteredItems.length > 0) filtered.push(_objectSpread(_objectSpread({}, group), {}, _defineProperty({}, typeof _this15.optionGroupChildren === 'string' ? _this15.optionGroupChildren : 'items', _toConsumableArray(filteredItems))));\n });\n return this.flatOptions(filtered);\n }\n return filteredOptions;\n }\n return options;\n },\n hasSelectedOption: function hasSelectedOption() {\n return isNotEmpty(this.modelValue);\n },\n label: function label() {\n var selectedOptionIndex = this.findSelectedOptionIndex();\n return selectedOptionIndex !== -1 ? this.getOptionLabel(this.visibleOptions[selectedOptionIndex]) : this.placeholder || 'p-emptylabel';\n },\n editableInputValue: function editableInputValue() {\n var selectedOptionIndex = this.findSelectedOptionIndex();\n return selectedOptionIndex !== -1 ? this.getOptionLabel(this.visibleOptions[selectedOptionIndex]) : this.modelValue || '';\n },\n equalityKey: function equalityKey() {\n return this.optionValue ? null : this.dataKey;\n },\n searchFields: function searchFields() {\n return this.filterFields || [this.optionLabel];\n },\n filterResultMessageText: function filterResultMessageText() {\n return isNotEmpty(this.visibleOptions) ? this.filterMessageText.replaceAll('{0}', this.visibleOptions.length) : this.emptyFilterMessageText;\n },\n filterMessageText: function filterMessageText() {\n return this.filterMessage || this.$primevue.config.locale.searchMessage || '';\n },\n emptyFilterMessageText: function emptyFilterMessageText() {\n return this.emptyFilterMessage || this.$primevue.config.locale.emptySearchMessage || this.$primevue.config.locale.emptyFilterMessage || '';\n },\n emptyMessageText: function emptyMessageText() {\n return this.emptyMessage || this.$primevue.config.locale.emptyMessage || '';\n },\n selectionMessageText: function selectionMessageText() {\n return this.selectionMessage || this.$primevue.config.locale.selectionMessage || '';\n },\n emptySelectionMessageText: function emptySelectionMessageText() {\n return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || '';\n },\n selectedMessageText: function selectedMessageText() {\n return this.hasSelectedOption ? this.selectionMessageText.replaceAll('{0}', '1') : this.emptySelectionMessageText;\n },\n focusedOptionId: function focusedOptionId() {\n return this.focusedOptionIndex !== -1 ? \"\".concat(this.id, \"_\").concat(this.focusedOptionIndex) : null;\n },\n ariaSetSize: function ariaSetSize() {\n var _this16 = this;\n return this.visibleOptions.filter(function (option) {\n return !_this16.isOptionGroup(option);\n }).length;\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n InputText: InputText,\n VirtualScroller: VirtualScroller,\n Portal: Portal,\n InputIcon: InputIcon,\n IconField: IconField,\n TimesIcon: TimesIcon,\n ChevronDownIcon: ChevronDownIcon,\n SpinnerIcon: SpinnerIcon,\n SearchIcon: SearchIcon,\n CheckIcon: CheckIcon,\n BlankIcon: BlankIcon\n }\n};\n\nvar _hoisted_1 = [\"id\"];\nvar _hoisted_2 = [\"id\", \"value\", \"placeholder\", \"tabindex\", \"disabled\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-invalid\"];\nvar _hoisted_3 = [\"id\", \"tabindex\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-disabled\"];\nvar _hoisted_4 = [\"id\"];\nvar _hoisted_5 = [\"id\"];\nvar _hoisted_6 = [\"id\", \"aria-label\", \"aria-selected\", \"aria-disabled\", \"aria-setsize\", \"aria-posinset\", \"onClick\", \"onMousemove\", \"data-p-selected\", \"data-p-focused\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_SearchIcon = resolveComponent(\"SearchIcon\");\n var _component_InputIcon = resolveComponent(\"InputIcon\");\n var _component_IconField = resolveComponent(\"IconField\");\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_BlankIcon = resolveComponent(\"BlankIcon\");\n var _component_VirtualScroller = resolveComponent(\"VirtualScroller\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n id: $data.id,\n \"class\": _ctx.cx('root'),\n onClick: _cache[11] || (_cache[11] = function () {\n return $options.onContainerClick && $options.onContainerClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [_ctx.editable ? (openBlock(), createElementBlock(\"input\", mergeProps({\n key: 0,\n ref: \"focusInput\",\n id: _ctx.labelId || _ctx.inputId,\n type: \"text\",\n \"class\": [_ctx.cx('label'), _ctx.inputClass, _ctx.labelClass],\n style: [_ctx.inputStyle, _ctx.labelStyle],\n value: $options.editableInputValue,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[2] || (_cache[2] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n onInput: _cache[3] || (_cache[3] = function () {\n return $options.onEditableInput && $options.onEditableInput.apply($options, arguments);\n })\n }, _ctx.ptm('label')), null, 16, _hoisted_2)) : (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n ref: \"focusInput\",\n id: _ctx.labelId || _ctx.inputId,\n \"class\": [_ctx.cx('label'), _ctx.inputClass, _ctx.labelClass],\n style: [_ctx.inputStyle, _ctx.labelStyle],\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel || ($options.label === 'p-emptylabel' ? undefined : $options.label),\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-disabled\": _ctx.disabled,\n onFocus: _cache[4] || (_cache[4] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[5] || (_cache[5] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[6] || (_cache[6] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('label')), [renderSlot(_ctx.$slots, \"value\", {\n value: _ctx.modelValue,\n placeholder: _ctx.placeholder\n }, function () {\n return [createTextVNode(toDisplayString($options.label === 'p-emptylabel' ? ' ' : $options.label || 'empty'), 1)];\n })], 16, _hoisted_3)), _ctx.showClear && _ctx.modelValue != null ? renderSlot(_ctx.$slots, \"clearicon\", {\n key: 2,\n \"class\": normalizeClass(_ctx.cx('clearIcon')),\n clearCallback: $options.onClearClick\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.clearIcon ? 'i' : 'TimesIcon'), mergeProps({\n ref: \"clearIcon\",\n \"class\": [_ctx.cx('clearIcon'), _ctx.clearIcon],\n onClick: $options.onClearClick\n }, _ctx.ptm('clearIcon'), {\n \"data-pc-section\": \"clearicon\"\n }), null, 16, [\"class\", \"onClick\"]))];\n }) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('dropdown')\n }, _ctx.ptm('dropdown')), [_ctx.loading ? renderSlot(_ctx.$slots, \"loadingicon\", {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('loadingIcon'))\n }, function () {\n return [_ctx.loadingIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('loadingIcon'), 'pi-spin', _ctx.loadingIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loadingIcon')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('loadingIcon'),\n spin: \"\",\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loadingIcon')), null, 16, [\"class\"]))];\n }) : renderSlot(_ctx.$slots, \"dropdownicon\", {\n key: 1,\n \"class\": normalizeClass(_ctx.cx('dropdownIcon'))\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.dropdownIcon ? 'span' : 'ChevronDownIcon'), mergeProps({\n \"class\": [_ctx.cx('dropdownIcon'), _ctx.dropdownIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('dropdownIcon')), null, 16, [\"class\"]))];\n })], 16), createVNode(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-connected-overlay\",\n onEnter: $options.onOverlayEnter,\n onAfterEnter: $options.onOverlayAfterEnter,\n onLeave: $options.onOverlayLeave,\n onAfterLeave: $options.onOverlayAfterLeave\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [$data.overlayVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.overlayRef,\n \"class\": [_ctx.cx('overlay'), _ctx.panelClass, _ctx.overlayClass],\n style: [_ctx.panelStyle, _ctx.overlayStyle],\n onClick: _cache[9] || (_cache[9] = function () {\n return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);\n }),\n onKeydown: _cache[10] || (_cache[10] = function () {\n return $options.onOverlayKeyDown && $options.onOverlayKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('overlay')), [createElementVNode(\"span\", mergeProps({\n ref: \"firstHiddenFocusableElementOnOverlay\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: 0,\n onFocus: _cache[7] || (_cache[7] = function () {\n return $options.onFirstHiddenFocus && $options.onFirstHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenFirstFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16), renderSlot(_ctx.$slots, \"header\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n }), _ctx.filter ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [createVNode(_component_IconField, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterContainer')), {\n \"default\": withCtx(function () {\n return [createVNode(_component_InputText, {\n ref: \"filterInput\",\n type: \"text\",\n value: $data.filterValue,\n onVnodeMounted: $options.onFilterUpdated,\n onVnodeUpdated: $options.onFilterUpdated,\n \"class\": normalizeClass(_ctx.cx('pcFilter')),\n placeholder: _ctx.filterPlaceholder,\n variant: _ctx.variant,\n unstyled: _ctx.unstyled,\n role: \"searchbox\",\n autocomplete: \"off\",\n \"aria-owns\": $data.id + '_list',\n \"aria-activedescendant\": $options.focusedOptionId,\n onKeydown: $options.onFilterKeyDown,\n onBlur: $options.onFilterBlur,\n onInput: $options.onFilterChange,\n pt: _ctx.ptm('pcFilter')\n }, null, 8, [\"value\", \"onVnodeMounted\", \"onVnodeUpdated\", \"class\", \"placeholder\", \"variant\", \"unstyled\", \"aria-owns\", \"aria-activedescendant\", \"onKeydown\", \"onBlur\", \"onInput\", \"pt\"]), createVNode(_component_InputIcon, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterIconContainer')), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"filtericon\", {}, function () {\n return [_ctx.filterIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.filterIcon\n }, _ctx.ptm('filterIcon')), null, 16)) : (openBlock(), createBlock(_component_SearchIcon, normalizeProps(mergeProps({\n key: 1\n }, _ctx.ptm('filterIcon'))), null, 16))];\n })];\n }),\n _: 3\n }, 16, [\"unstyled\"])];\n }),\n _: 3\n }, 16, [\"unstyled\"]), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenFilterResult'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.filterResultMessageText), 17)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('listContainer'),\n style: {\n 'max-height': $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }\n }, _ctx.ptm('listContainer')), [createVNode(_component_VirtualScroller, mergeProps({\n ref: $options.virtualScrollerRef\n }, _ctx.virtualScrollerOptions, {\n items: $options.visibleOptions,\n style: {\n height: _ctx.scrollHeight\n },\n tabindex: -1,\n disabled: $options.virtualScrollerDisabled,\n pt: _ctx.ptm('virtualScroller')\n }), createSlots({\n content: withCtx(function (_ref) {\n var styleClass = _ref.styleClass,\n contentRef = _ref.contentRef,\n items = _ref.items,\n getItemOptions = _ref.getItemOptions,\n contentStyle = _ref.contentStyle,\n itemSize = _ref.itemSize;\n return [createElementVNode(\"ul\", mergeProps({\n ref: function ref(el) {\n return $options.listRef(el, contentRef);\n },\n id: $data.id + '_list',\n \"class\": [_ctx.cx('list'), styleClass],\n style: contentStyle,\n role: \"listbox\"\n }, _ctx.ptm('list')), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function (option, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getOptionRenderKey(option, $options.getOptionIndex(i, getItemOptions))\n }, [$options.isOptionGroup(option) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('optionGroup'),\n role: \"option\",\n ref_for: true\n }, _ctx.ptm('optionGroup')), [renderSlot(_ctx.$slots, \"optiongroup\", {\n option: option.optionGroup,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('optionGroupLabel'),\n ref_for: true\n }, _ctx.ptm('optionGroupLabel')), toDisplayString($options.getOptionGroupLabel(option.optionGroup)), 17)];\n })], 16, _hoisted_5)) : withDirectives((openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n \"class\": _ctx.cx('option', {\n option: option,\n focusedOption: $options.getOptionIndex(i, getItemOptions)\n }),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": $options.isSelected(option),\n \"aria-disabled\": $options.isOptionDisabled(option),\n \"aria-setsize\": $options.ariaSetSize,\n \"aria-posinset\": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),\n onClick: function onClick($event) {\n return $options.onOptionSelect($event, option);\n },\n onMousemove: function onMousemove($event) {\n return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));\n },\n \"data-p-selected\": $options.isSelected(option),\n \"data-p-focused\": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),\n \"data-p-disabled\": $options.isOptionDisabled(option),\n ref_for: true\n }, $options.getPTItemOptions(option, getItemOptions, i, 'option')), [_ctx.checkmark ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [$options.isSelected(option) ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 0,\n \"class\": _ctx.cx('optionCheckIcon'),\n ref_for: true\n }, _ctx.ptm('optionCheckIcon')), null, 16, [\"class\"])) : (openBlock(), createBlock(_component_BlankIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('optionBlankIcon'),\n ref_for: true\n }, _ctx.ptm('optionBlankIcon')), null, 16, [\"class\"]))], 64)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"option\", {\n option: option,\n selected: $options.isSelected(option),\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('optionLabel'),\n ref_for: true\n }, _ctx.ptm('optionLabel')), toDisplayString($options.getOptionLabel(option)), 17)];\n })], 16, _hoisted_6)), [[_directive_ripple]])], 64);\n }), 128)), $data.filterValue && (!items || items && items.length === 0) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), [renderSlot(_ctx.$slots, \"emptyfilter\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyFilterMessageText), 1)];\n })], 16)) : !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), [renderSlot(_ctx.$slots, \"empty\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyMessageText), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_4)];\n }),\n _: 2\n }, [_ctx.$slots.loader ? {\n name: \"loader\",\n fn: withCtx(function (_ref2) {\n var options = _ref2.options;\n return [renderSlot(_ctx.$slots, \"loader\", {\n options: options\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"items\", \"style\", \"disabled\", \"pt\"])], 16), renderSlot(_ctx.$slots, \"footer\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n }), !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenEmptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.emptyMessageText), 17)) : createCommentVNode(\"\", true), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSelectedMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.selectedMessageText), 17), createElementVNode(\"span\", mergeProps({\n ref: \"lastHiddenFocusableElementOnOverlay\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: 0,\n onFocus: _cache[8] || (_cache[8] = function () {\n return $options.onLastHiddenFocus && $options.onLastHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenLastFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16)], 16)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 3\n }, 8, [\"appendTo\"])], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-toggleswitch {\\n display: inline-block;\\n width: \".concat(dt('toggleswitch.width'), \";\\n height: \").concat(dt('toggleswitch.height'), \";\\n}\\n\\n.p-toggleswitch-input {\\n cursor: pointer;\\n appearance: none;\\n position: absolute;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n padding: 0;\\n margin: 0;\\n opacity: 0;\\n z-index: 1;\\n outline: 0 none;\\n border-radius: \").concat(dt('toggleswitch.border.radius'), \";\\n}\\n\\n.p-toggleswitch-slider {\\n display: inline-block;\\n cursor: pointer;\\n width: 100%;\\n height: 100%;\\n border-width: \").concat(dt('toggleswitch.border.width'), \";\\n border-style: solid;\\n border-color: \").concat(dt('toggleswitch.border.color'), \";\\n background: \").concat(dt('toggleswitch.background'), \";\\n transition: background \").concat(dt('toggleswitch.transition.duration'), \", color \").concat(dt('toggleswitch.transition.duration'), \", border-color \").concat(dt('toggleswitch.transition.duration'), \", outline-color \").concat(dt('toggleswitch.transition.duration'), \", box-shadow \").concat(dt('toggleswitch.transition.duration'), \";\\n border-radius: \").concat(dt('toggleswitch.border.radius'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('toggleswitch.shadow'), \";\\n}\\n\\n.p-toggleswitch-slider:before {\\n position: absolute;\\n content: \\\"\\\";\\n top: 50%;\\n background: \").concat(dt('toggleswitch.handle.background'), \";\\n width: \").concat(dt('toggleswitch.handle.size'), \";\\n height: \").concat(dt('toggleswitch.handle.size'), \";\\n left: \").concat(dt('toggleswitch.gap'), \";\\n margin-top: calc(-1 * calc(\").concat(dt('toggleswitch.handle.size'), \" / 2));\\n border-radius: \").concat(dt('toggleswitch.handle.border.radius'), \";\\n transition: background \").concat(dt('toggleswitch.transition.duration'), \", left \").concat(dt('toggleswitch.slide.duration'), \";\\n}\\n\\n.p-toggleswitch.p-toggleswitch-checked .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.checked.background'), \";\\n border-color: \").concat(dt('toggleswitch.checked.border.color'), \";\\n}\\n\\n.p-toggleswitch.p-toggleswitch-checked .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.checked.background'), \";\\n left: calc(\").concat(dt('toggleswitch.width'), \" - calc(\").concat(dt('toggleswitch.handle.size'), \" + \").concat(dt('toggleswitch.gap'), \"));\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover) .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.hover.background'), \";\\n border-color: \").concat(dt('toggleswitch.hover.border.color'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover) .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.hover.background'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover).p-toggleswitch-checked .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.checked.hover.background'), \";\\n border-color: \").concat(dt('toggleswitch.checked.hover.border.color'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover).p-toggleswitch-checked .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.checked.hover.background'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:focus-visible) .p-toggleswitch-slider {\\n box-shadow: \").concat(dt('toggleswitch.focus.ring.shadow'), \";\\n outline: \").concat(dt('toggleswitch.focus.ring.width'), \" \").concat(dt('toggleswitch.focus.ring.style'), \" \").concat(dt('toggleswitch.focus.ring.color'), \";\\n outline-offset: \").concat(dt('toggleswitch.focus.ring.offset'), \";\\n}\\n\\n.p-toggleswitch.p-invalid > .p-toggleswitch-slider {\\n border-color: \").concat(dt('toggleswitch.invalid.border.color'), \";\\n}\\n\\n.p-toggleswitch.p-disabled {\\n opacity: 1;\\n}\\n\\n.p-toggleswitch.p-disabled .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.disabled.background'), \";\\n}\\n\\n.p-toggleswitch.p-disabled .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.disabled.background'), \";\\n}\\n\");\n};\nvar inlineStyles = {\n root: {\n position: 'relative'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-toggleswitch p-component', {\n 'p-toggleswitch-checked': instance.checked,\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid\n }];\n },\n input: 'p-toggleswitch-input',\n slider: 'p-toggleswitch-slider'\n};\nvar ToggleSwitchStyle = BaseStyle.extend({\n name: 'toggleswitch',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { ToggleSwitchStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport ToggleSwitchStyle from 'primevue/toggleswitch/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseToggleSwitch',\n \"extends\": BaseComponent,\n props: {\n modelValue: {\n type: null,\n \"default\": false\n },\n trueValue: {\n type: null,\n \"default\": true\n },\n falseValue: {\n type: null,\n \"default\": false\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: ToggleSwitchStyle,\n provide: function provide() {\n return {\n $pcToggleSwitch: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ToggleSwitch',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n checked: this.checked,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n if (!this.disabled && !this.readonly) {\n var newValue = this.checked ? this.falseValue : this.trueValue;\n this.$emit('update:modelValue', newValue);\n this.$emit('change', event);\n }\n },\n onFocus: function onFocus(event) {\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.$emit('blur', event);\n }\n },\n computed: {\n checked: function checked() {\n return this.modelValue === this.trueValue;\n }\n }\n};\n\nvar _hoisted_1 = [\"data-p-checked\", \"data-p-disabled\"];\nvar _hoisted_2 = [\"id\", \"checked\", \"tabindex\", \"disabled\", \"readonly\", \"aria-checked\", \"aria-labelledby\", \"aria-label\", \"aria-invalid\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root')\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.checked,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"input\", mergeProps({\n id: _ctx.inputId,\n type: \"checkbox\",\n role: \"switch\",\n \"class\": [_ctx.cx('input'), _ctx.inputClass],\n style: _ctx.inputStyle,\n checked: $options.checked,\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n \"aria-checked\": $options.checked,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onChange: _cache[2] || (_cache[2] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('input')), null, 16, _hoisted_2), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('slider')\n }, $options.getPTOptions('slider')), null, 16)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-tag {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n background: \".concat(dt('tag.primary.background'), \";\\n color: \").concat(dt('tag.primary.color'), \";\\n font-size: \").concat(dt('tag.font.size'), \";\\n font-weight: \").concat(dt('tag.font.weight'), \";\\n padding: \").concat(dt('tag.padding'), \";\\n border-radius: \").concat(dt('tag.border.radius'), \";\\n gap: \").concat(dt('tag.gap'), \";\\n}\\n\\n.p-tag-icon {\\n font-size: \").concat(dt('tag.icon.size'), \";\\n width: \").concat(dt('tag.icon.size'), \";\\n height:\").concat(dt('tag.icon.size'), \";\\n}\\n\\n.p-tag-rounded {\\n border-radius: \").concat(dt('tag.rounded.border.radius'), \";\\n}\\n\\n.p-tag-success {\\n background: \").concat(dt('tag.success.background'), \";\\n color: \").concat(dt('tag.success.color'), \";\\n}\\n\\n.p-tag-info {\\n background: \").concat(dt('tag.info.background'), \";\\n color: \").concat(dt('tag.info.color'), \";\\n}\\n\\n.p-tag-warn {\\n background: \").concat(dt('tag.warn.background'), \";\\n color: \").concat(dt('tag.warn.color'), \";\\n}\\n\\n.p-tag-danger {\\n background: \").concat(dt('tag.danger.background'), \";\\n color: \").concat(dt('tag.danger.color'), \";\\n}\\n\\n.p-tag-secondary {\\n background: \").concat(dt('tag.secondary.background'), \";\\n color: \").concat(dt('tag.secondary.color'), \";\\n}\\n\\n.p-tag-contrast {\\n background: \").concat(dt('tag.contrast.background'), \";\\n color: \").concat(dt('tag.contrast.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-tag p-component', {\n 'p-tag-info': props.severity === 'info',\n 'p-tag-success': props.severity === 'success',\n 'p-tag-warn': props.severity === 'warn',\n 'p-tag-danger': props.severity === 'danger',\n 'p-tag-secondary': props.severity === 'secondary',\n 'p-tag-contrast': props.severity === 'contrast',\n 'p-tag-rounded': props.rounded\n }];\n },\n icon: 'p-tag-icon',\n label: 'p-tag-label'\n};\nvar TagStyle = BaseStyle.extend({\n name: 'tag',\n theme: theme,\n classes: classes\n});\n\nexport { TagStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport TagStyle from 'primevue/tag/style';\nimport { openBlock, createElementBlock, mergeProps, createBlock, resolveDynamicComponent, createCommentVNode, renderSlot, createElementVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseTag',\n \"extends\": BaseComponent,\n props: {\n value: null,\n severity: null,\n rounded: Boolean,\n icon: String\n },\n style: TagStyle,\n provide: function provide() {\n return {\n $pcTag: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Tag',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [_ctx.$slots.icon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.icon), mergeProps({\n key: 0,\n \"class\": _ctx.cx('icon')\n }, _ctx.ptm('icon')), null, 16, [\"class\"])) : _ctx.icon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": [_ctx.cx('icon'), _ctx.icon]\n }, _ctx.ptm('icon')), null, 16)) : createCommentVNode(\"\", true), _ctx.value != null || _ctx.$slots[\"default\"] ? renderSlot(_ctx.$slots, \"default\", {\n key: 2\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('label')\n }, _ctx.ptm('label')), toDisplayString(_ctx.value), 17)];\n }) : createCommentVNode(\"\", true)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-slider {\\n position: relative;\\n background: \".concat(dt('slider.track.background'), \";\\n border-radius: \").concat(dt('slider.border.radius'), \";\\n}\\n\\n.p-slider-handle {\\n cursor: grab;\\n touch-action: none;\\n display: flex;\\n justify-content: center;\\n align-items: center;\\n height: \").concat(dt('slider.handle.height'), \";\\n width: \").concat(dt('slider.handle.width'), \";\\n background: \").concat(dt('slider.handle.background'), \";\\n border-radius: \").concat(dt('slider.handle.border.radius'), \";\\n transition: background \").concat(dt('slider.transition.duration'), \", color \").concat(dt('slider.transition.duration'), \", border-color \").concat(dt('slider.transition.duration'), \", box-shadow \").concat(dt('slider.transition.duration'), \", outline-color \").concat(dt('slider.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-slider-handle::before {\\n content: \\\"\\\";\\n width: \").concat(dt('slider.handle.content.width'), \";\\n height: \").concat(dt('slider.handle.content.height'), \";\\n display: block;\\n background: \").concat(dt('slider.handle.content.background'), \";\\n border-radius: \").concat(dt('slider.handle.content.border.radius'), \";\\n box-shadow: \").concat(dt('slider.handle.content.shadow'), \";\\n transition: background \").concat(dt('slider.transition.duration'), \";\\n}\\n\\n.p-slider:not(.p-disabled) .p-slider-handle:hover {\\n background: \").concat(dt('slider.handle.hover.background'), \";\\n}\\n\\n.p-slider:not(.p-disabled) .p-slider-handle:hover::before {\\n background: \").concat(dt('slider.handle.content.hover.background'), \";\\n}\\n\\n.p-slider-handle:focus-visible {\\n border-color: \").concat(dt('slider.handle.focus.border.color'), \";\\n box-shadow: \").concat(dt('slider.handle.focus.ring.shadow'), \";\\n outline: \").concat(dt('slider.handle.focus.ring.width'), \" \").concat(dt('slider.handle.focus.ring.style'), \" \").concat(dt('slider.handle.focus.ring.color'), \";\\n outline-offset: \").concat(dt('slider.handle.focus.ring.offset'), \";\\n}\\n\\n.p-slider-range {\\n display: block;\\n background: \").concat(dt('slider.range.background'), \";\\n border-radius: \").concat(dt('slider.border.radius'), \";\\n}\\n\\n.p-slider.p-slider-horizontal {\\n height: \").concat(dt('slider.track.size'), \";\\n}\\n\\n.p-slider-horizontal .p-slider-range {\\n top: 0;\\n left: 0;\\n height: 100%;\\n}\\n\\n.p-slider-horizontal .p-slider-handle {\\n top: 50%;\\n margin-top: calc(-1 * calc(\").concat(dt('slider.handle.height'), \" / 2));\\n margin-left: calc(-1 * calc(\").concat(dt('slider.handle.width'), \" / 2));\\n}\\n\\n.p-slider-vertical {\\n min-height: 100px;\\n width: \").concat(dt('slider.track.size'), \";\\n}\\n\\n.p-slider-vertical .p-slider-handle {\\n left: 50%;\\n margin-left: calc(-1 * calc(\").concat(dt('slider.handle.width'), \" / 2));\\n margin-bottom: calc(-1 * calc(\").concat(dt('slider.handle.height'), \" / 2));\\n}\\n\\n.p-slider-vertical .p-slider-range {\\n bottom: 0;\\n left: 0;\\n width: 100%;\\n}\\n\");\n};\nvar inlineStyles = {\n handle: {\n position: 'absolute'\n },\n range: {\n position: 'absolute'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-slider p-component', {\n 'p-disabled': props.disabled,\n 'p-slider-horizontal': props.orientation === 'horizontal',\n 'p-slider-vertical': props.orientation === 'vertical'\n }];\n },\n range: 'p-slider-range',\n handle: 'p-slider-handle'\n};\nvar SliderStyle = BaseStyle.extend({\n name: 'slider',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { SliderStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getWindowScrollLeft, getWindowScrollTop, getAttribute } from '@primeuix/utils/dom';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SliderStyle from 'primevue/slider/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseSlider',\n \"extends\": BaseComponent,\n props: {\n modelValue: [Number, Array],\n min: {\n type: Number,\n \"default\": 0\n },\n max: {\n type: Number,\n \"default\": 100\n },\n orientation: {\n type: String,\n \"default\": 'horizontal'\n },\n step: {\n type: Number,\n \"default\": null\n },\n range: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: SliderStyle,\n provide: function provide() {\n return {\n $pcSlider: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Slider',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'slideend'],\n dragging: false,\n handleIndex: null,\n initX: null,\n initY: null,\n barWidth: null,\n barHeight: null,\n dragListener: null,\n dragEndListener: null,\n beforeUnmount: function beforeUnmount() {\n this.unbindDragListeners();\n },\n methods: {\n updateDomData: function updateDomData() {\n var rect = this.$el.getBoundingClientRect();\n this.initX = rect.left + getWindowScrollLeft();\n this.initY = rect.top + getWindowScrollTop();\n this.barWidth = this.$el.offsetWidth;\n this.barHeight = this.$el.offsetHeight;\n },\n setValue: function setValue(event) {\n var handleValue;\n var pageX = event.touches ? event.touches[0].pageX : event.pageX;\n var pageY = event.touches ? event.touches[0].pageY : event.pageY;\n if (this.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight;\n var newValue = (this.max - this.min) * (handleValue / 100) + this.min;\n if (this.step) {\n var oldValue = this.range ? this.value[this.handleIndex] : this.value;\n var diff = newValue - oldValue;\n if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.step - oldValue / this.step) * this.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.step - oldValue / this.step) * this.step;\n } else {\n newValue = Math.floor(newValue);\n }\n this.updateModel(event, newValue);\n },\n updateModel: function updateModel(event, value) {\n var newValue = parseFloat(value.toFixed(10));\n var modelValue;\n if (this.range) {\n modelValue = this.value ? _toConsumableArray(this.value) : [];\n if (this.handleIndex == 0) {\n if (newValue < this.min) newValue = this.min;else if (newValue >= this.max) newValue = this.max;\n modelValue[0] = newValue;\n } else {\n if (newValue > this.max) newValue = this.max;else if (newValue <= this.min) newValue = this.min;\n modelValue[1] = newValue;\n }\n } else {\n if (newValue < this.min) newValue = this.min;else if (newValue > this.max) newValue = this.max;\n modelValue = newValue;\n }\n this.$emit('update:modelValue', modelValue);\n this.$emit('change', modelValue);\n },\n onDragStart: function onDragStart(event, index) {\n if (this.disabled) {\n return;\n }\n this.$el.setAttribute('data-p-sliding', true);\n this.dragging = true;\n this.updateDomData();\n if (this.range && this.value[0] === this.max) {\n this.handleIndex = 0;\n } else {\n this.handleIndex = index;\n }\n event.currentTarget.focus();\n event.preventDefault();\n },\n onDrag: function onDrag(event) {\n if (this.dragging) {\n this.setValue(event);\n event.preventDefault();\n }\n },\n onDragEnd: function onDragEnd(event) {\n if (this.dragging) {\n this.dragging = false;\n this.$el.setAttribute('data-p-sliding', false);\n this.$emit('slideend', {\n originalEvent: event,\n value: this.value\n });\n }\n },\n onBarClick: function onBarClick(event) {\n if (this.disabled) {\n return;\n }\n if (getAttribute(event.target, 'data-pc-section') !== 'handle') {\n this.updateDomData();\n this.setValue(event);\n }\n },\n onMouseDown: function onMouseDown(event, index) {\n this.bindDragListeners();\n this.onDragStart(event, index);\n },\n onKeyDown: function onKeyDown(event, index) {\n this.handleIndex = index;\n switch (event.code) {\n case 'ArrowDown':\n case 'ArrowLeft':\n this.decrementValue(event, index);\n event.preventDefault();\n break;\n case 'ArrowUp':\n case 'ArrowRight':\n this.incrementValue(event, index);\n event.preventDefault();\n break;\n case 'PageDown':\n this.decrementValue(event, index, true);\n event.preventDefault();\n break;\n case 'PageUp':\n this.incrementValue(event, index, true);\n event.preventDefault();\n break;\n case 'Home':\n this.updateModel(event, this.min);\n event.preventDefault();\n break;\n case 'End':\n this.updateModel(event, this.max);\n event.preventDefault();\n break;\n }\n },\n decrementValue: function decrementValue(event, index) {\n var pageKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var newValue;\n if (this.range) {\n if (this.step) newValue = this.value[index] - this.step;else newValue = this.value[index] - 1;\n } else {\n if (this.step) newValue = this.value - this.step;else if (!this.step && pageKey) newValue = this.value - 10;else newValue = this.value - 1;\n }\n this.updateModel(event, newValue);\n event.preventDefault();\n },\n incrementValue: function incrementValue(event, index) {\n var pageKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var newValue;\n if (this.range) {\n if (this.step) newValue = this.value[index] + this.step;else newValue = this.value[index] + 1;\n } else {\n if (this.step) newValue = this.value + this.step;else if (!this.step && pageKey) newValue = this.value + 10;else newValue = this.value + 1;\n }\n this.updateModel(event, newValue);\n event.preventDefault();\n },\n bindDragListeners: function bindDragListeners() {\n if (!this.dragListener) {\n this.dragListener = this.onDrag.bind(this);\n document.addEventListener('mousemove', this.dragListener);\n }\n if (!this.dragEndListener) {\n this.dragEndListener = this.onDragEnd.bind(this);\n document.addEventListener('mouseup', this.dragEndListener);\n }\n },\n unbindDragListeners: function unbindDragListeners() {\n if (this.dragListener) {\n document.removeEventListener('mousemove', this.dragListener);\n this.dragListener = null;\n }\n if (this.dragEndListener) {\n document.removeEventListener('mouseup', this.dragEndListener);\n this.dragEndListener = null;\n }\n }\n },\n computed: {\n value: function value() {\n var _this$modelValue3;\n if (this.range) {\n var _this$modelValue$, _this$modelValue, _this$modelValue$2, _this$modelValue2;\n return [(_this$modelValue$ = (_this$modelValue = this.modelValue) === null || _this$modelValue === void 0 ? void 0 : _this$modelValue[0]) !== null && _this$modelValue$ !== void 0 ? _this$modelValue$ : this.min, (_this$modelValue$2 = (_this$modelValue2 = this.modelValue) === null || _this$modelValue2 === void 0 ? void 0 : _this$modelValue2[1]) !== null && _this$modelValue$2 !== void 0 ? _this$modelValue$2 : this.max];\n }\n return (_this$modelValue3 = this.modelValue) !== null && _this$modelValue3 !== void 0 ? _this$modelValue3 : this.min;\n },\n horizontal: function horizontal() {\n return this.orientation === 'horizontal';\n },\n vertical: function vertical() {\n return this.orientation === 'vertical';\n },\n rangeStyle: function rangeStyle() {\n if (this.range) {\n var rangeSliderWidth = this.rangeEndPosition > this.rangeStartPosition ? this.rangeEndPosition - this.rangeStartPosition : this.rangeStartPosition - this.rangeEndPosition;\n var rangeSliderPosition = this.rangeEndPosition > this.rangeStartPosition ? this.rangeStartPosition : this.rangeEndPosition;\n if (this.horizontal) return {\n left: rangeSliderPosition + '%',\n width: rangeSliderWidth + '%'\n };else return {\n bottom: rangeSliderPosition + '%',\n height: rangeSliderWidth + '%'\n };\n } else {\n if (this.horizontal) return {\n width: this.handlePosition + '%'\n };else return {\n height: this.handlePosition + '%'\n };\n }\n },\n handleStyle: function handleStyle() {\n if (this.horizontal) return {\n left: this.handlePosition + '%'\n };else return {\n bottom: this.handlePosition + '%'\n };\n },\n handlePosition: function handlePosition() {\n if (this.value < this.min) return 0;else if (this.value > this.max) return 100;else return (this.value - this.min) * 100 / (this.max - this.min);\n },\n rangeStartPosition: function rangeStartPosition() {\n if (this.value && this.value[0]) return (this.value[0] < this.min ? 0 : this.value[0] - this.min) * 100 / (this.max - this.min);else return 0;\n },\n rangeEndPosition: function rangeEndPosition() {\n if (this.value && this.value.length === 2) return (this.value[1] > this.max ? 100 : this.value[1] - this.min) * 100 / (this.max - this.min);else return 100;\n },\n rangeStartHandleStyle: function rangeStartHandleStyle() {\n if (this.horizontal) return {\n left: this.rangeStartPosition + '%'\n };else return {\n bottom: this.rangeStartPosition + '%'\n };\n },\n rangeEndHandleStyle: function rangeEndHandleStyle() {\n if (this.horizontal) return {\n left: this.rangeEndPosition + '%'\n };else return {\n bottom: this.rangeEndPosition + '%'\n };\n }\n }\n};\n\nvar _hoisted_1 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nvar _hoisted_2 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nvar _hoisted_3 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n onClick: _cache[15] || (_cache[15] = function () {\n return $options.onBarClick && $options.onBarClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root'), {\n \"data-p-sliding\": false\n }), [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('range'),\n style: [_ctx.sx('range'), $options.rangeStyle]\n }, _ctx.ptm('range')), null, 16), !_ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.handleStyle],\n onTouchstartPassive: _cache[0] || (_cache[0] = function ($event) {\n return $options.onDragStart($event);\n }),\n onTouchmovePassive: _cache[1] || (_cache[1] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[2] || (_cache[2] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[3] || (_cache[3] = function ($event) {\n return $options.onMouseDown($event);\n }),\n onKeydown: _cache[4] || (_cache[4] = function ($event) {\n return $options.onKeyDown($event);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('handle')), null, 16, _hoisted_1)) : createCommentVNode(\"\", true), _ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.rangeStartHandleStyle],\n onTouchstartPassive: _cache[5] || (_cache[5] = function ($event) {\n return $options.onDragStart($event, 0);\n }),\n onTouchmovePassive: _cache[6] || (_cache[6] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[7] || (_cache[7] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[8] || (_cache[8] = function ($event) {\n return $options.onMouseDown($event, 0);\n }),\n onKeydown: _cache[9] || (_cache[9] = function ($event) {\n return $options.onKeyDown($event, 0);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue ? _ctx.modelValue[0] : null,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('startHandler')), null, 16, _hoisted_2)) : createCommentVNode(\"\", true), _ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.rangeEndHandleStyle],\n onTouchstartPassive: _cache[10] || (_cache[10] = function ($event) {\n return $options.onDragStart($event, 1);\n }),\n onTouchmovePassive: _cache[11] || (_cache[11] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[12] || (_cache[12] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[13] || (_cache[13] = function ($event) {\n return $options.onMouseDown($event, 1);\n }),\n onKeydown: _cache[14] || (_cache[14] = function ($event) {\n return $options.onKeyDown($event, 1);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue ? _ctx.modelValue[1] : null,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('endHandler')), null, 16, _hoisted_3)) : createCommentVNode(\"\", true)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n\r\n\r\n\r\n","export function formatCamelCase(str: string): string {\r\n // Check if the string is camel case\r\n const isCamelCase = /^([A-Z][a-z]*)+$/.test(str)\r\n\r\n if (!isCamelCase) {\r\n return str // Return original string if not camel case\r\n }\r\n\r\n // Split the string into words, keeping acronyms together\r\n const words = str.split(/(?=[A-Z][a-z])|\\d+/)\r\n\r\n // Process each word\r\n const processedWords = words.map((word) => {\r\n // If the word is all uppercase and longer than one character, it's likely an acronym\r\n if (word.length > 1 && word === word.toUpperCase()) {\r\n return word // Keep acronyms as is\r\n }\r\n // For other words, ensure the first letter is capitalized\r\n return word.charAt(0).toUpperCase() + word.slice(1)\r\n })\r\n\r\n // Join the words with spaces\r\n return processedWords.join(' ')\r\n}\r\n","\r\n\r\n\r\n\r\n\r\n","/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

' + func(text) + '

';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

fred, barney, & pebbles

'\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-card {\\n background: \".concat(dt('card.background'), \";\\n color: \").concat(dt('card.color'), \";\\n box-shadow: \").concat(dt('card.shadow'), \";\\n border-radius: \").concat(dt('card.border.radius'), \";\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-card-caption {\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('card.caption.gap'), \";\\n}\\n\\n.p-card-body {\\n padding: \").concat(dt('card.body.padding'), \";\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('card.body.gap'), \";\\n}\\n\\n.p-card-title {\\n font-size: \").concat(dt('card.title.font.size'), \";\\n font-weight: \").concat(dt('card.title.font.weight'), \";\\n}\\n\\n.p-card-subtitle {\\n color: \").concat(dt('card.subtitle.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-card p-component',\n header: 'p-card-header',\n body: 'p-card-body',\n caption: 'p-card-caption',\n title: 'p-card-title',\n subtitle: 'p-card-subtitle',\n content: 'p-card-content',\n footer: 'p-card-footer'\n};\nvar CardStyle = BaseStyle.extend({\n name: 'card',\n theme: theme,\n classes: classes\n});\n\nexport { CardStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport CardStyle from 'primevue/card/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createCommentVNode, createElementVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseCard',\n \"extends\": BaseComponent,\n style: CardStyle,\n provide: function provide() {\n return {\n $pcCard: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Card',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [_ctx.$slots.header ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [renderSlot(_ctx.$slots, \"header\")], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('body')\n }, _ctx.ptm('body')), [_ctx.$slots.title || _ctx.$slots.subtitle ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('caption')\n }, _ctx.ptm('caption')), [_ctx.$slots.title ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('title')\n }, _ctx.ptm('title')), [renderSlot(_ctx.$slots, \"title\")], 16)) : createCommentVNode(\"\", true), _ctx.$slots.subtitle ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('subtitle')\n }, _ctx.ptm('subtitle')), [renderSlot(_ctx.$slots, \"subtitle\")], 16)) : createCommentVNode(\"\", true)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('content')\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"content\")], 16), _ctx.$slots.footer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [renderSlot(_ctx.$slots, \"footer\")], 16)) : createCommentVNode(\"\", true)], 16)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import type { TreeNode } from 'primevue/treenode'\r\n\r\nexport function buildTree(\r\n items: T[],\r\n key: string | ((item: T) => string[])\r\n): TreeNode {\r\n const root: TreeNode = {\r\n key: 'root',\r\n label: 'root',\r\n children: []\r\n }\r\n\r\n const map: Record = {\r\n root: root\r\n }\r\n\r\n for (const item of items) {\r\n const keys = typeof key === 'string' ? item[key] : key(item)\r\n let parent = root\r\n for (const k of keys) {\r\n const id = parent.key + '/' + k\r\n if (!map[id]) {\r\n const node: TreeNode = {\r\n key: id,\r\n label: k,\r\n leaf: false,\r\n children: []\r\n }\r\n map[id] = node\r\n parent.children.push(node)\r\n }\r\n parent = map[id]\r\n }\r\n parent.leaf = true\r\n parent.data = item\r\n }\r\n return root\r\n}\r\n\r\nexport function flattenTree(tree: TreeNode): T[] {\r\n const result: T[] = []\r\n const stack: TreeNode[] = [tree]\r\n while (stack.length) {\r\n const node = stack.pop()!\r\n if (node.leaf && node.data) result.push(node.data)\r\n stack.push(...(node.children || []))\r\n }\r\n return result\r\n}\r\n\r\nexport function sortedTree(node: TreeNode): TreeNode {\r\n // Create a new node with the same label and data\r\n const newNode: TreeNode = {\r\n ...node\r\n }\r\n\r\n if (node.children) {\r\n // Sort the children of the current node\r\n const sortedChildren = [...node.children].sort((a, b) =>\r\n a.label.localeCompare(b.label)\r\n )\r\n // Recursively sort the children and add them to the new node\r\n newNode.children = []\r\n for (const child of sortedChildren) {\r\n newNode.children.push(sortedTree(child))\r\n }\r\n }\r\n\r\n return newNode\r\n}\r\n","\r\n\r\n\r\n\r\n\r\n\r\n\r\n","\r\n\r\n\r\n\r\n\r\n","// This module is mocked in tests-ui/\r\n// Import vue components here to avoid tests-ui/ reporting errors\r\n// about importing primevue components.\r\nimport { useDialogStore } from '@/stores/dialogStore'\r\nimport LoadWorkflowWarning from '@/components/dialog/content/LoadWorkflowWarning.vue'\r\nimport SettingDialogContent from '@/components/dialog/content/SettingDialogContent.vue'\r\nimport SettingDialogHeader from '@/components/dialog/header/SettingDialogHeader.vue'\r\n\r\nexport function showLoadWorkflowWarning(props: {\r\n missingNodeTypes: any[]\r\n hasAddedNodes: boolean\r\n [key: string]: any\r\n}) {\r\n const dialogStore = useDialogStore()\r\n dialogStore.showDialog({\r\n component: LoadWorkflowWarning,\r\n props\r\n })\r\n}\r\n\r\nexport function showSettingsDialog() {\r\n useDialogStore().showDialog({\r\n headerComponent: SettingDialogHeader,\r\n component: SettingDialogContent\r\n })\r\n}\r\n","import { api } from './api'\r\nimport { ComfyDialog as _ComfyDialog } from './ui/dialog'\r\nimport { toggleSwitch } from './ui/toggleSwitch'\r\nimport { ComfySettingsDialog } from './ui/settings'\r\nimport { ComfyApp, app } from './app'\r\nimport { TaskItem } from '@/types/apiTypes'\r\nimport { showSettingsDialog } from '@/services/dialogService'\r\n\r\nexport const ComfyDialog = _ComfyDialog\r\n\r\ntype Position2D = {\r\n x: number\r\n y: number\r\n}\r\n\r\ntype Props = {\r\n parent?: HTMLElement\r\n $?: (el: HTMLElement) => void\r\n dataset?: DOMStringMap\r\n style?: Partial\r\n for?: string\r\n textContent?: string\r\n [key: string]: any\r\n}\r\n\r\ntype Children = Element[] | Element | string | string[]\r\n\r\ntype ElementType = K extends keyof HTMLElementTagNameMap\r\n ? HTMLElementTagNameMap[K]\r\n : HTMLElement\r\n\r\nexport function $el(\r\n tag: TTag,\r\n propsOrChildren?: Children | Props,\r\n children?: Children\r\n): ElementType {\r\n const split = tag.split('.')\r\n const element = document.createElement(split.shift() as string)\r\n if (split.length > 0) {\r\n element.classList.add(...split)\r\n }\r\n\r\n if (propsOrChildren) {\r\n if (typeof propsOrChildren === 'string') {\r\n propsOrChildren = { textContent: propsOrChildren }\r\n } else if (propsOrChildren instanceof Element) {\r\n propsOrChildren = [propsOrChildren]\r\n }\r\n if (Array.isArray(propsOrChildren)) {\r\n element.append(...propsOrChildren)\r\n } else {\r\n const {\r\n parent,\r\n $: cb,\r\n dataset,\r\n style,\r\n ...rest\r\n } = propsOrChildren as Props\r\n\r\n if (rest.for) {\r\n element.setAttribute('for', rest.for)\r\n }\r\n\r\n if (style) {\r\n Object.assign(element.style, style)\r\n }\r\n\r\n if (dataset) {\r\n Object.assign(element.dataset, dataset)\r\n }\r\n\r\n Object.assign(element, rest)\r\n if (children) {\r\n element.append(...(Array.isArray(children) ? children : [children]))\r\n }\r\n\r\n if (parent) {\r\n parent.append(element)\r\n }\r\n\r\n if (cb) {\r\n cb(element)\r\n }\r\n }\r\n }\r\n return element as ElementType\r\n}\r\n\r\nfunction dragElement(dragEl, settings): () => void {\r\n var posDiffX = 0,\r\n posDiffY = 0,\r\n posStartX = 0,\r\n posStartY = 0,\r\n newPosX = 0,\r\n newPosY = 0\r\n if (dragEl.getElementsByClassName('drag-handle')[0]) {\r\n // if present, the handle is where you move the DIV from:\r\n dragEl.getElementsByClassName('drag-handle')[0].onmousedown = dragMouseDown\r\n } else {\r\n // otherwise, move the DIV from anywhere inside the DIV:\r\n dragEl.onmousedown = dragMouseDown\r\n }\r\n\r\n // When the element resizes (e.g. view queue) ensure it is still in the windows bounds\r\n const resizeObserver = new ResizeObserver(() => {\r\n ensureInBounds()\r\n }).observe(dragEl)\r\n\r\n function ensureInBounds() {\r\n try {\r\n newPosX = Math.min(\r\n document.body.clientWidth - dragEl.clientWidth,\r\n Math.max(0, dragEl.offsetLeft)\r\n )\r\n newPosY = Math.min(\r\n document.body.clientHeight - dragEl.clientHeight,\r\n Math.max(0, dragEl.offsetTop)\r\n )\r\n\r\n positionElement()\r\n } catch (exception) {\r\n // robust\r\n }\r\n }\r\n\r\n function positionElement() {\r\n if (dragEl.style.display === 'none') return\r\n\r\n const halfWidth = document.body.clientWidth / 2\r\n const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth\r\n\r\n // set the element's new position:\r\n if (anchorRight) {\r\n dragEl.style.left = 'unset'\r\n dragEl.style.right =\r\n document.body.clientWidth - newPosX - dragEl.clientWidth + 'px'\r\n } else {\r\n dragEl.style.left = newPosX + 'px'\r\n dragEl.style.right = 'unset'\r\n }\r\n\r\n dragEl.style.top = newPosY + 'px'\r\n dragEl.style.bottom = 'unset'\r\n\r\n if (savePos) {\r\n localStorage.setItem(\r\n 'Comfy.MenuPosition',\r\n JSON.stringify({\r\n x: dragEl.offsetLeft,\r\n y: dragEl.offsetTop\r\n })\r\n )\r\n }\r\n }\r\n\r\n function restorePos() {\r\n let posString = localStorage.getItem('Comfy.MenuPosition')\r\n if (posString) {\r\n const pos = JSON.parse(posString) as Position2D\r\n newPosX = pos.x\r\n newPosY = pos.y\r\n positionElement()\r\n ensureInBounds()\r\n }\r\n }\r\n\r\n let savePos = undefined\r\n settings.addSetting({\r\n id: 'Comfy.MenuPosition',\r\n category: ['Comfy', 'Menu', 'MenuPosition'],\r\n name: \"Save legacy menu's position\",\r\n type: 'boolean',\r\n defaultValue: savePos,\r\n onChange(value) {\r\n if (savePos === undefined && value) {\r\n restorePos()\r\n }\r\n savePos = value\r\n }\r\n })\r\n\r\n function dragMouseDown(e) {\r\n e = e || window.event\r\n e.preventDefault()\r\n // get the mouse cursor position at startup:\r\n posStartX = e.clientX\r\n posStartY = e.clientY\r\n document.onmouseup = closeDragElement\r\n // call a function whenever the cursor moves:\r\n document.onmousemove = elementDrag\r\n }\r\n\r\n function elementDrag(e) {\r\n e = e || window.event\r\n e.preventDefault()\r\n\r\n dragEl.classList.add('comfy-menu-manual-pos')\r\n\r\n // calculate the new cursor position:\r\n posDiffX = e.clientX - posStartX\r\n posDiffY = e.clientY - posStartY\r\n posStartX = e.clientX\r\n posStartY = e.clientY\r\n\r\n newPosX = Math.min(\r\n document.body.clientWidth - dragEl.clientWidth,\r\n Math.max(0, dragEl.offsetLeft + posDiffX)\r\n )\r\n newPosY = Math.min(\r\n document.body.clientHeight - dragEl.clientHeight,\r\n Math.max(0, dragEl.offsetTop + posDiffY)\r\n )\r\n\r\n positionElement()\r\n }\r\n\r\n window.addEventListener('resize', () => {\r\n ensureInBounds()\r\n })\r\n\r\n function closeDragElement() {\r\n // stop moving when mouse button is released:\r\n document.onmouseup = null\r\n document.onmousemove = null\r\n }\r\n\r\n return restorePos\r\n}\r\n\r\nclass ComfyList {\r\n #type\r\n #text\r\n #reverse\r\n element: HTMLDivElement\r\n button?: HTMLButtonElement\r\n\r\n constructor(text, type?, reverse?) {\r\n this.#text = text\r\n this.#type = type || text.toLowerCase()\r\n this.#reverse = reverse || false\r\n this.element = $el('div.comfy-list') as HTMLDivElement\r\n this.element.style.display = 'none'\r\n }\r\n\r\n get visible() {\r\n return this.element.style.display !== 'none'\r\n }\r\n\r\n async load() {\r\n const items = await api.getItems(this.#type)\r\n this.element.replaceChildren(\r\n ...Object.keys(items).flatMap((section) => [\r\n $el('h4', {\r\n textContent: section\r\n }),\r\n $el('div.comfy-list-items', [\r\n ...(this.#reverse ? items[section].reverse() : items[section]).map(\r\n (item: TaskItem) => {\r\n // Allow items to specify a custom remove action (e.g. for interrupt current prompt)\r\n const removeAction =\r\n 'remove' in item\r\n ? item.remove\r\n : {\r\n name: 'Delete',\r\n cb: () => api.deleteItem(this.#type, item.prompt[1])\r\n }\r\n return $el('div', { textContent: item.prompt[0] + ': ' }, [\r\n $el('button', {\r\n textContent: 'Load',\r\n onclick: async () => {\r\n await app.loadGraphData(\r\n item.prompt[3].extra_pnginfo.workflow,\r\n true,\r\n false\r\n )\r\n if ('outputs' in item) {\r\n app.nodeOutputs = {}\r\n for (const [key, value] of Object.entries(item.outputs)) {\r\n const realKey = item['meta']?.[key]?.display_node ?? key\r\n app.nodeOutputs[realKey] = value\r\n }\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n textContent: removeAction.name,\r\n onclick: async () => {\r\n await removeAction.cb()\r\n await this.update()\r\n }\r\n })\r\n ])\r\n }\r\n )\r\n ])\r\n ]),\r\n $el('div.comfy-list-actions', [\r\n $el('button', {\r\n textContent: 'Clear ' + this.#text,\r\n onclick: async () => {\r\n await api.clearItems(this.#type)\r\n await this.load()\r\n }\r\n }),\r\n $el('button', { textContent: 'Refresh', onclick: () => this.load() })\r\n ])\r\n )\r\n }\r\n\r\n async update() {\r\n if (this.visible) {\r\n await this.load()\r\n }\r\n }\r\n\r\n async show() {\r\n this.element.style.display = 'block'\r\n this.button.textContent = 'Close'\r\n\r\n await this.load()\r\n }\r\n\r\n hide() {\r\n this.element.style.display = 'none'\r\n this.button.textContent = 'View ' + this.#text\r\n }\r\n\r\n toggle() {\r\n if (this.visible) {\r\n this.hide()\r\n return false\r\n } else {\r\n this.show()\r\n return true\r\n }\r\n }\r\n}\r\n\r\nexport class ComfyUI {\r\n app: ComfyApp\r\n dialog: _ComfyDialog\r\n settings: ComfySettingsDialog\r\n batchCount: number\r\n lastQueueSize: number\r\n queue: ComfyList\r\n history: ComfyList\r\n autoQueueMode: string\r\n graphHasChanged: boolean\r\n autoQueueEnabled: boolean\r\n menuHamburger: HTMLDivElement\r\n menuContainer: HTMLDivElement\r\n queueSize: Element\r\n restoreMenuPosition: () => void\r\n loadFile: () => void\r\n\r\n constructor(app) {\r\n this.app = app\r\n this.dialog = new ComfyDialog()\r\n this.settings = new ComfySettingsDialog(app)\r\n\r\n this.batchCount = 1\r\n this.lastQueueSize = 0\r\n this.queue = new ComfyList('Queue')\r\n this.history = new ComfyList('History', 'history', true)\r\n\r\n api.addEventListener('status', () => {\r\n this.queue.update()\r\n this.history.update()\r\n })\r\n\r\n const confirmClear = this.settings.addSetting({\r\n id: 'Comfy.ConfirmClear',\r\n category: ['Comfy', 'Workflow', 'ConfirmClear'],\r\n name: 'Require confirmation when clearing workflow',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n const promptFilename = this.settings.addSetting({\r\n id: 'Comfy.PromptFilename',\r\n category: ['Comfy', 'Workflow', 'PromptFilename'],\r\n name: 'Prompt for filename when saving workflow',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n /**\r\n * file format for preview\r\n *\r\n * format;quality\r\n *\r\n * ex)\r\n * webp;50 -> webp, quality 50\r\n * jpeg;80 -> rgb, jpeg, quality 80\r\n *\r\n * @type {string}\r\n */\r\n const previewImage = this.settings.addSetting({\r\n id: 'Comfy.PreviewFormat',\r\n category: ['Comfy', 'Node Widget', 'PreviewFormat'],\r\n name: 'Preview image format',\r\n tooltip:\r\n 'When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc.',\r\n type: 'text',\r\n defaultValue: ''\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.DisableSliders',\r\n category: ['Comfy', 'Node Widget', 'DisableSliders'],\r\n name: 'Disable node widget sliders',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.DisableFloatRounding',\r\n category: ['Comfy', 'Node Widget', 'DisableFloatRounding'],\r\n name: 'Disable default float widget rounding.',\r\n tooltip:\r\n '(requires page reload) Cannot disable round when round is set by the node in the backend.',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.FloatRoundingPrecision',\r\n category: ['Comfy', 'Node Widget', 'FloatRoundingPrecision'],\r\n name: 'Float widget rounding decimal places [0 = auto].',\r\n tooltip: '(requires page reload)',\r\n type: 'slider',\r\n attrs: {\r\n min: 0,\r\n max: 6,\r\n step: 1\r\n },\r\n defaultValue: 0\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.EnableTooltips',\r\n category: ['Comfy', 'Node', 'EnableTooltips'],\r\n name: 'Enable Tooltips',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n const fileInput = $el('input', {\r\n id: 'comfy-file-input',\r\n type: 'file',\r\n accept: '.json,image/png,.latent,.safetensors,image/webp,audio/flac',\r\n style: { display: 'none' },\r\n parent: document.body,\r\n onchange: () => {\r\n app.handleFile(fileInput.files[0])\r\n }\r\n })\r\n\r\n this.loadFile = () => fileInput.click()\r\n\r\n const autoQueueModeEl = toggleSwitch(\r\n 'autoQueueMode',\r\n [\r\n {\r\n text: 'instant',\r\n tooltip: 'A new prompt will be queued as soon as the queue reaches 0'\r\n },\r\n {\r\n text: 'change',\r\n tooltip:\r\n 'A new prompt will be queued when the queue is at 0 and the graph is/has changed'\r\n }\r\n ],\r\n {\r\n onChange: (value) => {\r\n this.autoQueueMode = value.item.value\r\n }\r\n }\r\n )\r\n autoQueueModeEl.style.display = 'none'\r\n\r\n api.addEventListener('graphChanged', () => {\r\n if (this.autoQueueMode === 'change' && this.autoQueueEnabled === true) {\r\n if (this.lastQueueSize === 0) {\r\n this.graphHasChanged = false\r\n app.queuePrompt(0, this.batchCount)\r\n } else {\r\n this.graphHasChanged = true\r\n }\r\n }\r\n })\r\n\r\n this.menuHamburger = $el(\r\n 'div.comfy-menu-hamburger',\r\n {\r\n parent: document.body,\r\n onclick: () => {\r\n this.menuContainer.style.display = 'block'\r\n this.menuHamburger.style.display = 'none'\r\n }\r\n },\r\n [$el('div'), $el('div'), $el('div')]\r\n ) as HTMLDivElement\r\n\r\n this.menuContainer = $el('div.comfy-menu', { parent: document.body }, [\r\n $el(\r\n 'div.drag-handle.comfy-menu-header',\r\n {\r\n style: {\r\n overflow: 'hidden',\r\n position: 'relative',\r\n width: '100%',\r\n cursor: 'default'\r\n }\r\n },\r\n [\r\n $el('span.drag-handle'),\r\n $el('span.comfy-menu-queue-size', { $: (q) => (this.queueSize = q) }),\r\n $el('div.comfy-menu-actions', [\r\n $el('button.comfy-settings-btn', {\r\n textContent: '⚙️',\r\n onclick: showSettingsDialog\r\n }),\r\n $el('button.comfy-close-menu-btn', {\r\n textContent: '\\u00d7',\r\n onclick: () => {\r\n this.menuContainer.style.display = 'none'\r\n this.menuHamburger.style.display = 'flex'\r\n }\r\n })\r\n ])\r\n ]\r\n ),\r\n $el('button.comfy-queue-btn', {\r\n id: 'queue-button',\r\n textContent: 'Queue Prompt',\r\n onclick: () => app.queuePrompt(0, this.batchCount)\r\n }),\r\n $el('div', {}, [\r\n $el('label', { innerHTML: 'Extra options' }, [\r\n $el('input', {\r\n type: 'checkbox',\r\n onchange: (i) => {\r\n document.getElementById('extraOptions').style.display = i\r\n .srcElement.checked\r\n ? 'block'\r\n : 'none'\r\n this.batchCount = i.srcElement.checked\r\n ? Number.parseInt(\r\n (\r\n document.getElementById(\r\n 'batchCountInputRange'\r\n ) as HTMLInputElement\r\n ).value\r\n )\r\n : 1\r\n ;(\r\n document.getElementById('autoQueueCheckbox') as HTMLInputElement\r\n ).checked = false\r\n this.autoQueueEnabled = false\r\n }\r\n })\r\n ])\r\n ]),\r\n $el(\r\n 'div',\r\n { id: 'extraOptions', style: { width: '100%', display: 'none' } },\r\n [\r\n $el('div', [\r\n $el('label', { innerHTML: 'Batch count' }),\r\n $el('input', {\r\n id: 'batchCountInputNumber',\r\n type: 'number',\r\n value: this.batchCount,\r\n min: '1',\r\n style: { width: '35%', marginLeft: '0.4em' },\r\n oninput: (i) => {\r\n this.batchCount = i.target.value\r\n /* Even though an element with a type of range logically represents a number (since\r\n it's used for numeric input), the value it holds is still treated as a string in HTML and\r\n JavaScript. This behavior is consistent across all elements regardless of their type\r\n (like text, number, or range), where the .value property is always a string. */\r\n ;(\r\n document.getElementById(\r\n 'batchCountInputRange'\r\n ) as HTMLInputElement\r\n ).value = this.batchCount.toString()\r\n }\r\n }),\r\n $el('input', {\r\n id: 'batchCountInputRange',\r\n type: 'range',\r\n min: '1',\r\n max: '100',\r\n value: this.batchCount,\r\n oninput: (i) => {\r\n this.batchCount = i.srcElement.value\r\n // Note\r\n ;(\r\n document.getElementById(\r\n 'batchCountInputNumber'\r\n ) as HTMLInputElement\r\n ).value = i.srcElement.value\r\n }\r\n })\r\n ]),\r\n $el('div', [\r\n $el('label', {\r\n for: 'autoQueueCheckbox',\r\n innerHTML: 'Auto Queue'\r\n }),\r\n $el('input', {\r\n id: 'autoQueueCheckbox',\r\n type: 'checkbox',\r\n checked: false,\r\n title: 'Automatically queue prompt when the queue size hits 0',\r\n onchange: (e) => {\r\n this.autoQueueEnabled = e.target.checked\r\n autoQueueModeEl.style.display = this.autoQueueEnabled\r\n ? ''\r\n : 'none'\r\n }\r\n }),\r\n autoQueueModeEl\r\n ])\r\n ]\r\n ),\r\n $el('div.comfy-menu-btns', [\r\n $el('button', {\r\n id: 'queue-front-button',\r\n textContent: 'Queue Front',\r\n onclick: () => app.queuePrompt(-1, this.batchCount)\r\n }),\r\n $el('button', {\r\n $: (b) => (this.queue.button = b as HTMLButtonElement),\r\n id: 'comfy-view-queue-button',\r\n textContent: 'View Queue',\r\n onclick: () => {\r\n this.history.hide()\r\n this.queue.toggle()\r\n }\r\n }),\r\n $el('button', {\r\n $: (b) => (this.history.button = b as HTMLButtonElement),\r\n id: 'comfy-view-history-button',\r\n textContent: 'View History',\r\n onclick: () => {\r\n this.queue.hide()\r\n this.history.toggle()\r\n }\r\n })\r\n ]),\r\n this.queue.element,\r\n this.history.element,\r\n $el('button', {\r\n id: 'comfy-save-button',\r\n textContent: 'Save',\r\n onclick: () => {\r\n let filename = 'workflow.json'\r\n if (promptFilename.value) {\r\n filename = prompt('Save workflow as:', filename)\r\n if (!filename) return\r\n if (!filename.toLowerCase().endsWith('.json')) {\r\n filename += '.json'\r\n }\r\n }\r\n app.graphToPrompt().then((p) => {\r\n const json = JSON.stringify(p.workflow, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n })\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-dev-save-api-button',\r\n textContent: 'Save (API Format)',\r\n style: { width: '100%', display: 'none' },\r\n onclick: () => {\r\n let filename = 'workflow_api.json'\r\n if (promptFilename.value) {\r\n filename = prompt('Save workflow (API) as:', filename)\r\n if (!filename) return\r\n if (!filename.toLowerCase().endsWith('.json')) {\r\n filename += '.json'\r\n }\r\n }\r\n app.graphToPrompt().then((p) => {\r\n const json = JSON.stringify(p.output, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n })\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-load-button',\r\n textContent: 'Load',\r\n onclick: () => fileInput.click()\r\n }),\r\n $el('button', {\r\n id: 'comfy-refresh-button',\r\n textContent: 'Refresh',\r\n onclick: () => app.refreshComboInNodes()\r\n }),\r\n $el('button', {\r\n id: 'comfy-clipspace-button',\r\n textContent: 'Clipspace',\r\n onclick: () => app.openClipspace()\r\n }),\r\n $el('button', {\r\n id: 'comfy-clear-button',\r\n textContent: 'Clear',\r\n onclick: () => {\r\n if (!confirmClear.value || confirm('Clear workflow?')) {\r\n app.clean()\r\n app.graph.clear()\r\n app.resetView()\r\n api.dispatchEvent(new CustomEvent('graphCleared'))\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-load-default-button',\r\n textContent: 'Load Default',\r\n onclick: async () => {\r\n if (!confirmClear.value || confirm('Load default workflow?')) {\r\n app.resetView()\r\n await app.loadGraphData()\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-reset-view-button',\r\n textContent: 'Reset View',\r\n onclick: async () => {\r\n app.resetView()\r\n }\r\n })\r\n ]) as HTMLDivElement\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.DevMode',\r\n name: 'Enable dev mode options (API save, etc.)',\r\n type: 'boolean',\r\n defaultValue: false,\r\n onChange: function (value) {\r\n document.getElementById('comfy-dev-save-api-button').style.display =\r\n value ? 'flex' : 'none'\r\n }\r\n })\r\n\r\n this.restoreMenuPosition = dragElement(this.menuContainer, this.settings)\r\n\r\n this.setStatus({ exec_info: { queue_remaining: 'X' } })\r\n }\r\n\r\n setStatus(status) {\r\n this.queueSize.textContent =\r\n 'Queue size: ' + (status ? status.exec_info.queue_remaining : 'ERR')\r\n if (status) {\r\n if (\r\n this.lastQueueSize != 0 &&\r\n status.exec_info.queue_remaining == 0 &&\r\n this.autoQueueEnabled &&\r\n (this.autoQueueMode === 'instant' || this.graphHasChanged) &&\r\n !app.lastExecutionError\r\n ) {\r\n app.queuePrompt(0, this.batchCount)\r\n status.exec_info.queue_remaining += this.batchCount\r\n this.graphHasChanged = false\r\n }\r\n this.lastQueueSize = status.exec_info.queue_remaining\r\n }\r\n }\r\n}\r\n","import { $el, ComfyDialog } from './ui'\r\nimport { api } from './api'\r\nimport type { ComfyApp } from './app'\r\n\r\n$el('style', {\r\n textContent: `\r\n .comfy-logging-logs {\r\n display: grid;\r\n color: var(--fg-color);\r\n white-space: pre-wrap;\r\n }\r\n .comfy-logging-log {\r\n display: contents;\r\n }\r\n .comfy-logging-title {\r\n background: var(--tr-even-bg-color);\r\n font-weight: bold;\r\n margin-bottom: 5px;\r\n text-align: center;\r\n }\r\n .comfy-logging-log div {\r\n background: var(--row-bg);\r\n padding: 5px;\r\n }\r\n `,\r\n parent: document.body\r\n})\r\n\r\n// Stringify function supporting max depth and removal of circular references\r\n// https://stackoverflow.com/a/57193345\r\nfunction stringify(val, depth, replacer, space, onGetObjID?) {\r\n depth = isNaN(+depth) ? 1 : depth\r\n var recursMap = new WeakMap()\r\n function _build(val, depth, o?, a?, r?) {\r\n // (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)\r\n return !val || typeof val != 'object'\r\n ? val\r\n : ((r = recursMap.has(val)),\r\n recursMap.set(val, true),\r\n (a = Array.isArray(val)),\r\n r\r\n ? (o = (onGetObjID && onGetObjID(val)) || null)\r\n : JSON.stringify(val, function (k, v) {\r\n if (a || depth > 0) {\r\n if (replacer) v = replacer(k, v)\r\n if (!k) return (a = Array.isArray(v)), (val = v)\r\n !o && (o = a ? [] : {})\r\n o[k] = _build(v, a ? depth : depth - 1)\r\n }\r\n }),\r\n o === void 0 ? (a ? [] : {}) : o)\r\n }\r\n return JSON.stringify(_build(val, depth), null, space)\r\n}\r\n\r\nconst jsonReplacer = (k, v, ui) => {\r\n if (v instanceof Array && v.length === 1) {\r\n v = v[0]\r\n }\r\n if (v instanceof Date) {\r\n v = v.toISOString()\r\n if (ui) {\r\n v = v.split('T')[1]\r\n }\r\n }\r\n if (v instanceof Error) {\r\n let err = ''\r\n if (v.name) err += v.name + '\\n'\r\n if (v.message) err += v.message + '\\n'\r\n if (v.stack) err += v.stack + '\\n'\r\n if (!err) {\r\n err = v.toString()\r\n }\r\n v = err\r\n }\r\n return v\r\n}\r\n\r\nconst fileInput: HTMLInputElement = $el('input', {\r\n type: 'file',\r\n accept: '.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n}) as HTMLInputElement\r\n\r\nclass ComfyLoggingDialog extends ComfyDialog {\r\n logging: any\r\n\r\n constructor(logging) {\r\n super()\r\n this.logging = logging\r\n }\r\n\r\n clear() {\r\n this.logging.clear()\r\n this.show()\r\n }\r\n\r\n export() {\r\n const blob = new Blob(\r\n [stringify([...this.logging.entries], 20, jsonReplacer, '\\t')],\r\n {\r\n type: 'application/json'\r\n }\r\n )\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: `comfyui-logs-${Date.now()}.json`,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n\r\n import() {\r\n fileInput.onchange = () => {\r\n const reader = new FileReader()\r\n reader.onload = () => {\r\n fileInput.remove()\r\n try {\r\n const obj = JSON.parse(reader.result as string)\r\n if (obj instanceof Array) {\r\n this.show(obj)\r\n } else {\r\n throw new Error('Invalid file selected.')\r\n }\r\n } catch (error) {\r\n alert('Unable to load logs: ' + error.message)\r\n }\r\n }\r\n reader.readAsText(fileInput.files[0])\r\n }\r\n fileInput.click()\r\n }\r\n\r\n createButtons() {\r\n return [\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Clear',\r\n onclick: () => this.clear()\r\n }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Export logs...',\r\n onclick: () => this.export()\r\n }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'View exported logs...',\r\n onclick: () => this.import()\r\n }),\r\n ...super.createButtons()\r\n ]\r\n }\r\n\r\n getTypeColor(type) {\r\n switch (type) {\r\n case 'error':\r\n return 'red'\r\n case 'warn':\r\n return 'orange'\r\n case 'debug':\r\n return 'dodgerblue'\r\n }\r\n }\r\n\r\n show(entries?: any[]) {\r\n if (!entries) entries = this.logging.entries\r\n this.element.style.width = '100%'\r\n const cols = {\r\n source: 'Source',\r\n type: 'Type',\r\n timestamp: 'Timestamp',\r\n message: 'Message'\r\n }\r\n const keys = Object.keys(cols)\r\n const headers = Object.values(cols).map((title) =>\r\n $el('div.comfy-logging-title', {\r\n textContent: title\r\n })\r\n )\r\n const rows = entries.map((entry, i) => {\r\n return $el(\r\n 'div.comfy-logging-log',\r\n {\r\n $: (el) =>\r\n el.style.setProperty(\r\n '--row-bg',\r\n `var(--tr-${i % 2 ? 'even' : 'odd'}-bg-color)`\r\n )\r\n },\r\n keys.map((key) => {\r\n let v = entry[key]\r\n let color\r\n if (key === 'type') {\r\n color = this.getTypeColor(v)\r\n } else {\r\n v = jsonReplacer(key, v, true)\r\n\r\n if (typeof v === 'object') {\r\n v = stringify(v, 5, jsonReplacer, ' ')\r\n }\r\n }\r\n\r\n return $el('div', {\r\n style: {\r\n color\r\n },\r\n textContent: v\r\n })\r\n })\r\n )\r\n })\r\n\r\n const grid = $el(\r\n 'div.comfy-logging-logs',\r\n {\r\n style: {\r\n gridTemplateColumns: `repeat(${headers.length}, 1fr)`\r\n }\r\n },\r\n [...headers, ...rows]\r\n )\r\n const els = [grid]\r\n if (!this.logging.enabled) {\r\n els.unshift(\r\n $el('h3', {\r\n style: { textAlign: 'center' },\r\n textContent: 'Logging is disabled'\r\n })\r\n )\r\n }\r\n super.show($el('div', els))\r\n }\r\n}\r\n\r\nexport class ComfyLogging {\r\n /**\r\n * @type Array<{ source: string, type: string, timestamp: Date, message: any }>\r\n */\r\n entries = []\r\n\r\n #enabled\r\n #console = {}\r\n\r\n app: ComfyApp\r\n dialog: ComfyLoggingDialog\r\n\r\n get enabled() {\r\n return this.#enabled\r\n }\r\n\r\n set enabled(value) {\r\n if (value === this.#enabled) return\r\n if (value) {\r\n this.patchConsole()\r\n } else {\r\n this.unpatchConsole()\r\n }\r\n this.#enabled = value\r\n }\r\n\r\n constructor(app) {\r\n this.app = app\r\n\r\n this.dialog = new ComfyLoggingDialog(this)\r\n this.addSetting()\r\n this.catchUnhandled()\r\n this.addInitData()\r\n }\r\n\r\n addSetting() {\r\n const settingId: string = 'Comfy.Logging.Enabled'\r\n const htmlSettingId = settingId.replaceAll('.', '-')\r\n const setting = this.app.ui.settings.addSetting({\r\n id: settingId,\r\n name: settingId,\r\n defaultValue: true,\r\n onChange: (value) => {\r\n this.enabled = value\r\n },\r\n type: (name, setter, value) => {\r\n return $el('tr', [\r\n $el('td', [\r\n $el('label', {\r\n textContent: 'Logging',\r\n for: htmlSettingId\r\n })\r\n ]),\r\n $el('td', [\r\n $el('input', {\r\n id: htmlSettingId,\r\n type: 'checkbox',\r\n checked: value,\r\n onchange: (event) => {\r\n setter(event.target.checked)\r\n }\r\n }),\r\n $el('button', {\r\n textContent: 'View Logs',\r\n onclick: () => {\r\n this.app.ui.settings.element.close()\r\n this.dialog.show()\r\n },\r\n style: {\r\n fontSize: '14px',\r\n display: 'block',\r\n marginTop: '5px'\r\n }\r\n })\r\n ])\r\n ])\r\n }\r\n })\r\n this.enabled = setting.value\r\n }\r\n\r\n patchConsole() {\r\n // Capture common console outputs\r\n const self = this\r\n for (const type of ['log', 'warn', 'error', 'debug']) {\r\n const orig = console[type]\r\n this.#console[type] = orig\r\n console[type] = function () {\r\n orig.apply(console, arguments)\r\n self.addEntry('console', type, ...arguments)\r\n }\r\n }\r\n }\r\n\r\n unpatchConsole() {\r\n // Restore original console functions\r\n for (const type of Object.keys(this.#console)) {\r\n console[type] = this.#console[type]\r\n }\r\n this.#console = {}\r\n }\r\n\r\n catchUnhandled() {\r\n // Capture uncaught errors\r\n window.addEventListener('error', (e) => {\r\n this.addEntry('window', 'error', e.error ?? 'Unknown error')\r\n return false\r\n })\r\n\r\n window.addEventListener('unhandledrejection', (e) => {\r\n this.addEntry('unhandledrejection', 'error', e.reason ?? 'Unknown error')\r\n })\r\n }\r\n\r\n clear() {\r\n this.entries = []\r\n }\r\n\r\n addEntry(source, type, ...args) {\r\n if (this.enabled) {\r\n this.entries.push({\r\n source,\r\n type,\r\n timestamp: new Date(),\r\n message: args\r\n })\r\n }\r\n }\r\n\r\n log(source, ...args) {\r\n this.addEntry(source, 'log', ...args)\r\n }\r\n\r\n async addInitData() {\r\n if (!this.enabled) return\r\n const source = 'ComfyUI.Logging'\r\n this.addEntry(source, 'debug', { UserAgent: navigator.userAgent })\r\n const systemStats = await api.getSystemStats()\r\n this.addEntry(source, 'debug', systemStats)\r\n }\r\n}\r\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nconst globalExport = {};\n(function(globalThis) {\n var LiteGraph = globalThis.LiteGraph = {\n VERSION: 0.4,\n CANVAS_GRID_SIZE: 10,\n NODE_TITLE_HEIGHT: 30,\n NODE_TITLE_TEXT_Y: 20,\n NODE_SLOT_HEIGHT: 20,\n NODE_WIDGET_HEIGHT: 20,\n NODE_WIDTH: 140,\n NODE_MIN_WIDTH: 50,\n NODE_COLLAPSED_RADIUS: 10,\n NODE_COLLAPSED_WIDTH: 80,\n NODE_TITLE_COLOR: \"#999\",\n NODE_SELECTED_TITLE_COLOR: \"#FFF\",\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: \"#AAA\",\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: \"#333\",\n NODE_DEFAULT_BGCOLOR: \"#353535\",\n NODE_DEFAULT_BOXCOLOR: \"#666\",\n NODE_DEFAULT_SHAPE: \"box\",\n NODE_BOX_OUTLINE_COLOR: \"#FFF\",\n DEFAULT_SHADOW_COLOR: \"rgba(0,0,0,0.5)\",\n DEFAULT_GROUP_FONT: 24,\n WIDGET_BGCOLOR: \"#222\",\n WIDGET_OUTLINE_COLOR: \"#666\",\n WIDGET_TEXT_COLOR: \"#DDD\",\n WIDGET_SECONDARY_TEXT_COLOR: \"#999\",\n LINK_COLOR: \"#9A9\",\n EVENT_LINK_COLOR: \"#A86\",\n CONNECTING_LINK_COLOR: \"#AFA\",\n MAX_NUMBER_OF_NODES: 1e4,\n //avoid infinite loops\n DEFAULT_POSITION: [100, 100],\n //default node position\n VALID_SHAPES: [\"default\", \"box\", \"round\", \"card\"],\n //,\"circle\"\n //shapes are used for nodes but also for slots\n BOX_SHAPE: 1,\n ROUND_SHAPE: 2,\n CIRCLE_SHAPE: 3,\n CARD_SHAPE: 4,\n ARROW_SHAPE: 5,\n GRID_SHAPE: 6,\n // intended for slot arrays\n //enums\n INPUT: 1,\n OUTPUT: 2,\n EVENT: -1,\n //for outputs\n ACTION: -1,\n //for inputs\n NODE_MODES: [\"Always\", \"On Event\", \"Never\", \"On Trigger\"],\n // helper, will add \"On Request\" and more in the future\n NODE_MODES_COLORS: [\"#666\", \"#422\", \"#333\", \"#224\", \"#626\"],\n // use with node_box_coloured_by_mode\n ALWAYS: 0,\n ON_EVENT: 1,\n NEVER: 2,\n ON_TRIGGER: 3,\n UP: 1,\n DOWN: 2,\n LEFT: 3,\n RIGHT: 4,\n CENTER: 5,\n LINK_RENDER_MODES: [\"Straight\", \"Linear\", \"Spline\"],\n // helper\n STRAIGHT_LINK: 0,\n LINEAR_LINK: 1,\n SPLINE_LINK: 2,\n NORMAL_TITLE: 0,\n NO_TITLE: 1,\n TRANSPARENT_TITLE: 2,\n AUTOHIDE_TITLE: 3,\n VERTICAL_LAYOUT: \"vertical\",\n // arrange nodes vertically\n proxy: null,\n //used to redirect calls\n node_images_path: \"\",\n debug: false,\n catch_exceptions: true,\n throw_errors: true,\n allow_scripts: false,\n //if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits\n registered_node_types: {},\n //nodetypes by string\n node_types_by_file_extension: {},\n //used for dropping files in the canvas\n Nodes: {},\n //node types by classname\n Globals: {},\n //used to store vars between graphs\n searchbox_extras: {},\n //used to add extra features to the search box\n auto_sort_node_types: false,\n // [true!] If set to true, will automatically sort node types / categories in the context menus\n node_box_coloured_when_on: false,\n // [true!] this make the nodes box (top left circle) coloured when triggered (execute/action), visual feedback\n node_box_coloured_by_mode: false,\n // [true!] nodebox based on node mode, visual feedback\n dialog_close_on_mouse_leave: false,\n // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false\n dialog_close_on_mouse_leave_delay: 500,\n shift_click_do_break_link_from: false,\n // [false!] prefer false if results too easy to break links - implement with ALT or TODO custom keys\n click_do_break_link_to: false,\n // [false!]prefer false, way too easy to break links\n ctrl_alt_click_do_break_link: true,\n // [true!] who accidentally ctrl-alt-clicks on an in/output? nobody! that's who!\n search_hide_on_mouse_leave: true,\n // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false\n search_filter_enabled: false,\n // [true!] enable filtering slots type in the search widget, !requires auto_load_slot_types or manual set registered_slot_[in/out]_types and slot_types_[in/out]\n search_show_all_on_open: true,\n // [true!] opens the results list when opening the search widget\n auto_load_slot_types: false,\n // [if want false, use true, run, get vars values to be statically set, than disable] nodes types and nodeclass association with node types need to be calculated, if dont want this, calculate once and set registered_slot_[in/out]_types and slot_types_[in/out]\n // set these values if not using auto_load_slot_types\n registered_slot_in_types: {},\n // slot types for nodeclass\n registered_slot_out_types: {},\n // slot types for nodeclass\n slot_types_in: [],\n // slot types IN\n slot_types_out: [],\n // slot types OUT\n slot_types_default_in: [],\n // specify for each IN slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search\n slot_types_default_out: [],\n // specify for each OUT slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search\n alt_drag_do_clone_nodes: false,\n // [true!] very handy, ALT click to clone and drag the new node\n do_add_triggers_slots: false,\n // [true!] will create and connect event slots when using action/events connections, !WILL CHANGE node mode when using onTrigger (enable mode colors), onExecuted does not need this\n allow_multi_output_for_events: true,\n // [false!] being events, it is strongly reccomended to use them sequentially, one by one\n middle_click_slot_add_default_node: false,\n //[true!] allows to create and connect a ndoe clicking with the third button (wheel)\n release_link_on_empty_shows_menu: false,\n //[true!] dragging a link to empty space will open a menu, add from list, search or defaults\n pointerevents_method: \"pointer\",\n // \"mouse\"|\"pointer\" use mouse for retrocompatibility issues? (none found @ now)\n // TODO implement pointercancel, gotpointercapture, lostpointercapture, (pointerover, pointerout if necessary)\n ctrl_shift_v_paste_connect_unselected_outputs: true,\n //[true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected with the inputs of the newly pasted nodes\n // if true, all newly created nodes/links will use string UUIDs for their id fields instead of integers.\n // use this if you must have node IDs that are unique across all graphs and subgraphs.\n use_uuids: false,\n /**\n * Register a node class so it can be listed when the user wants to create a new one\n * @method registerNodeType\n * @param {String} type name of the node and path\n * @param {Class} base_class class containing the structure of a node\n */\n registerNodeType: function(type, base_class) {\n if (!base_class.prototype) {\n throw \"Cannot register a simple object, it must be a class with a prototype\";\n }\n base_class.type = type;\n if (LiteGraph.debug) {\n console.log(\"Node registered: \" + type);\n }\n const classname = base_class.name;\n const pos2 = type.lastIndexOf(\"/\");\n base_class.category = type.substring(0, pos2);\n if (!base_class.title) {\n base_class.title = classname;\n }\n for (var i2 in LGraphNode.prototype) {\n if (!base_class.prototype[i2]) {\n base_class.prototype[i2] = LGraphNode.prototype[i2];\n }\n }\n const prev = this.registered_node_types[type];\n if (prev) {\n console.log(\"replacing node type: \" + type);\n }\n if (!Object.prototype.hasOwnProperty.call(base_class.prototype, \"shape\")) {\n Object.defineProperty(base_class.prototype, \"shape\", {\n set: function(v2) {\n switch (v2) {\n case \"default\":\n delete this._shape;\n break;\n case \"box\":\n this._shape = LiteGraph.BOX_SHAPE;\n break;\n case \"round\":\n this._shape = LiteGraph.ROUND_SHAPE;\n break;\n case \"circle\":\n this._shape = LiteGraph.CIRCLE_SHAPE;\n break;\n case \"card\":\n this._shape = LiteGraph.CARD_SHAPE;\n break;\n default:\n this._shape = v2;\n }\n },\n get: function() {\n return this._shape;\n },\n enumerable: true,\n configurable: true\n });\n if (base_class.supported_extensions) {\n for (let i3 in base_class.supported_extensions) {\n const ext = base_class.supported_extensions[i3];\n if (ext && ext.constructor === String) {\n this.node_types_by_file_extension[ext.toLowerCase()] = base_class;\n }\n }\n }\n }\n this.registered_node_types[type] = base_class;\n if (base_class.constructor.name) {\n this.Nodes[classname] = base_class;\n }\n if (LiteGraph.onNodeTypeRegistered) {\n LiteGraph.onNodeTypeRegistered(type, base_class);\n }\n if (prev && LiteGraph.onNodeTypeReplaced) {\n LiteGraph.onNodeTypeReplaced(type, base_class, prev);\n }\n if (base_class.prototype.onPropertyChange) {\n console.warn(\n \"LiteGraph node class \" + type + \" has onPropertyChange method, it must be called onPropertyChanged with d at the end\"\n );\n }\n if (this.auto_load_slot_types) {\n new base_class(base_class.title || \"tmpnode\");\n }\n },\n /**\n * removes a node type from the system\n * @method unregisterNodeType\n * @param {String|Object} type name of the node or the node constructor itself\n */\n unregisterNodeType: function(type) {\n const base_class = type.constructor === String ? this.registered_node_types[type] : type;\n if (!base_class) {\n throw \"node type not found: \" + type;\n }\n delete this.registered_node_types[base_class.type];\n if (base_class.constructor.name) {\n delete this.Nodes[base_class.constructor.name];\n }\n },\n /**\n * Save a slot type and his node\n * @method registerSlotType\n * @param {String|Object} type name of the node or the node constructor itself\n * @param {String} slot_type name of the slot type (variable type), eg. string, number, array, boolean, ..\n */\n registerNodeAndSlotType: function(type, slot_type, out) {\n out = out || false;\n const base_class = type.constructor === String && this.registered_node_types[type] !== \"anonymous\" ? this.registered_node_types[type] : type;\n const class_type = base_class.constructor.type;\n let allTypes = [];\n if (typeof slot_type === \"string\") {\n allTypes = slot_type.split(\",\");\n } else if (slot_type == this.EVENT || slot_type == this.ACTION) {\n allTypes = [\"_event_\"];\n } else {\n allTypes = [\"*\"];\n }\n for (let i2 = 0; i2 < allTypes.length; ++i2) {\n let slotType = allTypes[i2];\n if (slotType === \"\") {\n slotType = \"*\";\n }\n const registerTo = out ? \"registered_slot_out_types\" : \"registered_slot_in_types\";\n if (this[registerTo][slotType] === void 0) {\n this[registerTo][slotType] = { nodes: [] };\n }\n if (!this[registerTo][slotType].nodes.includes(class_type)) {\n this[registerTo][slotType].nodes.push(class_type);\n }\n if (!out) {\n if (!this.slot_types_in.includes(slotType.toLowerCase())) {\n this.slot_types_in.push(slotType.toLowerCase());\n this.slot_types_in.sort();\n }\n } else {\n if (!this.slot_types_out.includes(slotType.toLowerCase())) {\n this.slot_types_out.push(slotType.toLowerCase());\n this.slot_types_out.sort();\n }\n }\n }\n },\n /**\n * Create a new nodetype by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function.\n * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output.\n * @method wrapFunctionAsNode\n * @param {String} name node name with namespace (p.e.: 'math/sum')\n * @param {Function} func\n * @param {Array} param_types [optional] an array containing the type of every parameter, otherwise parameters will accept any type\n * @param {String} return_type [optional] string with the return type, otherwise it will be generic\n * @param {Object} properties [optional] properties to be configurable\n */\n wrapFunctionAsNode: function(name, func, param_types, return_type, properties) {\n var params = Array(func.length);\n var code = \"\";\n var names = LiteGraph.getParameterNames(func);\n for (var i2 = 0; i2 < names.length; ++i2) {\n code += \"this.addInput('\" + names[i2] + \"',\" + (param_types && param_types[i2] ? \"'\" + param_types[i2] + \"'\" : \"0\") + \");\\n\";\n }\n code += \"this.addOutput('out',\" + (return_type ? \"'\" + return_type + \"'\" : 0) + \");\\n\";\n if (properties) {\n code += \"this.properties = \" + JSON.stringify(properties) + \";\\n\";\n }\n var classobj = Function(code);\n classobj.title = name.split(\"/\").pop();\n classobj.desc = \"Generated from \" + func.name;\n classobj.prototype.onExecute = function onExecute() {\n for (var i3 = 0; i3 < params.length; ++i3) {\n params[i3] = this.getInputData(i3);\n }\n var r = func.apply(this, params);\n this.setOutputData(0, r);\n };\n this.registerNodeType(name, classobj);\n },\n /**\n * Removes all previously registered node's types\n */\n clearRegisteredTypes: function() {\n this.registered_node_types = {};\n this.node_types_by_file_extension = {};\n this.Nodes = {};\n this.searchbox_extras = {};\n },\n /**\n * Adds this method to all nodetypes, existing and to be created\n * (You can add it to LGraphNode.prototype but then existing node types wont have it)\n * @method addNodeMethod\n * @param {Function} func\n */\n addNodeMethod: function(name, func) {\n LGraphNode.prototype[name] = func;\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.prototype[name]) {\n type.prototype[\"_\" + name] = type.prototype[name];\n }\n type.prototype[name] = func;\n }\n },\n /**\n * Create a node of a given type with a name. The node is not attached to any graph yet.\n * @method createNode\n * @param {String} type full name of the node class. p.e. \"math/sin\"\n * @param {String} name a name to distinguish from other nodes\n * @param {Object} options to set options\n */\n createNode: function(type, title, options) {\n var base_class = this.registered_node_types[type];\n if (!base_class) {\n if (LiteGraph.debug) {\n console.log(\n 'GraphNode type \"' + type + '\" not registered.'\n );\n }\n return null;\n }\n base_class.prototype || base_class;\n title = title || base_class.title || type;\n var node2 = null;\n if (LiteGraph.catch_exceptions) {\n try {\n node2 = new base_class(title);\n } catch (err) {\n console.error(err);\n return null;\n }\n } else {\n node2 = new base_class(title);\n }\n node2.type = type;\n if (!node2.title && title) {\n node2.title = title;\n }\n if (!node2.properties) {\n node2.properties = {};\n }\n if (!node2.properties_info) {\n node2.properties_info = [];\n }\n if (!node2.flags) {\n node2.flags = {};\n }\n if (!node2.size) {\n node2.size = node2.computeSize();\n }\n if (!node2.pos) {\n node2.pos = LiteGraph.DEFAULT_POSITION.concat();\n }\n if (!node2.mode) {\n node2.mode = LiteGraph.ALWAYS;\n }\n if (options) {\n for (var i2 in options) {\n node2[i2] = options[i2];\n }\n }\n if (node2.onNodeCreated) {\n node2.onNodeCreated();\n }\n return node2;\n },\n /**\n * Returns a registered node type with a given name\n * @method getNodeType\n * @param {String} type full name of the node class. p.e. \"math/sin\"\n * @return {Class} the node class\n */\n getNodeType: function(type) {\n return this.registered_node_types[type];\n },\n /**\n * Returns a list of node types matching one category\n * @method getNodeType\n * @param {String} category category name\n * @return {Array} array with all the node classes\n */\n getNodeTypesInCategory: function(category, filter) {\n var r = [];\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.filter != filter) {\n continue;\n }\n if (category == \"\") {\n if (type.category == null) {\n r.push(type);\n }\n } else if (type.category == category) {\n r.push(type);\n }\n }\n if (this.auto_sort_node_types) {\n r.sort(function(a, b) {\n return a.title.localeCompare(b.title);\n });\n }\n return r;\n },\n /**\n * Returns a list with all the node type categories\n * @method getNodeTypesCategories\n * @param {String} filter only nodes with ctor.filter equal can be shown\n * @return {Array} array with all the names of the categories\n */\n getNodeTypesCategories: function(filter) {\n var categories = { \"\": 1 };\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.category && !type.skip_list) {\n if (type.filter != filter)\n continue;\n categories[type.category] = 1;\n }\n }\n var result = [];\n for (var i2 in categories) {\n result.push(i2);\n }\n return this.auto_sort_node_types ? result.sort() : result;\n },\n //debug purposes: reloads all the js scripts that matches a wildcard\n reloadNodes: function(folder_wildcard) {\n var tmp = document.getElementsByTagName(\"script\");\n var script_files = [];\n for (var i2 = 0; i2 < tmp.length; i2++) {\n script_files.push(tmp[i2]);\n }\n var docHeadObj = document.getElementsByTagName(\"head\")[0];\n folder_wildcard = document.location.href + folder_wildcard;\n for (var i2 = 0; i2 < script_files.length; i2++) {\n var src = script_files[i2].src;\n if (!src || src.substr(0, folder_wildcard.length) != folder_wildcard) {\n continue;\n }\n try {\n if (LiteGraph.debug) {\n console.log(\"Reloading: \" + src);\n }\n var dynamicScript = document.createElement(\"script\");\n dynamicScript.type = \"text/javascript\";\n dynamicScript.src = src;\n docHeadObj.appendChild(dynamicScript);\n docHeadObj.removeChild(script_files[i2]);\n } catch (err) {\n if (LiteGraph.throw_errors) {\n throw err;\n }\n if (LiteGraph.debug) {\n console.log(\"Error while reloading \" + src);\n }\n }\n }\n if (LiteGraph.debug) {\n console.log(\"Nodes reloaded\");\n }\n },\n //separated just to improve if it doesn't work\n cloneObject: function(obj, target) {\n if (obj == null) {\n return null;\n }\n var r = JSON.parse(JSON.stringify(obj));\n if (!target) {\n return r;\n }\n for (var i2 in r) {\n target[i2] = r[i2];\n }\n return target;\n },\n /*\n * https://gist.github.com/jed/982883?permalink_comment_id=852670#gistcomment-852670\n */\n uuidv4: function() {\n return (\"10000000-1000-4000-8000\" + -1e11).replace(/[018]/g, (a) => (a ^ Math.random() * 16 >> a / 4).toString(16));\n },\n /**\n * Returns if the types of two slots are compatible (taking into account wildcards, etc)\n * @method isValidConnection\n * @param {String} type_a\n * @param {String} type_b\n * @return {Boolean} true if they can be connected\n */\n isValidConnection: function(type_a, type_b) {\n if (type_a == \"\" || type_a === \"*\") type_a = 0;\n if (type_b == \"\" || type_b === \"*\") type_b = 0;\n if (!type_a || !type_b || type_a == type_b || type_a == LiteGraph.EVENT && type_b == LiteGraph.ACTION) {\n return true;\n }\n type_a = String(type_a);\n type_b = String(type_b);\n type_a = type_a.toLowerCase();\n type_b = type_b.toLowerCase();\n if (type_a.indexOf(\",\") == -1 && type_b.indexOf(\",\") == -1) {\n return type_a == type_b;\n }\n var supported_types_a = type_a.split(\",\");\n var supported_types_b = type_b.split(\",\");\n for (var i2 = 0; i2 < supported_types_a.length; ++i2) {\n for (var j = 0; j < supported_types_b.length; ++j) {\n if (this.isValidConnection(supported_types_a[i2], supported_types_b[j])) {\n return true;\n }\n }\n }\n return false;\n },\n /**\n * Register a string in the search box so when the user types it it will recommend this node\n * @method registerSearchboxExtra\n * @param {String} node_type the node recommended\n * @param {String} description text to show next to it\n * @param {Object} data it could contain info of how the node should be configured\n * @return {Boolean} true if they can be connected\n */\n registerSearchboxExtra: function(node_type, description, data) {\n this.searchbox_extras[description.toLowerCase()] = {\n type: node_type,\n desc: description,\n data\n };\n },\n /**\n * Wrapper to load files (from url using fetch or from file using FileReader)\n * @method fetchFile\n * @param {String|File|Blob} url the url of the file (or the file itself)\n * @param {String} type an string to know how to fetch it: \"text\",\"arraybuffer\",\"json\",\"blob\"\n * @param {Function} on_complete callback(data)\n * @param {Function} on_error in case of an error\n * @return {FileReader|Promise} returns the object used to \n */\n fetchFile: function(url, type, on_complete, on_error) {\n if (!url)\n return null;\n type = type || \"text\";\n if (url.constructor === String) {\n if (url.substr(0, 4) == \"http\" && LiteGraph.proxy) {\n url = LiteGraph.proxy + url.substr(url.indexOf(\":\") + 3);\n }\n return fetch(url).then(function(response) {\n if (!response.ok)\n throw new Error(\"File not found\");\n if (type == \"arraybuffer\")\n return response.arrayBuffer();\n else if (type == \"text\" || type == \"string\")\n return response.text();\n else if (type == \"json\")\n return response.json();\n else if (type == \"blob\")\n return response.blob();\n }).then(function(data) {\n if (on_complete)\n on_complete(data);\n }).catch(function(error) {\n console.error(\"error fetching file:\", url);\n if (on_error)\n on_error(error);\n });\n } else if (url.constructor === File || url.constructor === Blob) {\n var reader = new FileReader();\n reader.onload = function(e) {\n var v2 = e.target.result;\n if (type == \"json\")\n v2 = JSON.parse(v2);\n if (on_complete)\n on_complete(v2);\n };\n if (type == \"arraybuffer\")\n return reader.readAsArrayBuffer(url);\n else if (type == \"text\" || type == \"json\")\n return reader.readAsText(url);\n else if (type == \"blob\")\n return reader.readAsBinaryString(url);\n }\n return null;\n }\n };\n if (typeof performance != \"undefined\") {\n LiteGraph.getTime = performance.now.bind(performance);\n } else if (typeof Date != \"undefined\" && Date.now) {\n LiteGraph.getTime = Date.now.bind(Date);\n } else if (typeof process != \"undefined\") {\n LiteGraph.getTime = function() {\n var t = process.hrtime();\n return t[0] * 1e-3 + t[1] * 1e-6;\n };\n } else {\n LiteGraph.getTime = function getTime() {\n return (/* @__PURE__ */ new Date()).getTime();\n };\n }\n const _LGraph = class _LGraph {\n constructor(o) {\n if (LiteGraph.debug) {\n console.log(\"Graph created\");\n }\n this.list_of_graphcanvas = null;\n this.clear();\n if (o) {\n this.configure(o);\n }\n }\n //used to know which types of connections support this graph (some graphs do not allow certain types)\n getSupportedTypes() {\n return this.supported_types || _LGraph.supported_types;\n }\n /**\n * Removes all nodes from this graph\n * @method clear\n */\n clear() {\n this.stop();\n this.status = _LGraph.STATUS_STOPPED;\n this.last_node_id = 0;\n this.last_link_id = 0;\n this._version = -1;\n if (this._nodes) {\n for (var i2 = 0; i2 < this._nodes.length; ++i2) {\n var node2 = this._nodes[i2];\n if (node2.onRemoved) {\n node2.onRemoved();\n }\n }\n }\n this._nodes = [];\n this._nodes_by_id = {};\n this._nodes_in_order = [];\n this._nodes_executable = null;\n this._groups = [];\n this.links = {};\n this.iteration = 0;\n this.config = {};\n this.vars = {};\n this.extra = {};\n this.globaltime = 0;\n this.runningtime = 0;\n this.fixedtime = 0;\n this.fixedtime_lapse = 0.01;\n this.elapsed_time = 0.01;\n this.last_update_time = 0;\n this.starttime = 0;\n this.catch_errors = true;\n this.nodes_executing = [];\n this.nodes_actioning = [];\n this.nodes_executedAction = [];\n this.inputs = {};\n this.outputs = {};\n this.change();\n this.sendActionToCanvas(\"clear\");\n }\n /**\n * Attach Canvas to this graph\n * @method attachCanvas\n * @param {GraphCanvas} graph_canvas\n */\n attachCanvas(graphcanvas) {\n if (graphcanvas.constructor != LGraphCanvas) {\n throw \"attachCanvas expects a LGraphCanvas instance\";\n }\n if (graphcanvas.graph && graphcanvas.graph != this) {\n graphcanvas.graph.detachCanvas(graphcanvas);\n }\n graphcanvas.graph = this;\n if (!this.list_of_graphcanvas) {\n this.list_of_graphcanvas = [];\n }\n this.list_of_graphcanvas.push(graphcanvas);\n }\n /**\n * Detach Canvas from this graph\n * @method detachCanvas\n * @param {GraphCanvas} graph_canvas\n */\n detachCanvas(graphcanvas) {\n if (!this.list_of_graphcanvas) {\n return;\n }\n var pos2 = this.list_of_graphcanvas.indexOf(graphcanvas);\n if (pos2 == -1) {\n return;\n }\n graphcanvas.graph = null;\n this.list_of_graphcanvas.splice(pos2, 1);\n }\n /**\n * Starts running this graph every interval milliseconds.\n * @method start\n * @param {number} interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate\n */\n start(interval) {\n if (this.status == _LGraph.STATUS_RUNNING) {\n return;\n }\n this.status = _LGraph.STATUS_RUNNING;\n if (this.onPlayEvent) {\n this.onPlayEvent();\n }\n this.sendEventToAllNodes(\"onStart\");\n this.starttime = LiteGraph.getTime();\n this.last_update_time = this.starttime;\n interval = interval || 0;\n var that2 = this;\n if (interval == 0 && typeof window != \"undefined\" && window.requestAnimationFrame) {\n let on_frame = function() {\n if (that2.execution_timer_id != -1) {\n return;\n }\n window.requestAnimationFrame(on_frame);\n if (that2.onBeforeStep)\n that2.onBeforeStep();\n that2.runStep(1, !that2.catch_errors);\n if (that2.onAfterStep)\n that2.onAfterStep();\n };\n this.execution_timer_id = -1;\n on_frame();\n } else {\n this.execution_timer_id = setInterval(function() {\n if (that2.onBeforeStep)\n that2.onBeforeStep();\n that2.runStep(1, !that2.catch_errors);\n if (that2.onAfterStep)\n that2.onAfterStep();\n }, interval);\n }\n }\n /**\n * Stops the execution loop of the graph\n * @method stop execution\n */\n stop() {\n if (this.status == _LGraph.STATUS_STOPPED) {\n return;\n }\n this.status = _LGraph.STATUS_STOPPED;\n if (this.onStopEvent) {\n this.onStopEvent();\n }\n if (this.execution_timer_id != null) {\n if (this.execution_timer_id != -1) {\n clearInterval(this.execution_timer_id);\n }\n this.execution_timer_id = null;\n }\n this.sendEventToAllNodes(\"onStop\");\n }\n /**\n * Run N steps (cycles) of the graph\n * @method runStep\n * @param {number} num number of steps to run, default is 1\n * @param {Boolean} do_not_catch_errors [optional] if you want to try/catch errors\n * @param {number} limit max number of nodes to execute (used to execute from start to a node)\n */\n runStep(num, do_not_catch_errors, limit) {\n num = num || 1;\n var start = LiteGraph.getTime();\n this.globaltime = 1e-3 * (start - this.starttime);\n var nodes = this._nodes_executable ? this._nodes_executable : this._nodes;\n if (!nodes) {\n return;\n }\n limit = limit || nodes.length;\n if (do_not_catch_errors) {\n for (var i2 = 0; i2 < num; i2++) {\n for (var j = 0; j < limit; ++j) {\n var node2 = nodes[j];\n if (node2.mode == LiteGraph.ALWAYS && node2.onExecute) {\n node2.doExecute();\n }\n }\n this.fixedtime += this.fixedtime_lapse;\n if (this.onExecuteStep) {\n this.onExecuteStep();\n }\n }\n if (this.onAfterExecute) {\n this.onAfterExecute();\n }\n } else {\n try {\n for (var i2 = 0; i2 < num; i2++) {\n for (var j = 0; j < limit; ++j) {\n var node2 = nodes[j];\n if (node2.mode == LiteGraph.ALWAYS && node2.onExecute) {\n node2.onExecute();\n }\n }\n this.fixedtime += this.fixedtime_lapse;\n if (this.onExecuteStep) {\n this.onExecuteStep();\n }\n }\n if (this.onAfterExecute) {\n this.onAfterExecute();\n }\n this.errors_in_execution = false;\n } catch (err) {\n this.errors_in_execution = true;\n if (LiteGraph.throw_errors) {\n throw err;\n }\n if (LiteGraph.debug) {\n console.log(\"Error during execution: \" + err);\n }\n this.stop();\n }\n }\n var now = LiteGraph.getTime();\n var elapsed = now - start;\n if (elapsed == 0) {\n elapsed = 1;\n }\n this.execution_time = 1e-3 * elapsed;\n this.globaltime += 1e-3 * elapsed;\n this.iteration += 1;\n this.elapsed_time = (now - this.last_update_time) * 1e-3;\n this.last_update_time = now;\n this.nodes_executing = [];\n this.nodes_actioning = [];\n this.nodes_executedAction = [];\n }\n /**\n * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than\n * nodes with only inputs.\n * @method updateExecutionOrder\n */\n updateExecutionOrder() {\n this._nodes_in_order = this.computeExecutionOrder(false);\n this._nodes_executable = [];\n for (var i2 = 0; i2 < this._nodes_in_order.length; ++i2) {\n if (this._nodes_in_order[i2].onExecute) {\n this._nodes_executable.push(this._nodes_in_order[i2]);\n }\n }\n }\n //This is more internal, it computes the executable nodes in order and returns it\n computeExecutionOrder(only_onExecute, set_level) {\n var L = [];\n var S = [];\n var M = {};\n var visited_links = {};\n var remaining_links = {};\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n var node2 = this._nodes[i2];\n if (only_onExecute && !node2.onExecute) {\n continue;\n }\n M[node2.id] = node2;\n var num = 0;\n if (node2.inputs) {\n for (var j = 0, l2 = node2.inputs.length; j < l2; j++) {\n if (node2.inputs[j] && node2.inputs[j].link != null) {\n num += 1;\n }\n }\n }\n if (num == 0) {\n S.push(node2);\n if (set_level) {\n node2._level = 1;\n }\n } else {\n if (set_level) {\n node2._level = 0;\n }\n remaining_links[node2.id] = num;\n }\n }\n while (true) {\n if (S.length == 0) {\n break;\n }\n var node2 = S.shift();\n L.push(node2);\n delete M[node2.id];\n if (!node2.outputs) {\n continue;\n }\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var output = node2.outputs[i2];\n if (output == null || output.links == null || output.links.length == 0) {\n continue;\n }\n for (var j = 0; j < output.links.length; j++) {\n var link_id = output.links[j];\n var link = this.links[link_id];\n if (!link) {\n continue;\n }\n if (visited_links[link.id]) {\n continue;\n }\n var target_node = this.getNodeById(link.target_id);\n if (target_node == null) {\n visited_links[link.id] = true;\n continue;\n }\n if (set_level && (!target_node._level || target_node._level <= node2._level)) {\n target_node._level = node2._level + 1;\n }\n visited_links[link.id] = true;\n remaining_links[target_node.id] -= 1;\n if (remaining_links[target_node.id] == 0) {\n S.push(target_node);\n }\n }\n }\n }\n for (var i2 in M) {\n L.push(M[i2]);\n }\n if (L.length != this._nodes.length && LiteGraph.debug) {\n console.warn(\"something went wrong, nodes missing\");\n }\n var l = L.length;\n for (var i2 = 0; i2 < l; ++i2) {\n L[i2].order = i2;\n }\n L = L.sort(function(A, B) {\n var Ap = A.constructor.priority || A.priority || 0;\n var Bp = B.constructor.priority || B.priority || 0;\n if (Ap == Bp) {\n return A.order - B.order;\n }\n return Ap - Bp;\n });\n for (var i2 = 0; i2 < l; ++i2) {\n L[i2].order = i2;\n }\n return L;\n }\n /**\n * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively.\n * It doesn't include the node itself\n * @method getAncestors\n * @return {Array} an array with all the LGraphNodes that affect this node, in order of execution\n */\n getAncestors(node2) {\n var ancestors = [];\n var pending = [node2];\n var visited = {};\n while (pending.length) {\n var current = pending.shift();\n if (!current.inputs) {\n continue;\n }\n if (!visited[current.id] && current != node2) {\n visited[current.id] = true;\n ancestors.push(current);\n }\n for (var i2 = 0; i2 < current.inputs.length; ++i2) {\n var input = current.getInputNode(i2);\n if (input && ancestors.indexOf(input) == -1) {\n pending.push(input);\n }\n }\n }\n ancestors.sort(function(a, b) {\n return a.order - b.order;\n });\n return ancestors;\n }\n /**\n * Positions every node in a more readable manner\n * @method arrange\n */\n arrange(margin, layout) {\n margin = margin || 100;\n const nodes = this.computeExecutionOrder(false, true);\n const columns = [];\n for (let i2 = 0; i2 < nodes.length; ++i2) {\n const node2 = nodes[i2];\n const col = node2._level || 1;\n if (!columns[col]) {\n columns[col] = [];\n }\n columns[col].push(node2);\n }\n let x2 = margin;\n for (let i2 = 0; i2 < columns.length; ++i2) {\n const column = columns[i2];\n if (!column) {\n continue;\n }\n let max_size = 100;\n let y2 = margin + LiteGraph.NODE_TITLE_HEIGHT;\n for (let j = 0; j < column.length; ++j) {\n const node2 = column[j];\n node2.pos[0] = layout == LiteGraph.VERTICAL_LAYOUT ? y2 : x2;\n node2.pos[1] = layout == LiteGraph.VERTICAL_LAYOUT ? x2 : y2;\n const max_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 1 : 0;\n if (node2.size[max_size_index] > max_size) {\n max_size = node2.size[max_size_index];\n }\n const node_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 0 : 1;\n y2 += node2.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT;\n }\n x2 += max_size + margin;\n }\n this.setDirtyCanvas(true, true);\n }\n /**\n * Returns the amount of time the graph has been running in milliseconds\n * @method getTime\n * @return {number} number of milliseconds the graph has been running\n */\n getTime() {\n return this.globaltime;\n }\n /**\n * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant\n * @method getFixedTime\n * @return {number} number of milliseconds the graph has been running\n */\n getFixedTime() {\n return this.fixedtime;\n }\n /**\n * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct\n * if the nodes are using graphical actions\n * @method getElapsedTime\n * @return {number} number of milliseconds it took the last cycle\n */\n getElapsedTime() {\n return this.elapsed_time;\n }\n /**\n * Sends an event to all the nodes, useful to trigger stuff\n * @method sendEventToAllNodes\n * @param {String} eventname the name of the event (function to be called)\n * @param {Array} params parameters in array format\n */\n sendEventToAllNodes(eventname, params, mode) {\n mode = mode || LiteGraph.ALWAYS;\n var nodes = this._nodes_in_order ? this._nodes_in_order : this._nodes;\n if (!nodes) {\n return;\n }\n for (var j = 0, l = nodes.length; j < l; ++j) {\n var node2 = nodes[j];\n if (node2.constructor === LiteGraph.Subgraph && eventname != \"onExecute\") {\n if (node2.mode == mode) {\n node2.sendEventToAllNodes(eventname, params, mode);\n }\n continue;\n }\n if (!node2[eventname] || node2.mode != mode) {\n continue;\n }\n if (params === void 0) {\n node2[eventname]();\n } else if (params && params.constructor === Array) {\n node2[eventname].apply(node2, params);\n } else {\n node2[eventname](params);\n }\n }\n }\n sendActionToCanvas(action, params) {\n if (!this.list_of_graphcanvas) {\n return;\n }\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var c = this.list_of_graphcanvas[i2];\n if (c[action]) {\n c[action].apply(c, params);\n }\n }\n }\n /**\n * Adds a new node instance to this graph\n * @method add\n * @param {LGraphNode} node the instance of the node\n */\n add(node2, skip_compute_order) {\n if (!node2) {\n return;\n }\n if (node2.constructor === LGraphGroup) {\n this._groups.push(node2);\n this.setDirtyCanvas(true);\n this.change();\n node2.graph = this;\n this._version++;\n return;\n }\n if (node2.id != -1 && this._nodes_by_id[node2.id] != null) {\n console.warn(\n \"LiteGraph: there is already a node with this ID, changing it\"\n );\n if (LiteGraph.use_uuids) {\n node2.id = LiteGraph.uuidv4();\n } else {\n node2.id = ++this.last_node_id;\n }\n }\n if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) {\n throw \"LiteGraph: max number of nodes in a graph reached\";\n }\n if (LiteGraph.use_uuids) {\n if (node2.id == null || node2.id == -1)\n node2.id = LiteGraph.uuidv4();\n } else {\n if (node2.id == null || node2.id == -1) {\n node2.id = ++this.last_node_id;\n } else if (this.last_node_id < node2.id) {\n this.last_node_id = node2.id;\n }\n }\n node2.graph = this;\n this._version++;\n this._nodes.push(node2);\n this._nodes_by_id[node2.id] = node2;\n if (node2.onAdded) {\n node2.onAdded(this);\n }\n if (this.config.align_to_grid) {\n node2.alignToGrid();\n }\n if (!skip_compute_order) {\n this.updateExecutionOrder();\n }\n if (this.onNodeAdded) {\n this.onNodeAdded(node2);\n }\n this.setDirtyCanvas(true);\n this.change();\n return node2;\n }\n /**\n * Removes a node from the graph\n * @method remove\n * @param {LGraphNode} node the instance of the node\n */\n remove(node2) {\n if (node2.constructor === LiteGraph.LGraphGroup) {\n var index2 = this._groups.indexOf(node2);\n if (index2 != -1) {\n this._groups.splice(index2, 1);\n }\n node2.graph = null;\n this._version++;\n this.setDirtyCanvas(true, true);\n this.change();\n return;\n }\n if (this._nodes_by_id[node2.id] == null) {\n return;\n }\n if (node2.ignore_remove) {\n return;\n }\n this.beforeChange();\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n if (slot.link != null) {\n node2.disconnectInput(i2);\n }\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n if (slot.links != null && slot.links.length) {\n node2.disconnectOutput(i2);\n }\n }\n }\n if (node2.onRemoved) {\n node2.onRemoved();\n }\n node2.graph = null;\n this._version++;\n if (this.list_of_graphcanvas) {\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var canvas = this.list_of_graphcanvas[i2];\n if (canvas.selected_nodes[node2.id]) {\n delete canvas.selected_nodes[node2.id];\n }\n if (canvas.node_dragged == node2) {\n canvas.node_dragged = null;\n }\n }\n }\n var pos2 = this._nodes.indexOf(node2);\n if (pos2 != -1) {\n this._nodes.splice(pos2, 1);\n }\n delete this._nodes_by_id[node2.id];\n if (this.onNodeRemoved) {\n this.onNodeRemoved(node2);\n }\n this.sendActionToCanvas(\"checkPanels\");\n this.setDirtyCanvas(true, true);\n this.afterChange();\n this.change();\n this.updateExecutionOrder();\n }\n /**\n * Returns a node by its id.\n * @method getNodeById\n * @param {Number} id\n */\n getNodeById(id) {\n if (id == null) {\n return null;\n }\n return this._nodes_by_id[id];\n }\n /**\n * Returns a list of nodes that matches a class\n * @method findNodesByClass\n * @param {Class} classObject the class itself (not an string)\n * @return {Array} a list with all the nodes of this type\n */\n findNodesByClass(classObject, result) {\n result = result || [];\n result.length = 0;\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].constructor === classObject) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns a list of nodes that matches a type\n * @method findNodesByType\n * @param {String} type the name of the node type\n * @return {Array} a list with all the nodes of this type\n */\n findNodesByType(type, result) {\n var type = type.toLowerCase();\n result = result || [];\n result.length = 0;\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].type.toLowerCase() == type) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns the first node that matches a name in its title\n * @method findNodeByTitle\n * @param {String} name the name of the node to search\n * @return {Node} the node or null\n */\n findNodeByTitle(title) {\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].title == title) {\n return this._nodes[i2];\n }\n }\n return null;\n }\n /**\n * Returns a list of nodes that matches a name\n * @method findNodesByTitle\n * @param {String} name the name of the node to search\n * @return {Array} a list with all the nodes with this name\n */\n findNodesByTitle(title) {\n var result = [];\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].title == title) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns the top-most node in this position of the canvas\n * @method getNodeOnPos\n * @param {number} x the x coordinate in canvas space\n * @param {number} y the y coordinate in canvas space\n * @param {Array} nodes_list a list with all the nodes to search from, by default is all the nodes in the graph\n * @return {LGraphNode} the node at this position or null\n */\n getNodeOnPos(x2, y2, nodes_list, margin) {\n nodes_list = nodes_list || this._nodes;\n var nRet = null;\n for (var i2 = nodes_list.length - 1; i2 >= 0; i2--) {\n var n = nodes_list[i2];\n var skip_title = n.constructor.title_mode == LiteGraph.NO_TITLE;\n if (n.isPointInside(x2, y2, margin, skip_title)) {\n return n;\n }\n }\n return nRet;\n }\n /**\n * Returns the top-most group in that position\n * @method getGroupOnPos\n * @param {number} x the x coordinate in canvas space\n * @param {number} y the y coordinate in canvas space\n * @return {LGraphGroup} the group or null\n */\n getGroupOnPos(x2, y2) {\n for (var i2 = this._groups.length - 1; i2 >= 0; i2--) {\n var g = this._groups[i2];\n if (g.isPointInside(x2, y2, 2, true)) {\n return g;\n }\n }\n return null;\n }\n /**\n * Checks that the node type matches the node type registered, used when replacing a nodetype by a newer version during execution\n * this replaces the ones using the old version with the new version\n * @method checkNodeTypes\n */\n checkNodeTypes() {\n for (var i2 = 0; i2 < this._nodes.length; i2++) {\n var node2 = this._nodes[i2];\n var ctor = LiteGraph.registered_node_types[node2.type];\n if (node2.constructor == ctor) {\n continue;\n }\n console.log(\"node being replaced by newer version: \" + node2.type);\n var newnode = LiteGraph.createNode(node2.type);\n this._nodes[i2] = newnode;\n newnode.configure(node2.serialize());\n newnode.graph = this;\n this._nodes_by_id[newnode.id] = newnode;\n if (node2.inputs) {\n newnode.inputs = node2.inputs.concat();\n }\n if (node2.outputs) {\n newnode.outputs = node2.outputs.concat();\n }\n }\n this.updateExecutionOrder();\n }\n // ********** GLOBALS *****************\n onAction(action, param, options) {\n this._input_nodes = this.findNodesByClass(\n LiteGraph.GraphInput,\n this._input_nodes\n );\n for (var i2 = 0; i2 < this._input_nodes.length; ++i2) {\n var node2 = this._input_nodes[i2];\n if (node2.properties.name != action) {\n continue;\n }\n node2.actionDo(action, param, options);\n break;\n }\n }\n trigger(action, param) {\n if (this.onTrigger) {\n this.onTrigger(action, param);\n }\n }\n /**\n * Tell this graph it has a global graph input of this type\n * @method addGlobalInput\n * @param {String} name\n * @param {String} type\n * @param {*} value [optional]\n */\n addInput(name, type, value) {\n var input = this.inputs[name];\n if (input) {\n return;\n }\n this.beforeChange();\n this.inputs[name] = { name, type, value };\n this._version++;\n this.afterChange();\n if (this.onInputAdded) {\n this.onInputAdded(name, type);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Assign a data to the global graph input\n * @method setGlobalInputData\n * @param {String} name\n * @param {*} data\n */\n setInputData(name, data) {\n var input = this.inputs[name];\n if (!input) {\n return;\n }\n input.value = data;\n }\n /**\n * Returns the current value of a global graph input\n * @method getInputData\n * @param {String} name\n * @return {*} the data\n */\n getInputData(name) {\n var input = this.inputs[name];\n if (!input) {\n return null;\n }\n return input.value;\n }\n /**\n * Changes the name of a global graph input\n * @method renameInput\n * @param {String} old_name\n * @param {String} new_name\n */\n renameInput(old_name, name) {\n if (name == old_name) {\n return;\n }\n if (!this.inputs[old_name]) {\n return false;\n }\n if (this.inputs[name]) {\n console.error(\"there is already one input with that name\");\n return false;\n }\n this.inputs[name] = this.inputs[old_name];\n delete this.inputs[old_name];\n this._version++;\n if (this.onInputRenamed) {\n this.onInputRenamed(old_name, name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Changes the type of a global graph input\n * @method changeInputType\n * @param {String} name\n * @param {String} type\n */\n changeInputType(name, type) {\n if (!this.inputs[name]) {\n return false;\n }\n if (this.inputs[name].type && String(this.inputs[name].type).toLowerCase() == String(type).toLowerCase()) {\n return;\n }\n this.inputs[name].type = type;\n this._version++;\n if (this.onInputTypeChanged) {\n this.onInputTypeChanged(name, type);\n }\n }\n /**\n * Removes a global graph input\n * @method removeInput\n * @param {String} name\n * @param {String} type\n */\n removeInput(name) {\n if (!this.inputs[name]) {\n return false;\n }\n delete this.inputs[name];\n this._version++;\n if (this.onInputRemoved) {\n this.onInputRemoved(name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n return true;\n }\n /**\n * Creates a global graph output\n * @method addOutput\n * @param {String} name\n * @param {String} type\n * @param {*} value\n */\n addOutput(name, type, value) {\n this.outputs[name] = { name, type, value };\n this._version++;\n if (this.onOutputAdded) {\n this.onOutputAdded(name, type);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Assign a data to the global output\n * @method setOutputData\n * @param {String} name\n * @param {String} value\n */\n setOutputData(name, value) {\n var output = this.outputs[name];\n if (!output) {\n return;\n }\n output.value = value;\n }\n /**\n * Returns the current value of a global graph output\n * @method getOutputData\n * @param {String} name\n * @return {*} the data\n */\n getOutputData(name) {\n var output = this.outputs[name];\n if (!output) {\n return null;\n }\n return output.value;\n }\n /**\n * Renames a global graph output\n * @method renameOutput\n * @param {String} old_name\n * @param {String} new_name\n */\n renameOutput(old_name, name) {\n if (!this.outputs[old_name]) {\n return false;\n }\n if (this.outputs[name]) {\n console.error(\"there is already one output with that name\");\n return false;\n }\n this.outputs[name] = this.outputs[old_name];\n delete this.outputs[old_name];\n this._version++;\n if (this.onOutputRenamed) {\n this.onOutputRenamed(old_name, name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Changes the type of a global graph output\n * @method changeOutputType\n * @param {String} name\n * @param {String} type\n */\n changeOutputType(name, type) {\n if (!this.outputs[name]) {\n return false;\n }\n if (this.outputs[name].type && String(this.outputs[name].type).toLowerCase() == String(type).toLowerCase()) {\n return;\n }\n this.outputs[name].type = type;\n this._version++;\n if (this.onOutputTypeChanged) {\n this.onOutputTypeChanged(name, type);\n }\n }\n /**\n * Removes a global graph output\n * @method removeOutput\n * @param {String} name\n */\n removeOutput(name) {\n if (!this.outputs[name]) {\n return false;\n }\n delete this.outputs[name];\n this._version++;\n if (this.onOutputRemoved) {\n this.onOutputRemoved(name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n return true;\n }\n triggerInput(name, value) {\n var nodes = this.findNodesByTitle(name);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].onTrigger(value);\n }\n }\n setCallback(name, func) {\n var nodes = this.findNodesByTitle(name);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].setTrigger(func);\n }\n }\n //used for undo, called before any change is made to the graph\n beforeChange(info) {\n if (this.onBeforeChange) {\n this.onBeforeChange(this, info);\n }\n this.sendActionToCanvas(\"onBeforeChange\", this);\n }\n //used to resend actions, called after any change is made to the graph\n afterChange(info) {\n if (this.onAfterChange) {\n this.onAfterChange(this, info);\n }\n this.sendActionToCanvas(\"onAfterChange\", this);\n }\n connectionChange(node2, link_info) {\n this.updateExecutionOrder();\n if (this.onConnectionChange) {\n this.onConnectionChange(node2);\n }\n this._version++;\n this.sendActionToCanvas(\"onConnectionChange\");\n }\n /**\n * returns if the graph is in live mode\n * @method isLive\n */\n isLive() {\n if (!this.list_of_graphcanvas) {\n return false;\n }\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var c = this.list_of_graphcanvas[i2];\n if (c.live_mode) {\n return true;\n }\n }\n return false;\n }\n /**\n * clears the triggered slot animation in all links (stop visual animation)\n * @method clearTriggeredSlots\n */\n clearTriggeredSlots() {\n for (var i2 in this.links) {\n var link_info = this.links[i2];\n if (!link_info) {\n continue;\n }\n if (link_info._last_time) {\n link_info._last_time = 0;\n }\n }\n }\n /* Called when something visually changed (not the graph!) */\n change() {\n if (LiteGraph.debug) {\n console.log(\"Graph changed\");\n }\n this.sendActionToCanvas(\"setDirty\", [true, true]);\n if (this.on_change) {\n this.on_change(this);\n }\n }\n setDirtyCanvas(fg, bg) {\n this.sendActionToCanvas(\"setDirty\", [fg, bg]);\n }\n /**\n * Destroys a link\n * @method removeLink\n * @param {Number} link_id\n */\n removeLink(link_id) {\n var link = this.links[link_id];\n if (!link) {\n return;\n }\n var node2 = this.getNodeById(link.target_id);\n if (node2) {\n node2.disconnectInput(link.target_slot);\n }\n }\n //save and recover app state ***************************************\n /**\n * Creates a Object containing all the info about this graph, it can be serialized\n * @method serialize\n * @return {Object} value of the node\n */\n serialize(option = { sortNodes: false }) {\n var nodes_info = [];\n nodes_info = ((option == null ? void 0 : option.sortNodes) ? [...this._nodes].sort((a, b) => a.id - b.id) : this._nodes).map((node2) => node2.serialize());\n var links = [];\n for (var i2 in this.links) {\n var link = this.links[i2];\n if (!link.serialize) {\n console.warn(\n \"weird LLink bug, link info is not a LLink but a regular object\"\n );\n var link2 = new LLink();\n for (var j in link) {\n link2[j] = link[j];\n }\n this.links[i2] = link2;\n link = link2;\n }\n links.push(link.serialize());\n }\n var groups_info = [];\n for (var i2 = 0; i2 < this._groups.length; ++i2) {\n groups_info.push(this._groups[i2].serialize());\n }\n var data = {\n last_node_id: this.last_node_id,\n last_link_id: this.last_link_id,\n nodes: nodes_info,\n links,\n groups: groups_info,\n config: this.config,\n extra: this.extra,\n version: LiteGraph.VERSION\n };\n if (this.onSerialize)\n this.onSerialize(data);\n return data;\n }\n /**\n * Configure a graph from a JSON string\n * @method configure\n * @param {String} str configure a graph from a JSON string\n * @param {Boolean} returns if there was any error parsing\n */\n configure(data, keep_old) {\n if (!data) {\n return;\n }\n if (!keep_old) {\n this.clear();\n }\n var nodes = data.nodes;\n if (data.links && data.links.constructor === Array) {\n var links = [];\n for (var i2 = 0; i2 < data.links.length; ++i2) {\n var link_data = data.links[i2];\n if (!link_data) {\n console.warn(\"serialized graph link data contains errors, skipping.\");\n continue;\n }\n var link = new LLink();\n link.configure(link_data);\n links[link.id] = link;\n }\n data.links = links;\n }\n for (var i2 in data) {\n if (i2 == \"nodes\" || i2 == \"groups\")\n continue;\n this[i2] = data[i2];\n }\n var error = false;\n this._nodes = [];\n if (nodes) {\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n_info = nodes[i2];\n var node2 = LiteGraph.createNode(n_info.type, n_info.title);\n if (!node2) {\n if (LiteGraph.debug) {\n console.log(\n \"Node not found or has errors: \" + n_info.type\n );\n }\n node2 = new LGraphNode();\n node2.last_serialization = n_info;\n node2.has_errors = true;\n error = true;\n }\n node2.id = n_info.id;\n this.add(node2, true);\n }\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n_info = nodes[i2];\n var node2 = this.getNodeById(n_info.id);\n if (node2) {\n node2.configure(n_info);\n }\n }\n }\n this._groups.length = 0;\n if (data.groups) {\n for (var i2 = 0; i2 < data.groups.length; ++i2) {\n var group = new LiteGraph.LGraphGroup();\n group.configure(data.groups[i2]);\n this.add(group);\n }\n }\n this.updateExecutionOrder();\n this.extra = data.extra || {};\n if (this.onConfigure)\n this.onConfigure(data);\n this._version++;\n this.setDirtyCanvas(true, true);\n return error;\n }\n load(url, callback) {\n var that2 = this;\n if (url.constructor === File || url.constructor === Blob) {\n var reader = new FileReader();\n reader.addEventListener(\"load\", function(event2) {\n var data = JSON.parse(event2.target.result);\n that2.configure(data);\n if (callback)\n callback();\n });\n reader.readAsText(url);\n return;\n }\n var req = new XMLHttpRequest();\n req.open(\"GET\", url, true);\n req.send(null);\n req.onload = function(oEvent) {\n if (req.status !== 200) {\n console.error(\"Error loading graph:\", req.status, req.response);\n return;\n }\n var data = JSON.parse(req.response);\n that2.configure(data);\n if (callback)\n callback();\n };\n req.onerror = function(err) {\n console.error(\"Error loading graph:\", err);\n };\n }\n onNodeTrace(node2, msg, color) {\n }\n };\n //default supported types\n __publicField(_LGraph, \"supported_types\", [\"number\", \"string\", \"boolean\"]);\n __publicField(_LGraph, \"STATUS_STOPPED\", 1);\n __publicField(_LGraph, \"STATUS_RUNNING\", 2);\n let LGraph = _LGraph;\n globalThis.LGraph = LiteGraph.LGraph = LGraph;\n class LLink {\n constructor(id, type, origin_id, origin_slot, target_id, target_slot) {\n this.id = id;\n this.type = type;\n this.origin_id = origin_id;\n this.origin_slot = origin_slot;\n this.target_id = target_id;\n this.target_slot = target_slot;\n this._data = null;\n this._pos = new Float32Array(2);\n }\n configure(o) {\n if (o.constructor === Array) {\n this.id = o[0];\n this.origin_id = o[1];\n this.origin_slot = o[2];\n this.target_id = o[3];\n this.target_slot = o[4];\n this.type = o[5];\n } else {\n this.id = o.id;\n this.type = o.type;\n this.origin_id = o.origin_id;\n this.origin_slot = o.origin_slot;\n this.target_id = o.target_id;\n this.target_slot = o.target_slot;\n }\n }\n serialize() {\n return [\n this.id,\n this.origin_id,\n this.origin_slot,\n this.target_id,\n this.target_slot,\n this.type\n ];\n }\n }\n LiteGraph.LLink = LLink;\n function LGraphNode(title) {\n this._ctor(title);\n }\n globalThis.LGraphNode = LiteGraph.LGraphNode = LGraphNode;\n LGraphNode.prototype._ctor = function(title) {\n this.title = title || \"Unnamed\";\n this.size = [LiteGraph.NODE_WIDTH, 60];\n this.graph = null;\n this._pos = new Float32Array(10, 10);\n Object.defineProperty(this, \"pos\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._pos[0] = v2[0];\n this._pos[1] = v2[1];\n },\n get: function() {\n return this._pos;\n },\n enumerable: true\n });\n if (LiteGraph.use_uuids) {\n this.id = LiteGraph.uuidv4();\n } else {\n this.id = -1;\n }\n this.type = null;\n this.inputs = [];\n this.outputs = [];\n this.connections = [];\n this.properties = {};\n this.properties_info = [];\n this.flags = {};\n };\n LGraphNode.prototype.configure = function(info) {\n if (this.graph) {\n this.graph._version++;\n }\n for (var j in info) {\n if (j == \"properties\") {\n for (var k in info.properties) {\n this.properties[k] = info.properties[k];\n if (this.onPropertyChanged) {\n this.onPropertyChanged(k, info.properties[k]);\n }\n }\n continue;\n }\n if (info[j] == null) {\n continue;\n } else if (typeof info[j] == \"object\") {\n if (this[j] && this[j].configure) {\n this[j].configure(info[j]);\n } else {\n this[j] = LiteGraph.cloneObject(info[j], this[j]);\n }\n } else {\n this[j] = info[j];\n }\n }\n if (!info.title) {\n this.title = this.constructor.title;\n }\n if (this.inputs) {\n for (var i2 = 0; i2 < this.inputs.length; ++i2) {\n var input = this.inputs[i2];\n var link_info = this.graph ? this.graph.links[input.link] : null;\n if (this.onConnectionsChange)\n this.onConnectionsChange(LiteGraph.INPUT, i2, true, link_info, input);\n if (this.onInputAdded)\n this.onInputAdded(input);\n }\n }\n if (this.outputs) {\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n var output = this.outputs[i2];\n if (!output.links) {\n continue;\n }\n for (var j = 0; j < output.links.length; ++j) {\n var link_info = this.graph ? this.graph.links[output.links[j]] : null;\n if (this.onConnectionsChange)\n this.onConnectionsChange(LiteGraph.OUTPUT, i2, true, link_info, output);\n }\n if (this.onOutputAdded)\n this.onOutputAdded(output);\n }\n }\n if (this.widgets) {\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n var w2 = this.widgets[i2];\n if (!w2)\n continue;\n if (w2.options && w2.options.property && this.properties[w2.options.property] != void 0)\n w2.value = JSON.parse(JSON.stringify(this.properties[w2.options.property]));\n }\n if (info.widgets_values) {\n for (var i2 = 0; i2 < info.widgets_values.length; ++i2) {\n if (this.widgets[i2]) {\n this.widgets[i2].value = info.widgets_values[i2];\n }\n }\n }\n }\n if (this.onConfigure) {\n this.onConfigure(info);\n }\n };\n LGraphNode.prototype.serialize = function() {\n var o = {\n id: this.id,\n type: this.type,\n pos: this.pos,\n size: this.size,\n flags: LiteGraph.cloneObject(this.flags),\n order: this.order,\n mode: this.mode\n };\n if (this.constructor === LGraphNode && this.last_serialization) {\n return this.last_serialization;\n }\n if (this.inputs) {\n o.inputs = this.inputs;\n }\n if (this.outputs) {\n for (var i2 = 0; i2 < this.outputs.length; i2++) {\n delete this.outputs[i2]._data;\n }\n o.outputs = this.outputs;\n }\n if (this.title && this.title != this.constructor.title) {\n o.title = this.title;\n }\n if (this.properties) {\n o.properties = LiteGraph.cloneObject(this.properties);\n }\n if (this.widgets && this.serialize_widgets) {\n o.widgets_values = [];\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n if (this.widgets[i2])\n o.widgets_values[i2] = this.widgets[i2].value;\n else\n o.widgets_values[i2] = null;\n }\n }\n if (!o.type) {\n o.type = this.constructor.type;\n }\n if (this.color) {\n o.color = this.color;\n }\n if (this.bgcolor) {\n o.bgcolor = this.bgcolor;\n }\n if (this.boxcolor) {\n o.boxcolor = this.boxcolor;\n }\n if (this.shape) {\n o.shape = this.shape;\n }\n if (this.onSerialize) {\n if (this.onSerialize(o)) {\n console.warn(\n \"node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter\"\n );\n }\n }\n return o;\n };\n LGraphNode.prototype.clone = function() {\n var node2 = LiteGraph.createNode(this.type);\n if (!node2) {\n return null;\n }\n var data = LiteGraph.cloneObject(this.serialize());\n if (data.inputs) {\n for (var i2 = 0; i2 < data.inputs.length; ++i2) {\n data.inputs[i2].link = null;\n }\n }\n if (data.outputs) {\n for (var i2 = 0; i2 < data.outputs.length; ++i2) {\n if (data.outputs[i2].links) {\n data.outputs[i2].links.length = 0;\n }\n }\n }\n delete data[\"id\"];\n if (LiteGraph.use_uuids) {\n data[\"id\"] = LiteGraph.uuidv4();\n }\n node2.configure(data);\n return node2;\n };\n LGraphNode.prototype.toString = function() {\n return JSON.stringify(this.serialize());\n };\n LGraphNode.prototype.getTitle = function() {\n return this.title || this.constructor.title;\n };\n LGraphNode.prototype.setProperty = function(name, value) {\n if (!this.properties) {\n this.properties = {};\n }\n if (value === this.properties[name])\n return;\n var prev_value = this.properties[name];\n this.properties[name] = value;\n if (this.onPropertyChanged) {\n if (this.onPropertyChanged(name, value, prev_value) === false)\n this.properties[name] = prev_value;\n }\n if (this.widgets)\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n var w2 = this.widgets[i2];\n if (!w2)\n continue;\n if (w2.options.property == name) {\n w2.value = value;\n break;\n }\n }\n };\n LGraphNode.prototype.setOutputData = function(slot, data) {\n if (!this.outputs) {\n return;\n }\n if (slot == -1 || slot >= this.outputs.length) {\n return;\n }\n var output_info = this.outputs[slot];\n if (!output_info) {\n return;\n }\n output_info._data = data;\n if (this.outputs[slot].links) {\n for (var i2 = 0; i2 < this.outputs[slot].links.length; i2++) {\n var link_id = this.outputs[slot].links[i2];\n var link = this.graph.links[link_id];\n if (link)\n link.data = data;\n }\n }\n };\n LGraphNode.prototype.setOutputDataType = function(slot, type) {\n if (!this.outputs) {\n return;\n }\n if (slot == -1 || slot >= this.outputs.length) {\n return;\n }\n var output_info = this.outputs[slot];\n if (!output_info) {\n return;\n }\n output_info.type = type;\n if (this.outputs[slot].links) {\n for (var i2 = 0; i2 < this.outputs[slot].links.length; i2++) {\n var link_id = this.outputs[slot].links[i2];\n this.graph.links[link_id].type = type;\n }\n }\n };\n LGraphNode.prototype.getInputData = function(slot, force_update) {\n if (!this.inputs) {\n return;\n }\n if (slot >= this.inputs.length || this.inputs[slot].link == null) {\n return;\n }\n var link_id = this.inputs[slot].link;\n var link = this.graph.links[link_id];\n if (!link) {\n return null;\n }\n if (!force_update) {\n return link.data;\n }\n var node2 = this.graph.getNodeById(link.origin_id);\n if (!node2) {\n return link.data;\n }\n if (node2.updateOutputData) {\n node2.updateOutputData(link.origin_slot);\n } else if (node2.onExecute) {\n node2.onExecute();\n }\n return link.data;\n };\n LGraphNode.prototype.getInputDataType = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot >= this.inputs.length || this.inputs[slot].link == null) {\n return null;\n }\n var link_id = this.inputs[slot].link;\n var link = this.graph.links[link_id];\n if (!link) {\n return null;\n }\n var node2 = this.graph.getNodeById(link.origin_id);\n if (!node2) {\n return link.type;\n }\n var output_info = node2.outputs[link.origin_slot];\n if (output_info) {\n return output_info.type;\n }\n return null;\n };\n LGraphNode.prototype.getInputDataByName = function(slot_name, force_update) {\n var slot = this.findInputSlot(slot_name);\n if (slot == -1) {\n return null;\n }\n return this.getInputData(slot, force_update);\n };\n LGraphNode.prototype.isInputConnected = function(slot) {\n if (!this.inputs) {\n return false;\n }\n return slot < this.inputs.length && this.inputs[slot].link != null;\n };\n LGraphNode.prototype.getInputInfo = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot < this.inputs.length) {\n return this.inputs[slot];\n }\n return null;\n };\n LGraphNode.prototype.getInputLink = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot < this.inputs.length) {\n var slot_info = this.inputs[slot];\n return this.graph.links[slot_info.link];\n }\n return null;\n };\n LGraphNode.prototype.getInputNode = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot >= this.inputs.length) {\n return null;\n }\n var input = this.inputs[slot];\n if (!input || input.link === null) {\n return null;\n }\n var link_info = this.graph.links[input.link];\n if (!link_info) {\n return null;\n }\n return this.graph.getNodeById(link_info.origin_id);\n };\n LGraphNode.prototype.getInputOrProperty = function(name) {\n if (!this.inputs || !this.inputs.length) {\n return this.properties ? this.properties[name] : null;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input_info = this.inputs[i2];\n if (name == input_info.name && input_info.link != null) {\n var link = this.graph.links[input_info.link];\n if (link) {\n return link.data;\n }\n }\n }\n return this.properties[name];\n };\n LGraphNode.prototype.getOutputData = function(slot) {\n if (!this.outputs) {\n return null;\n }\n if (slot >= this.outputs.length) {\n return null;\n }\n var info = this.outputs[slot];\n return info._data;\n };\n LGraphNode.prototype.getOutputInfo = function(slot) {\n if (!this.outputs) {\n return null;\n }\n if (slot < this.outputs.length) {\n return this.outputs[slot];\n }\n return null;\n };\n LGraphNode.prototype.isOutputConnected = function(slot) {\n if (!this.outputs) {\n return false;\n }\n return slot < this.outputs.length && this.outputs[slot].links && this.outputs[slot].links.length;\n };\n LGraphNode.prototype.isAnyOutputConnected = function() {\n if (!this.outputs) {\n return false;\n }\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n if (this.outputs[i2].links && this.outputs[i2].links.length) {\n return true;\n }\n }\n return false;\n };\n LGraphNode.prototype.getOutputNodes = function(slot) {\n if (!this.outputs || this.outputs.length == 0) {\n return null;\n }\n if (slot >= this.outputs.length) {\n return null;\n }\n var output = this.outputs[slot];\n if (!output.links || output.links.length == 0) {\n return null;\n }\n var r = [];\n for (var i2 = 0; i2 < output.links.length; i2++) {\n var link_id = output.links[i2];\n var link = this.graph.links[link_id];\n if (link) {\n var target_node = this.graph.getNodeById(link.target_id);\n if (target_node) {\n r.push(target_node);\n }\n }\n }\n return r;\n };\n LGraphNode.prototype.addOnTriggerInput = function() {\n var trigS = this.findInputSlot(\"onTrigger\");\n if (trigS == -1) {\n //!trigS || \n this.addInput(\"onTrigger\", LiteGraph.EVENT, { optional: true, nameLocked: true });\n return this.findInputSlot(\"onTrigger\");\n }\n return trigS;\n };\n LGraphNode.prototype.addOnExecutedOutput = function() {\n var trigS = this.findOutputSlot(\"onExecuted\");\n if (trigS == -1) {\n //!trigS || \n this.addOutput(\"onExecuted\", LiteGraph.ACTION, { optional: true, nameLocked: true });\n return this.findOutputSlot(\"onExecuted\");\n }\n return trigS;\n };\n LGraphNode.prototype.onAfterExecuteNode = function(param, options) {\n var trigS = this.findOutputSlot(\"onExecuted\");\n if (trigS != -1) {\n this.triggerSlot(trigS, param, null, options);\n }\n };\n LGraphNode.prototype.changeMode = function(modeTo) {\n switch (modeTo) {\n case LiteGraph.ON_EVENT:\n break;\n case LiteGraph.ON_TRIGGER:\n this.addOnTriggerInput();\n this.addOnExecutedOutput();\n break;\n case LiteGraph.NEVER:\n break;\n case LiteGraph.ALWAYS:\n break;\n case LiteGraph.ON_REQUEST:\n break;\n default:\n return false;\n }\n this.mode = modeTo;\n return true;\n };\n LGraphNode.prototype.doExecute = function(param, options) {\n options = options || {};\n if (this.onExecute) {\n if (!options.action_call) options.action_call = this.id + \"_exec_\" + Math.floor(Math.random() * 9999);\n this.graph.nodes_executing[this.id] = true;\n this.onExecute(param, options);\n this.graph.nodes_executing[this.id] = false;\n this.exec_version = this.graph.iteration;\n if (options && options.action_call) {\n this.action_call = options.action_call;\n this.graph.nodes_executedAction[this.id] = options.action_call;\n }\n }\n this.execute_triggered = 2;\n if (this.onAfterExecuteNode) this.onAfterExecuteNode(param, options);\n };\n LGraphNode.prototype.actionDo = function(action, param, options) {\n options = options || {};\n if (this.onAction) {\n if (!options.action_call) options.action_call = this.id + \"_\" + (action ? action : \"action\") + \"_\" + Math.floor(Math.random() * 9999);\n this.graph.nodes_actioning[this.id] = action ? action : \"actioning\";\n this.onAction(action, param, options);\n this.graph.nodes_actioning[this.id] = false;\n if (options && options.action_call) {\n this.action_call = options.action_call;\n this.graph.nodes_executedAction[this.id] = options.action_call;\n }\n }\n this.action_triggered = 2;\n if (this.onAfterExecuteNode) this.onAfterExecuteNode(param, options);\n };\n LGraphNode.prototype.trigger = function(action, param, options) {\n if (!this.outputs || !this.outputs.length) {\n return;\n }\n if (this.graph)\n this.graph._last_trigger_time = LiteGraph.getTime();\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n var output = this.outputs[i2];\n if (!output || output.type !== LiteGraph.EVENT || action && output.name != action)\n continue;\n this.triggerSlot(i2, param, null, options);\n }\n };\n LGraphNode.prototype.triggerSlot = function(slot, param, link_id, options) {\n options = options || {};\n if (!this.outputs) {\n return;\n }\n if (slot == null) {\n console.error(\"slot must be a number\");\n return;\n }\n if (slot.constructor !== Number)\n console.warn(\"slot must be a number, use node.trigger('name') if you want to use a string\");\n var output = this.outputs[slot];\n if (!output) {\n return;\n }\n var links = output.links;\n if (!links || !links.length) {\n return;\n }\n if (this.graph) {\n this.graph._last_trigger_time = LiteGraph.getTime();\n }\n for (var k = 0; k < links.length; ++k) {\n var id = links[k];\n if (link_id != null && link_id != id) {\n continue;\n }\n var link_info = this.graph.links[links[k]];\n if (!link_info) {\n continue;\n }\n link_info._last_time = LiteGraph.getTime();\n var node2 = this.graph.getNodeById(link_info.target_id);\n if (!node2) {\n continue;\n }\n var target_connection = node2.inputs[link_info.target_slot];\n if (node2.mode === LiteGraph.ON_TRIGGER) {\n if (!options.action_call) options.action_call = this.id + \"_trigg_\" + Math.floor(Math.random() * 9999);\n if (node2.onExecute) {\n node2.doExecute(param, options);\n }\n } else if (node2.onAction) {\n if (!options.action_call) options.action_call = this.id + \"_act_\" + Math.floor(Math.random() * 9999);\n var target_connection = node2.inputs[link_info.target_slot];\n node2.actionDo(target_connection.name, param, options);\n }\n }\n };\n LGraphNode.prototype.clearTriggeredSlot = function(slot, link_id) {\n if (!this.outputs) {\n return;\n }\n var output = this.outputs[slot];\n if (!output) {\n return;\n }\n var links = output.links;\n if (!links || !links.length) {\n return;\n }\n for (var k = 0; k < links.length; ++k) {\n var id = links[k];\n if (link_id != null && link_id != id) {\n continue;\n }\n var link_info = this.graph.links[links[k]];\n if (!link_info) {\n continue;\n }\n link_info._last_time = 0;\n }\n };\n LGraphNode.prototype.setSize = function(size) {\n this.size = size;\n if (this.onResize)\n this.onResize(this.size);\n };\n LGraphNode.prototype.addProperty = function(name, default_value, type, extra_info) {\n var o = { name, type, default_value };\n if (extra_info) {\n for (var i2 in extra_info) {\n o[i2] = extra_info[i2];\n }\n }\n if (!this.properties_info) {\n this.properties_info = [];\n }\n this.properties_info.push(o);\n if (!this.properties) {\n this.properties = {};\n }\n this.properties[name] = default_value;\n return o;\n };\n LGraphNode.prototype.addOutput = function(name, type, extra_info) {\n var output = { name, type, links: null };\n if (extra_info) {\n for (var i2 in extra_info) {\n output[i2] = extra_info[i2];\n }\n }\n if (!this.outputs) {\n this.outputs = [];\n }\n this.outputs.push(output);\n if (this.onOutputAdded) {\n this.onOutputAdded(output);\n }\n if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this, type, true);\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n return output;\n };\n LGraphNode.prototype.addOutputs = function(array) {\n for (var i2 = 0; i2 < array.length; ++i2) {\n var info = array[i2];\n var o = { name: info[0], type: info[1], link: null };\n if (array[2]) {\n for (var j in info[2]) {\n o[j] = info[2][j];\n }\n }\n if (!this.outputs) {\n this.outputs = [];\n }\n this.outputs.push(o);\n if (this.onOutputAdded) {\n this.onOutputAdded(o);\n }\n if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this, info[1], true);\n }\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.removeOutput = function(slot) {\n this.disconnectOutput(slot);\n this.outputs.splice(slot, 1);\n for (var i2 = slot; i2 < this.outputs.length; ++i2) {\n if (!this.outputs[i2] || !this.outputs[i2].links) {\n continue;\n }\n var links = this.outputs[i2].links;\n for (var j = 0; j < links.length; ++j) {\n var link = this.graph.links[links[j]];\n if (!link) {\n continue;\n }\n link.origin_slot -= 1;\n }\n }\n this.setSize(this.computeSize());\n if (this.onOutputRemoved) {\n this.onOutputRemoved(slot);\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.addInput = function(name, type, extra_info) {\n type = type || 0;\n var input = { name, type, link: null };\n if (extra_info) {\n for (var i2 in extra_info) {\n input[i2] = extra_info[i2];\n }\n }\n if (!this.inputs) {\n this.inputs = [];\n }\n this.inputs.push(input);\n this.setSize(this.computeSize());\n if (this.onInputAdded) {\n this.onInputAdded(input);\n }\n LiteGraph.registerNodeAndSlotType(this, type);\n this.setDirtyCanvas(true, true);\n return input;\n };\n LGraphNode.prototype.addInputs = function(array) {\n for (var i2 = 0; i2 < array.length; ++i2) {\n var info = array[i2];\n var o = { name: info[0], type: info[1], link: null };\n if (array[2]) {\n for (var j in info[2]) {\n o[j] = info[2][j];\n }\n }\n if (!this.inputs) {\n this.inputs = [];\n }\n this.inputs.push(o);\n if (this.onInputAdded) {\n this.onInputAdded(o);\n }\n LiteGraph.registerNodeAndSlotType(this, info[1]);\n }\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.removeInput = function(slot) {\n this.disconnectInput(slot);\n var slot_info = this.inputs.splice(slot, 1);\n for (var i2 = slot; i2 < this.inputs.length; ++i2) {\n if (!this.inputs[i2]) {\n continue;\n }\n var link = this.graph.links[this.inputs[i2].link];\n if (!link) {\n continue;\n }\n link.target_slot -= 1;\n }\n this.setSize(this.computeSize());\n if (this.onInputRemoved) {\n this.onInputRemoved(slot, slot_info[0]);\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.addConnection = function(name, type, pos2, direction) {\n var o = {\n name,\n type,\n pos: pos2,\n direction,\n links: null\n };\n this.connections.push(o);\n return o;\n };\n LGraphNode.prototype.computeSize = function(out) {\n if (this.constructor.size) {\n return this.constructor.size.concat();\n }\n var rows = Math.max(\n this.inputs ? this.inputs.length : 1,\n this.outputs ? this.outputs.length : 1\n );\n var size = out || new Float32Array([0, 0]);\n rows = Math.max(rows, 1);\n var font_size = LiteGraph.NODE_TEXT_SIZE;\n var title_width = compute_text_size(this.title);\n var input_width = 0;\n var output_width = 0;\n if (this.inputs) {\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input = this.inputs[i2];\n var text = input.label || input.name || \"\";\n var text_width = compute_text_size(text);\n if (input_width < text_width) {\n input_width = text_width;\n }\n }\n }\n if (this.outputs) {\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n var output = this.outputs[i2];\n var text = output.label || output.name || \"\";\n var text_width = compute_text_size(text);\n if (output_width < text_width) {\n output_width = text_width;\n }\n }\n }\n size[0] = Math.max(input_width + output_width + 10, title_width);\n size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH);\n if (this.widgets && this.widgets.length) {\n size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH * 1.5);\n }\n size[1] = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;\n var widgets_height = 0;\n if (this.widgets && this.widgets.length) {\n for (var i2 = 0, l = this.widgets.length; i2 < l; ++i2) {\n if (this.widgets[i2].computeSize)\n widgets_height += this.widgets[i2].computeSize(size[0])[1] + 4;\n else\n widgets_height += LiteGraph.NODE_WIDGET_HEIGHT + 4;\n }\n widgets_height += 8;\n }\n if (this.widgets_up)\n size[1] = Math.max(size[1], widgets_height);\n else if (this.widgets_start_y != null)\n size[1] = Math.max(size[1], widgets_height + this.widgets_start_y);\n else\n size[1] += widgets_height;\n function compute_text_size(text2) {\n if (!text2) {\n return 0;\n }\n return font_size * text2.length * 0.6;\n }\n if (this.constructor.min_height && size[1] < this.constructor.min_height) {\n size[1] = this.constructor.min_height;\n }\n size[1] += 6;\n return size;\n };\n LGraphNode.prototype.inResizeCorner = function(canvasX, canvasY) {\n var rows = this.outputs ? this.outputs.length : 1;\n var outputs_offset = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;\n return isInsideRectangle(\n canvasX,\n canvasY,\n this.pos[0] + this.size[0] - 15,\n this.pos[1] + Math.max(this.size[1] - 15, outputs_offset),\n 20,\n 20\n );\n };\n LGraphNode.prototype.getPropertyInfo = function(property) {\n var info = null;\n if (this.properties_info) {\n for (var i2 = 0; i2 < this.properties_info.length; ++i2) {\n if (this.properties_info[i2].name == property) {\n info = this.properties_info[i2];\n break;\n }\n }\n }\n if (this.constructor[\"@\" + property])\n info = this.constructor[\"@\" + property];\n if (this.constructor.widgets_info && this.constructor.widgets_info[property])\n info = this.constructor.widgets_info[property];\n if (!info && this.onGetPropertyInfo) {\n info = this.onGetPropertyInfo(property);\n }\n if (!info)\n info = {};\n if (!info.type)\n info.type = typeof this.properties[property];\n if (info.widget == \"combo\")\n info.type = \"enum\";\n return info;\n };\n LGraphNode.prototype.addWidget = function(type, name, value, callback, options) {\n if (!this.widgets) {\n this.widgets = [];\n }\n if (!options && callback && callback.constructor === Object) {\n options = callback;\n callback = null;\n }\n if (options && options.constructor === String)\n options = { property: options };\n if (callback && callback.constructor === String) {\n if (!options)\n options = {};\n options.property = callback;\n callback = null;\n }\n if (callback && callback.constructor !== Function) {\n console.warn(\"addWidget: callback must be a function\");\n callback = null;\n }\n var w2 = {\n type: type.toLowerCase(),\n name,\n value,\n callback,\n options: options || {}\n };\n if (w2.options.y !== void 0) {\n w2.y = w2.options.y;\n }\n if (!callback && !w2.options.callback && !w2.options.property) {\n console.warn(\"LiteGraph addWidget(...) without a callback or property assigned\");\n }\n if (type == \"combo\" && !w2.options.values) {\n throw \"LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }\";\n }\n this.widgets.push(w2);\n this.setSize(this.computeSize());\n return w2;\n };\n LGraphNode.prototype.addCustomWidget = function(custom_widget) {\n if (!this.widgets) {\n this.widgets = [];\n }\n this.widgets.push(custom_widget);\n return custom_widget;\n };\n LGraphNode.prototype.getBounding = function(out, compute_outer) {\n out = out || new Float32Array(4);\n const nodePos = this.pos;\n const isCollapsed = this.flags.collapsed;\n const nodeSize = this.size;\n let left_offset = 0;\n let right_offset = 1;\n let top_offset = 0;\n let bottom_offset = 0;\n if (compute_outer) {\n left_offset = 4;\n right_offset = 6 + left_offset;\n top_offset = 4;\n bottom_offset = 5 + top_offset;\n }\n out[0] = nodePos[0] - left_offset;\n out[1] = nodePos[1] - LiteGraph.NODE_TITLE_HEIGHT - top_offset;\n out[2] = isCollapsed ? (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + right_offset : nodeSize[0] + right_offset;\n out[3] = isCollapsed ? LiteGraph.NODE_TITLE_HEIGHT + bottom_offset : nodeSize[1] + LiteGraph.NODE_TITLE_HEIGHT + bottom_offset;\n if (this.onBounding) {\n this.onBounding(out);\n }\n return out;\n };\n LGraphNode.prototype.isPointInside = function(x2, y2, margin, skip_title) {\n margin = margin || 0;\n var margin_top = this.graph && this.graph.isLive() ? 0 : LiteGraph.NODE_TITLE_HEIGHT;\n if (skip_title) {\n margin_top = 0;\n }\n if (this.flags && this.flags.collapsed) {\n if (isInsideRectangle(\n x2,\n y2,\n this.pos[0] - margin,\n this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT - margin,\n (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + 2 * margin,\n LiteGraph.NODE_TITLE_HEIGHT + 2 * margin\n )) {\n return true;\n }\n } else if (this.pos[0] - 4 - margin < x2 && this.pos[0] + this.size[0] + 4 + margin > x2 && this.pos[1] - margin_top - margin < y2 && this.pos[1] + this.size[1] + margin > y2) {\n return true;\n }\n return false;\n };\n LGraphNode.prototype.getSlotInPosition = function(x2, y2) {\n var link_pos = new Float32Array(2);\n if (this.inputs) {\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input = this.inputs[i2];\n this.getConnectionPos(true, i2, link_pos);\n if (isInsideRectangle(\n x2,\n y2,\n link_pos[0] - 10,\n link_pos[1] - 5,\n 20,\n 10\n )) {\n return { input, slot: i2, link_pos };\n }\n }\n }\n if (this.outputs) {\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n var output = this.outputs[i2];\n this.getConnectionPos(false, i2, link_pos);\n if (isInsideRectangle(\n x2,\n y2,\n link_pos[0] - 10,\n link_pos[1] - 5,\n 20,\n 10\n )) {\n return { output, slot: i2, link_pos };\n }\n }\n }\n return null;\n };\n LGraphNode.prototype.findInputSlot = function(name, returnObj) {\n if (!this.inputs) {\n return -1;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n if (name == this.inputs[i2].name) {\n return !returnObj ? i2 : this.inputs[i2];\n }\n }\n return -1;\n };\n LGraphNode.prototype.findOutputSlot = function(name, returnObj) {\n returnObj = returnObj || false;\n if (!this.outputs) {\n return -1;\n }\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n if (name == this.outputs[i2].name) {\n return !returnObj ? i2 : this.outputs[i2];\n }\n }\n return -1;\n };\n LGraphNode.prototype.findInputSlotFree = function(optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n returnObj: false,\n typesNotAccepted: []\n };\n var opts = Object.assign(optsDef, optsIn);\n if (!this.inputs) {\n return -1;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n if (this.inputs[i2].link && this.inputs[i2].link != null) {\n continue;\n }\n if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.inputs[i2].type)) {\n continue;\n }\n return !opts.returnObj ? i2 : this.inputs[i2];\n }\n return -1;\n };\n LGraphNode.prototype.findOutputSlotFree = function(optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n returnObj: false,\n typesNotAccepted: []\n };\n var opts = Object.assign(optsDef, optsIn);\n if (!this.outputs) {\n return -1;\n }\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n if (this.outputs[i2].links && this.outputs[i2].links != null) {\n continue;\n }\n if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.outputs[i2].type)) {\n continue;\n }\n return !opts.returnObj ? i2 : this.outputs[i2];\n }\n return -1;\n };\n LGraphNode.prototype.findInputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(true, type, returnObj, preferFreeSlot, doNotUseOccupied);\n };\n LGraphNode.prototype.findOutputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(false, type, returnObj, preferFreeSlot, doNotUseOccupied);\n };\n LGraphNode.prototype.findSlotByType = function(input, type, returnObj, preferFreeSlot, doNotUseOccupied) {\n input = input || false;\n returnObj = returnObj || false;\n preferFreeSlot = preferFreeSlot || false;\n doNotUseOccupied = doNotUseOccupied || false;\n var aSlots = input ? this.inputs : this.outputs;\n if (!aSlots) {\n return -1;\n }\n if (type == \"\" || type == \"*\") type = 0;\n for (var i2 = 0, l = aSlots.length; i2 < l; ++i2) {\n var aSource = (type + \"\").toLowerCase().split(\",\");\n var aDest = aSlots[i2].type == \"0\" || aSlots[i2].type == \"*\" ? \"0\" : aSlots[i2].type;\n aDest = (aDest + \"\").toLowerCase().split(\",\");\n for (var sI = 0; sI < aSource.length; sI++) {\n for (var dI = 0; dI < aDest.length; dI++) {\n if (aSource[sI] == \"_event_\") aSource[sI] = LiteGraph.EVENT;\n if (aDest[sI] == \"_event_\") aDest[sI] = LiteGraph.EVENT;\n if (aSource[sI] == \"*\") aSource[sI] = 0;\n if (aDest[sI] == \"*\") aDest[sI] = 0;\n if (aSource[sI] == aDest[dI]) {\n if (preferFreeSlot && (aSlots[i2].links && aSlots[i2].links !== null) || aSlots[i2].link && aSlots[i2].link !== null) continue;\n return !returnObj ? i2 : aSlots[i2];\n }\n }\n }\n }\n if (preferFreeSlot && !doNotUseOccupied) {\n for (var i2 = 0, l = aSlots.length; i2 < l; ++i2) {\n var aSource = (type + \"\").toLowerCase().split(\",\");\n var aDest = aSlots[i2].type == \"0\" || aSlots[i2].type == \"*\" ? \"0\" : aSlots[i2].type;\n aDest = (aDest + \"\").toLowerCase().split(\",\");\n for (var sI = 0; sI < aSource.length; sI++) {\n for (var dI = 0; dI < aDest.length; dI++) {\n if (aSource[sI] == \"*\") aSource[sI] = 0;\n if (aDest[sI] == \"*\") aDest[sI] = 0;\n if (aSource[sI] == aDest[dI]) {\n return !returnObj ? i2 : aSlots[i2];\n }\n }\n }\n }\n }\n return -1;\n };\n LGraphNode.prototype.connectByType = function(slot, target_node, target_slotType, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n createEventInCase: true,\n firstFreeIfOutputGeneralInCase: true,\n generalTypeInCase: true\n };\n var opts = Object.assign(optsDef, optsIn);\n if (target_node && target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n var target_slot = target_node.findInputSlotByType(target_slotType, false, true);\n if (target_slot >= 0 && target_slot !== null) {\n return this.connect(slot, target_node, target_slot);\n } else {\n if (opts.createEventInCase && target_slotType == LiteGraph.EVENT) {\n return this.connect(slot, target_node, -1);\n }\n if (opts.generalTypeInCase) {\n var target_slot = target_node.findInputSlotByType(0, false, true, true);\n if (target_slot >= 0) {\n return this.connect(slot, target_node, target_slot);\n }\n }\n if (opts.firstFreeIfOutputGeneralInCase && (target_slotType == 0 || target_slotType == \"*\" || target_slotType == \"\")) {\n var target_slot = target_node.findInputSlotFree({ typesNotAccepted: [LiteGraph.EVENT] });\n if (target_slot >= 0) {\n return this.connect(slot, target_node, target_slot);\n }\n }\n console.debug(\"no way to connect type: \", target_slotType, \" to targetNODE \", target_node);\n return null;\n }\n };\n LGraphNode.prototype.connectByTypeOutput = function(slot, source_node, source_slotType, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n createEventInCase: true,\n firstFreeIfInputGeneralInCase: true,\n generalTypeInCase: true\n };\n var opts = Object.assign(optsDef, optsIn);\n if (source_node && source_node.constructor === Number) {\n source_node = this.graph.getNodeById(source_node);\n }\n var source_slot = source_node.findOutputSlotByType(source_slotType, false, true);\n if (source_slot >= 0 && source_slot !== null) {\n return source_node.connect(source_slot, this, slot);\n } else {\n if (opts.generalTypeInCase) {\n var source_slot = source_node.findOutputSlotByType(0, false, true, true);\n if (source_slot >= 0) {\n return source_node.connect(source_slot, this, slot);\n }\n }\n if (opts.createEventInCase && source_slotType == LiteGraph.EVENT) {\n if (LiteGraph.do_add_triggers_slots) {\n var source_slot = source_node.addOnExecutedOutput();\n return source_node.connect(source_slot, this, slot);\n }\n }\n if (opts.firstFreeIfInputGeneralInCase && (source_slotType == 0 || source_slotType == \"*\" || source_slotType == \"\")) {\n var source_slot = source_node.findOutputSlotFree({ typesNotAccepted: [LiteGraph.EVENT] });\n if (source_slot >= 0) {\n return source_node.connect(source_slot, this, slot);\n }\n }\n console.debug(\"no way to connect byOUT type: \", source_slotType, \" to sourceNODE \", source_node);\n return null;\n }\n };\n LGraphNode.prototype.connect = function(slot, target_node, target_slot) {\n target_slot = target_slot || 0;\n if (!this.graph) {\n console.log(\n \"Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them.\"\n );\n return null;\n }\n if (slot.constructor === String) {\n slot = this.findOutputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return null;\n }\n } else if (!this.outputs || slot >= this.outputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return null;\n }\n if (target_node && target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n if (!target_node) {\n throw \"target node is null\";\n }\n if (target_node == this) {\n return null;\n }\n if (target_slot.constructor === String) {\n target_slot = target_node.findInputSlot(target_slot);\n if (target_slot == -1) {\n if (LiteGraph.debug) {\n console.log(\n \"Connect: Error, no slot of name \" + target_slot\n );\n }\n return null;\n }\n } else if (target_slot === LiteGraph.EVENT) {\n if (LiteGraph.do_add_triggers_slots) {\n target_node.changeMode(LiteGraph.ON_TRIGGER);\n target_slot = target_node.findInputSlot(\"onTrigger\");\n } else {\n return null;\n }\n } else if (!target_node.inputs || target_slot >= target_node.inputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return null;\n }\n var changed = false;\n var input = target_node.inputs[target_slot];\n var link_info = null;\n var output = this.outputs[slot];\n if (!this.outputs[slot]) {\n return null;\n }\n if (target_node.onBeforeConnectInput) {\n target_slot = target_node.onBeforeConnectInput(target_slot);\n }\n if (target_slot === false || target_slot === null || !LiteGraph.isValidConnection(output.type, input.type)) {\n this.setDirtyCanvas(false, true);\n if (changed)\n this.graph.connectionChange(this, link_info);\n return null;\n }\n if (target_node.onConnectInput) {\n if (target_node.onConnectInput(target_slot, output.type, output, this, slot) === false) {\n return null;\n }\n }\n if (this.onConnectOutput) {\n if (this.onConnectOutput(slot, input.type, input, target_node, target_slot) === false) {\n return null;\n }\n }\n if (target_node.inputs[target_slot] && target_node.inputs[target_slot].link != null) {\n this.graph.beforeChange();\n target_node.disconnectInput(target_slot, { doProcessChange: false });\n changed = true;\n }\n if (output.links !== null && output.links.length) {\n switch (output.type) {\n case LiteGraph.EVENT:\n if (!LiteGraph.allow_multi_output_for_events) {\n this.graph.beforeChange();\n this.disconnectOutput(slot, false, { doProcessChange: false });\n changed = true;\n }\n break;\n }\n }\n var nextId;\n if (LiteGraph.use_uuids)\n nextId = LiteGraph.uuidv4();\n else\n nextId = ++this.graph.last_link_id;\n link_info = new LLink(\n nextId,\n input.type || output.type,\n this.id,\n slot,\n target_node.id,\n target_slot\n );\n this.graph.links[link_info.id] = link_info;\n if (output.links == null) {\n output.links = [];\n }\n output.links.push(link_info.id);\n target_node.inputs[target_slot].link = link_info.id;\n if (this.graph) {\n this.graph._version++;\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n true,\n link_info,\n output\n );\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n target_slot,\n true,\n link_info,\n input\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n target_slot,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot,\n target_node,\n target_slot\n );\n }\n this.setDirtyCanvas(false, true);\n this.graph.afterChange();\n this.graph.connectionChange(this, link_info);\n return link_info;\n };\n LGraphNode.prototype.disconnectOutput = function(slot, target_node) {\n if (slot.constructor === String) {\n slot = this.findOutputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return false;\n }\n } else if (!this.outputs || slot >= this.outputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return false;\n }\n var output = this.outputs[slot];\n if (!output || !output.links || output.links.length == 0) {\n return false;\n }\n if (target_node) {\n if (target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n if (!target_node) {\n throw \"Target Node not found\";\n }\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n var link_id = output.links[i2];\n var link_info = this.graph.links[link_id];\n if (link_info.target_id == target_node.id) {\n output.links.splice(i2, 1);\n var input = target_node.inputs[link_info.target_slot];\n input.link = null;\n delete this.graph.links[link_id];\n if (this.graph) {\n this.graph._version++;\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n link_info.target_slot,\n false,\n link_info,\n input\n );\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n break;\n }\n }\n } else {\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n var link_id = output.links[i2];\n var link_info = this.graph.links[link_id];\n if (!link_info) {\n continue;\n }\n var target_node = this.graph.getNodeById(link_info.target_id);\n var input = null;\n if (this.graph) {\n this.graph._version++;\n }\n if (target_node) {\n input = target_node.inputs[link_info.target_slot];\n input.link = null;\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n link_info.target_slot,\n false,\n link_info,\n input\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n }\n delete this.graph.links[link_id];\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n }\n output.links = null;\n }\n this.setDirtyCanvas(false, true);\n this.graph.connectionChange(this);\n return true;\n };\n LGraphNode.prototype.disconnectInput = function(slot) {\n if (slot.constructor === String) {\n slot = this.findInputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return false;\n }\n } else if (!this.inputs || slot >= this.inputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return false;\n }\n var input = this.inputs[slot];\n if (!input) {\n return false;\n }\n var link_id = this.inputs[slot].link;\n if (link_id != null) {\n this.inputs[slot].link = null;\n var link_info = this.graph.links[link_id];\n if (link_info) {\n var target_node = this.graph.getNodeById(link_info.origin_id);\n if (!target_node) {\n return false;\n }\n var output = target_node.outputs[link_info.origin_slot];\n if (!output || !output.links || output.links.length == 0) {\n return false;\n }\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n if (output.links[i2] == link_id) {\n output.links.splice(i2, 1);\n break;\n }\n }\n delete this.graph.links[link_id];\n if (this.graph) {\n this.graph._version++;\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.INPUT,\n slot,\n false,\n link_info,\n input\n );\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.OUTPUT,\n i2,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n target_node,\n i2\n );\n this.graph.onNodeConnectionChange(LiteGraph.INPUT, this, slot);\n }\n }\n }\n this.setDirtyCanvas(false, true);\n if (this.graph)\n this.graph.connectionChange(this);\n return true;\n };\n LGraphNode.prototype.getConnectionPos = function(is_input, slot_number, out) {\n out = out || new Float32Array(2);\n var num_slots = 0;\n if (is_input && this.inputs) {\n num_slots = this.inputs.length;\n }\n if (!is_input && this.outputs) {\n num_slots = this.outputs.length;\n }\n var offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n if (this.flags.collapsed) {\n var w2 = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;\n if (this.horizontal) {\n out[0] = this.pos[0] + w2 * 0.5;\n if (is_input) {\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT;\n } else {\n out[1] = this.pos[1];\n }\n } else {\n if (is_input) {\n out[0] = this.pos[0];\n } else {\n out[0] = this.pos[0] + w2;\n }\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n }\n return out;\n }\n if (is_input && slot_number == -1) {\n out[0] = this.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n out[1] = this.pos[1] + LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n return out;\n }\n if (is_input && num_slots > slot_number && this.inputs[slot_number].pos) {\n out[0] = this.pos[0] + this.inputs[slot_number].pos[0];\n out[1] = this.pos[1] + this.inputs[slot_number].pos[1];\n return out;\n } else if (!is_input && num_slots > slot_number && this.outputs[slot_number].pos) {\n out[0] = this.pos[0] + this.outputs[slot_number].pos[0];\n out[1] = this.pos[1] + this.outputs[slot_number].pos[1];\n return out;\n }\n if (this.horizontal) {\n out[0] = this.pos[0] + (slot_number + 0.5) * (this.size[0] / num_slots);\n if (is_input) {\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT;\n } else {\n out[1] = this.pos[1] + this.size[1];\n }\n return out;\n }\n if (is_input) {\n out[0] = this.pos[0] + offset;\n } else {\n out[0] = this.pos[0] + this.size[0] + 1 - offset;\n }\n out[1] = this.pos[1] + (slot_number + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + (this.constructor.slot_start_y || 0);\n return out;\n };\n LGraphNode.prototype.alignToGrid = function() {\n this.pos[0] = LiteGraph.CANVAS_GRID_SIZE * Math.round(this.pos[0] / LiteGraph.CANVAS_GRID_SIZE);\n this.pos[1] = LiteGraph.CANVAS_GRID_SIZE * Math.round(this.pos[1] / LiteGraph.CANVAS_GRID_SIZE);\n };\n LGraphNode.prototype.trace = function(msg) {\n if (!this.console) {\n this.console = [];\n }\n this.console.push(msg);\n if (this.console.length > LGraphNode.MAX_CONSOLE) {\n this.console.shift();\n }\n if (this.graph.onNodeTrace)\n this.graph.onNodeTrace(this, msg);\n };\n LGraphNode.prototype.setDirtyCanvas = function(dirty_foreground, dirty_background) {\n if (!this.graph) {\n return;\n }\n this.graph.sendActionToCanvas(\"setDirty\", [\n dirty_foreground,\n dirty_background\n ]);\n };\n LGraphNode.prototype.loadImage = function(url) {\n var img = new Image();\n img.src = LiteGraph.node_images_path + url;\n img.ready = false;\n var that2 = this;\n img.onload = function() {\n this.ready = true;\n that2.setDirtyCanvas(true);\n };\n return img;\n };\n LGraphNode.prototype.captureInput = function(v2) {\n if (!this.graph || !this.graph.list_of_graphcanvas) {\n return;\n }\n var list = this.graph.list_of_graphcanvas;\n for (var i2 = 0; i2 < list.length; ++i2) {\n var c = list[i2];\n if (!v2 && c.node_capturing_input != this) {\n continue;\n }\n c.node_capturing_input = v2 ? this : null;\n }\n };\n LGraphNode.prototype.collapse = function(force) {\n this.graph._version++;\n if (this.constructor.collapsable === false && !force) {\n return;\n }\n if (!this.flags.collapsed) {\n this.flags.collapsed = true;\n } else {\n this.flags.collapsed = false;\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.pin = function(v2) {\n this.graph._version++;\n if (v2 === void 0) {\n this.flags.pinned = !this.flags.pinned;\n } else {\n this.flags.pinned = v2;\n }\n };\n LGraphNode.prototype.localToScreen = function(x2, y2, graphcanvas) {\n return [\n (x2 + this.pos[0]) * graphcanvas.scale + graphcanvas.offset[0],\n (y2 + this.pos[1]) * graphcanvas.scale + graphcanvas.offset[1]\n ];\n };\n function LGraphGroup(title) {\n this._ctor(title);\n }\n globalThis.LGraphGroup = LiteGraph.LGraphGroup = LGraphGroup;\n LGraphGroup.prototype._ctor = function(title) {\n this.title = title || \"Group\";\n this.font_size = LiteGraph.DEFAULT_GROUP_FONT || 24;\n this.color = LGraphCanvas.node_colors.pale_blue ? LGraphCanvas.node_colors.pale_blue.groupcolor : \"#AAA\";\n this._bounding = new Float32Array([10, 10, 140, 80]);\n this._pos = this._bounding.subarray(0, 2);\n this._size = this._bounding.subarray(2, 4);\n this._nodes = [];\n this.graph = null;\n Object.defineProperty(this, \"pos\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._pos[0] = v2[0];\n this._pos[1] = v2[1];\n },\n get: function() {\n return this._pos;\n },\n enumerable: true\n });\n Object.defineProperty(this, \"size\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._size[0] = Math.max(140, v2[0]);\n this._size[1] = Math.max(80, v2[1]);\n },\n get: function() {\n return this._size;\n },\n enumerable: true\n });\n };\n LGraphGroup.prototype.configure = function(o) {\n this.title = o.title;\n this._bounding.set(o.bounding);\n this.color = o.color;\n if (o.font_size) {\n this.font_size = o.font_size;\n }\n };\n LGraphGroup.prototype.serialize = function() {\n var b = this._bounding;\n return {\n title: this.title,\n bounding: [\n Math.round(b[0]),\n Math.round(b[1]),\n Math.round(b[2]),\n Math.round(b[3])\n ],\n color: this.color,\n font_size: this.font_size\n };\n };\n LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) {\n this._pos[0] += deltax;\n this._pos[1] += deltay;\n if (ignore_nodes) {\n return;\n }\n for (var i2 = 0; i2 < this._nodes.length; ++i2) {\n var node2 = this._nodes[i2];\n node2.pos[0] += deltax;\n node2.pos[1] += deltay;\n }\n };\n LGraphGroup.prototype.recomputeInsideNodes = function() {\n this._nodes.length = 0;\n var nodes = this.graph._nodes;\n var node_bounding = new Float32Array(4);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n var node2 = nodes[i2];\n node2.getBounding(node_bounding);\n if (!overlapBounding(this._bounding, node_bounding)) {\n continue;\n }\n this._nodes.push(node2);\n }\n };\n LGraphGroup.prototype.isPointInside = LGraphNode.prototype.isPointInside;\n LGraphGroup.prototype.setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;\n function DragAndScale(element, skip_events) {\n this.offset = new Float32Array([0, 0]);\n this.scale = 1;\n this.max_scale = 10;\n this.min_scale = 0.1;\n this.onredraw = null;\n this.enabled = true;\n this.last_mouse = [0, 0];\n this.element = null;\n this.visible_area = new Float32Array(4);\n if (element) {\n this.element = element;\n if (!skip_events) {\n this.bindEvents(element);\n }\n }\n }\n LiteGraph.DragAndScale = DragAndScale;\n DragAndScale.prototype.bindEvents = function(element) {\n this.last_mouse = new Float32Array(2);\n this._binded_mouse_callback = this.onMouse.bind(this);\n LiteGraph.pointerListenerAdd(element, \"down\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(element, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(element, \"up\", this._binded_mouse_callback);\n element.addEventListener(\n \"mousewheel\",\n this._binded_mouse_callback,\n false\n );\n element.addEventListener(\"wheel\", this._binded_mouse_callback, false);\n };\n DragAndScale.prototype.computeVisibleArea = function(viewport) {\n if (!this.element) {\n this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0;\n return;\n }\n var width2 = this.element.width;\n var height = this.element.height;\n var startx = -this.offset[0];\n var starty = -this.offset[1];\n if (viewport) {\n startx += viewport[0] / this.scale;\n starty += viewport[1] / this.scale;\n width2 = viewport[2];\n height = viewport[3];\n }\n var endx = startx + width2 / this.scale;\n var endy = starty + height / this.scale;\n this.visible_area[0] = startx;\n this.visible_area[1] = starty;\n this.visible_area[2] = endx - startx;\n this.visible_area[3] = endy - starty;\n };\n DragAndScale.prototype.onMouse = function(e) {\n if (!this.enabled) {\n return;\n }\n var canvas = this.element;\n var rect = canvas.getBoundingClientRect();\n var x2 = e.clientX - rect.left;\n var y2 = e.clientY - rect.top;\n e.canvasx = x2;\n e.canvasy = y2;\n e.dragging = this.dragging;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n var ignore = false;\n if (this.onmouse) {\n ignore = this.onmouse(e);\n }\n if (e.type == LiteGraph.pointerevents_method + \"down\" && is_inside) {\n this.dragging = true;\n LiteGraph.pointerListenerRemove(canvas, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(document, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(document, \"up\", this._binded_mouse_callback);\n } else if (e.type == LiteGraph.pointerevents_method + \"move\") {\n if (!ignore) {\n var deltax = x2 - this.last_mouse[0];\n var deltay = y2 - this.last_mouse[1];\n if (this.dragging) {\n this.mouseDrag(deltax, deltay);\n }\n }\n } else if (e.type == LiteGraph.pointerevents_method + \"up\") {\n this.dragging = false;\n LiteGraph.pointerListenerRemove(document, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerRemove(document, \"up\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(canvas, \"move\", this._binded_mouse_callback);\n } else if (is_inside && (e.type == \"mousewheel\" || e.type == \"wheel\" || e.type == \"DOMMouseScroll\")) {\n e.eventType = \"mousewheel\";\n if (e.type == \"wheel\") {\n e.wheel = -e.deltaY;\n } else {\n e.wheel = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60;\n }\n e.delta = e.wheelDelta ? e.wheelDelta / 40 : e.deltaY ? -e.deltaY / 3 : 0;\n this.changeDeltaScale(1 + e.delta * 0.05);\n }\n this.last_mouse[0] = x2;\n this.last_mouse[1] = y2;\n if (is_inside) {\n e.preventDefault();\n e.stopPropagation();\n return false;\n }\n };\n DragAndScale.prototype.toCanvasContext = function(ctx) {\n ctx.scale(this.scale, this.scale);\n ctx.translate(this.offset[0], this.offset[1]);\n };\n DragAndScale.prototype.convertOffsetToCanvas = function(pos2) {\n return [\n (pos2[0] + this.offset[0]) * this.scale,\n (pos2[1] + this.offset[1]) * this.scale\n ];\n };\n DragAndScale.prototype.convertCanvasToOffset = function(pos2, out) {\n out = out || [0, 0];\n out[0] = pos2[0] / this.scale - this.offset[0];\n out[1] = pos2[1] / this.scale - this.offset[1];\n return out;\n };\n DragAndScale.prototype.mouseDrag = function(x2, y2) {\n this.offset[0] += x2 / this.scale;\n this.offset[1] += y2 / this.scale;\n if (this.onredraw) {\n this.onredraw(this);\n }\n };\n DragAndScale.prototype.changeScale = function(value, zooming_center) {\n if (value < this.min_scale) {\n value = this.min_scale;\n } else if (value > this.max_scale) {\n value = this.max_scale;\n }\n if (value == this.scale) {\n return;\n }\n if (!this.element) {\n return;\n }\n var rect = this.element.getBoundingClientRect();\n if (!rect) {\n return;\n }\n zooming_center = zooming_center || [\n rect.width * 0.5,\n rect.height * 0.5\n ];\n var center = this.convertCanvasToOffset(zooming_center);\n this.scale = value;\n if (Math.abs(this.scale - 1) < 0.01) {\n this.scale = 1;\n }\n var new_center = this.convertCanvasToOffset(zooming_center);\n var delta_offset = [\n new_center[0] - center[0],\n new_center[1] - center[1]\n ];\n this.offset[0] += delta_offset[0];\n this.offset[1] += delta_offset[1];\n if (this.onredraw) {\n this.onredraw(this);\n }\n };\n DragAndScale.prototype.changeDeltaScale = function(value, zooming_center) {\n this.changeScale(this.scale * value, zooming_center);\n };\n DragAndScale.prototype.reset = function() {\n this.scale = 1;\n this.offset[0] = 0;\n this.offset[1] = 0;\n };\n function LGraphCanvas(canvas, graph, options) {\n this.options = options = options || {};\n this.background_image = LGraphCanvas.DEFAULT_BACKGROUND_IMAGE;\n if (canvas && canvas.constructor === String) {\n canvas = document.querySelector(canvas);\n }\n this.ds = new DragAndScale();\n this.zoom_modify_alpha = true;\n this.title_text_font = \"\" + LiteGraph.NODE_TEXT_SIZE + \"px Arial\";\n this.inner_text_font = \"normal \" + LiteGraph.NODE_SUBTEXT_SIZE + \"px Arial\";\n this.node_title_color = LiteGraph.NODE_TITLE_COLOR;\n this.default_link_color = LiteGraph.LINK_COLOR;\n this.default_connection_color = {\n input_off: \"#778\",\n input_on: \"#7F7\",\n //\"#BBD\"\n output_off: \"#778\",\n output_on: \"#7F7\"\n //\"#BBD\"\n };\n this.default_connection_color_byType = {\n /*number: \"#7F7\",\n string: \"#77F\",\n boolean: \"#F77\",*/\n };\n this.default_connection_color_byTypeOff = {\n /*number: \"#474\",\n string: \"#447\",\n boolean: \"#744\",*/\n };\n this.highquality_render = true;\n this.use_gradients = false;\n this.editor_alpha = 1;\n this.pause_rendering = false;\n this.clear_background = true;\n this.clear_background_color = \"#222\";\n this.read_only = false;\n this.render_only_selected = true;\n this.live_mode = false;\n this.show_info = true;\n this.allow_dragcanvas = true;\n this.allow_dragnodes = true;\n this.allow_interaction = true;\n this.multi_select = false;\n this.allow_searchbox = true;\n this.allow_reconnect_links = true;\n this.align_to_grid = false;\n this.drag_mode = false;\n this.dragging_rectangle = null;\n this.filter = null;\n this.set_canvas_dirty_on_mouse_event = true;\n this.always_render_background = false;\n this.render_shadows = true;\n this.render_canvas_border = true;\n this.render_connections_shadows = false;\n this.render_connections_border = true;\n this.render_curved_connections = false;\n this.render_connection_arrows = false;\n this.render_collapsed_slots = true;\n this.render_execution_order = false;\n this.render_title_colored = true;\n this.render_link_tooltip = true;\n this.links_render_mode = LiteGraph.SPLINE_LINK;\n this.mouse = [0, 0];\n this.graph_mouse = [0, 0];\n this.canvas_mouse = this.graph_mouse;\n this.onSearchBox = null;\n this.onSearchBoxSelection = null;\n this.onMouse = null;\n this.onDrawBackground = null;\n this.onDrawForeground = null;\n this.onDrawOverlay = null;\n this.onDrawLinkTooltip = null;\n this.onNodeMoved = null;\n this.onSelectionChange = null;\n this.onConnectingChange = null;\n this.onBeforeChange = null;\n this.onAfterChange = null;\n this.connections_width = 3;\n this.round_radius = 8;\n this.current_node = null;\n this.node_widget = null;\n this.over_link_center = null;\n this.last_mouse_position = [0, 0];\n this.visible_area = this.ds.visible_area;\n this.visible_links = [];\n this.connecting_links = null;\n this.viewport = options.viewport || null;\n if (graph) {\n graph.attachCanvas(this);\n }\n this.setCanvas(canvas, options.skip_events);\n this.clear();\n if (!options.skip_render) {\n this.startRendering();\n }\n this.autoresize = options.autoresize;\n }\n globalThis.LGraphCanvas = LiteGraph.LGraphCanvas = LGraphCanvas;\n LGraphCanvas.DEFAULT_BACKGROUND_IMAGE = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=\";\n LGraphCanvas.link_type_colors = {\n \"-1\": LiteGraph.EVENT_LINK_COLOR,\n number: \"#AAA\",\n node: \"#DCA\"\n };\n LGraphCanvas.gradients = {};\n LGraphCanvas.prototype.clear = function() {\n this.frame = 0;\n this.last_draw_time = 0;\n this.render_time = 0;\n this.fps = 0;\n this.dragging_rectangle = null;\n this.selected_nodes = {};\n this.selected_group = null;\n this.visible_nodes = [];\n this.node_dragged = null;\n this.node_over = null;\n this.node_capturing_input = null;\n this.connecting_links = null;\n this.highlighted_links = {};\n this.dragging_canvas = false;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.dirty_area = null;\n this.node_in_panel = null;\n this.node_widget = null;\n this.last_mouse = [0, 0];\n this.last_mouseclick = 0;\n this.pointer_is_down = false;\n this.pointer_is_double = false;\n this.visible_area.set([0, 0, 0, 0]);\n if (this.onClear) {\n this.onClear();\n }\n };\n LGraphCanvas.prototype.setGraph = function(graph, skip_clear) {\n if (this.graph == graph) {\n return;\n }\n if (!skip_clear) {\n this.clear();\n }\n if (!graph && this.graph) {\n this.graph.detachCanvas(this);\n return;\n }\n graph.attachCanvas(this);\n if (this._graph_stack)\n this._graph_stack = null;\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.getTopGraph = function() {\n if (this._graph_stack.length)\n return this._graph_stack[0];\n return this.graph;\n };\n LGraphCanvas.prototype.openSubgraph = function(graph) {\n if (!graph) {\n throw \"graph cannot be null\";\n }\n if (this.graph == graph) {\n throw \"graph cannot be the same\";\n }\n this.clear();\n if (this.graph) {\n if (!this._graph_stack) {\n this._graph_stack = [];\n }\n this._graph_stack.push(this.graph);\n }\n graph.attachCanvas(this);\n this.checkPanels();\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.closeSubgraph = function() {\n if (!this._graph_stack || this._graph_stack.length == 0) {\n return;\n }\n var subgraph_node = this.graph._subgraph_node;\n var graph = this._graph_stack.pop();\n this.selected_nodes = {};\n this.highlighted_links = {};\n graph.attachCanvas(this);\n this.setDirty(true, true);\n if (subgraph_node) {\n this.centerOnNode(subgraph_node);\n this.selectNodes([subgraph_node]);\n }\n this.ds.offset = [0, 0];\n this.ds.scale = 1;\n };\n LGraphCanvas.prototype.getCurrentGraph = function() {\n return this.graph;\n };\n LGraphCanvas.prototype.setCanvas = function(canvas, skip_events) {\n if (canvas) {\n if (canvas.constructor === String) {\n canvas = document.getElementById(canvas);\n if (!canvas) {\n throw \"Error creating LiteGraph canvas: Canvas not found\";\n }\n }\n }\n if (canvas === this.canvas) {\n return;\n }\n if (!canvas && this.canvas) {\n if (!skip_events) {\n this.unbindEvents();\n }\n }\n this.canvas = canvas;\n this.ds.element = canvas;\n if (!canvas) {\n return;\n }\n canvas.className += \" lgraphcanvas\";\n canvas.data = this;\n canvas.tabindex = \"1\";\n this.bgcanvas = null;\n if (!this.bgcanvas) {\n this.bgcanvas = document.createElement(\"canvas\");\n this.bgcanvas.width = this.canvas.width;\n this.bgcanvas.height = this.canvas.height;\n }\n if (canvas.getContext == null) {\n if (canvas.localName != \"canvas\") {\n throw \"Element supplied for LGraphCanvas must be a element, you passed a \" + canvas.localName;\n }\n throw \"This browser doesn't support Canvas\";\n }\n var ctx = this.ctx = canvas.getContext(\"2d\");\n if (ctx == null) {\n if (!canvas.webgl_enabled) {\n console.warn(\n \"This canvas seems to be WebGL, enabling WebGL renderer\"\n );\n }\n this.enableWebGL();\n }\n if (!skip_events) {\n this.bindEvents();\n }\n };\n LGraphCanvas.prototype._doNothing = function doNothing(e) {\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype._doReturnTrue = function doNothing(e) {\n e.preventDefault();\n return true;\n };\n LGraphCanvas.prototype.bindEvents = function() {\n if (this._events_binded) {\n console.warn(\"LGraphCanvas: events already binded\");\n return;\n }\n var canvas = this.canvas;\n var ref_window2 = this.getCanvasWindow();\n var document2 = ref_window2.document;\n this._mousedown_callback = this.processMouseDown.bind(this);\n this._mousewheel_callback = this.processMouseWheel.bind(this);\n this._mousemove_callback = this.processMouseMove.bind(this);\n this._mouseup_callback = this.processMouseUp.bind(this);\n LiteGraph.pointerListenerAdd(canvas, \"down\", this._mousedown_callback, true);\n canvas.addEventListener(\"mousewheel\", this._mousewheel_callback, false);\n LiteGraph.pointerListenerAdd(canvas, \"up\", this._mouseup_callback, true);\n LiteGraph.pointerListenerAdd(canvas, \"move\", this._mousemove_callback);\n canvas.addEventListener(\"contextmenu\", this._doNothing);\n canvas.addEventListener(\n \"DOMMouseScroll\",\n this._mousewheel_callback,\n false\n );\n this._key_callback = this.processKey.bind(this);\n canvas.addEventListener(\"keydown\", this._key_callback, true);\n document2.addEventListener(\"keyup\", this._key_callback, true);\n this._ondrop_callback = this.processDrop.bind(this);\n canvas.addEventListener(\"dragover\", this._doNothing, false);\n canvas.addEventListener(\"dragend\", this._doNothing, false);\n canvas.addEventListener(\"drop\", this._ondrop_callback, false);\n canvas.addEventListener(\"dragenter\", this._doReturnTrue, false);\n this._events_binded = true;\n };\n LGraphCanvas.prototype.unbindEvents = function() {\n if (!this._events_binded) {\n console.warn(\"LGraphCanvas: no events binded\");\n return;\n }\n var ref_window2 = this.getCanvasWindow();\n var document2 = ref_window2.document;\n LiteGraph.pointerListenerRemove(this.canvas, \"move\", this._mousemove_callback);\n LiteGraph.pointerListenerRemove(this.canvas, \"up\", this._mouseup_callback);\n LiteGraph.pointerListenerRemove(this.canvas, \"down\", this._mousedown_callback);\n this.canvas.removeEventListener(\n \"mousewheel\",\n this._mousewheel_callback\n );\n this.canvas.removeEventListener(\n \"DOMMouseScroll\",\n this._mousewheel_callback\n );\n this.canvas.removeEventListener(\"keydown\", this._key_callback);\n document2.removeEventListener(\"keyup\", this._key_callback);\n this.canvas.removeEventListener(\"contextmenu\", this._doNothing);\n this.canvas.removeEventListener(\"drop\", this._ondrop_callback);\n this.canvas.removeEventListener(\"dragenter\", this._doReturnTrue);\n this._mousedown_callback = null;\n this._mousewheel_callback = null;\n this._key_callback = null;\n this._ondrop_callback = null;\n this._events_binded = false;\n };\n LGraphCanvas.getFileExtension = function(url) {\n var question = url.indexOf(\"?\");\n if (question != -1) {\n url = url.substr(0, question);\n }\n var point = url.lastIndexOf(\".\");\n if (point == -1) {\n return \"\";\n }\n return url.substr(point + 1).toLowerCase();\n };\n LGraphCanvas.prototype.enableWebGL = function() {\n if (typeof GL === \"undefined\") {\n throw \"litegl.js must be included to use a WebGL canvas\";\n }\n if (typeof enableWebGLCanvas === \"undefined\") {\n throw \"webglCanvas.js must be included to use this feature\";\n }\n this.gl = this.ctx = enableWebGLCanvas(this.canvas);\n this.ctx.webgl = true;\n this.bgcanvas = this.canvas;\n this.bgctx = this.gl;\n this.canvas.webgl_enabled = true;\n };\n LGraphCanvas.prototype.setDirty = function(fgcanvas, bgcanvas) {\n if (fgcanvas) {\n this.dirty_canvas = true;\n }\n if (bgcanvas) {\n this.dirty_bgcanvas = true;\n }\n };\n LGraphCanvas.prototype.getCanvasWindow = function() {\n if (!this.canvas) {\n return window;\n }\n var doc = this.canvas.ownerDocument;\n return doc.defaultView || doc.parentWindow;\n };\n LGraphCanvas.prototype.startRendering = function() {\n if (this.is_rendering) {\n return;\n }\n this.is_rendering = true;\n renderFrame.call(this);\n function renderFrame() {\n if (!this.pause_rendering) {\n this.draw();\n }\n var window2 = this.getCanvasWindow();\n if (this.is_rendering) {\n window2.requestAnimationFrame(renderFrame.bind(this));\n }\n }\n };\n LGraphCanvas.prototype.stopRendering = function() {\n this.is_rendering = false;\n };\n LGraphCanvas.prototype.blockClick = function() {\n this.block_click = true;\n this.last_mouseclick = 0;\n };\n LGraphCanvas.prototype.processMouseDown = function(e) {\n var _a;\n if (this.set_canvas_dirty_on_mouse_event)\n this.dirty_canvas = true;\n if (!this.graph) {\n return;\n }\n this.adjustMouseEvent(e);\n var ref_window2 = this.getCanvasWindow();\n ref_window2.document;\n LGraphCanvas.active_canvas = this;\n var that2 = this;\n var x2 = e.clientX;\n var y2 = e.clientY;\n this.ds.viewport = this.viewport;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!this.options.skip_events) {\n LiteGraph.pointerListenerRemove(this.canvas, \"move\", this._mousemove_callback);\n LiteGraph.pointerListenerAdd(ref_window2.document, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerAdd(ref_window2.document, \"up\", this._mouseup_callback, true);\n }\n if (!is_inside) {\n return;\n }\n var node2 = this.graph.getNodeOnPos(e.canvasX, e.canvasY, this.visible_nodes, 5);\n var skip_action = false;\n var now = LiteGraph.getTime();\n var is_primary = e.isPrimary === void 0 || !e.isPrimary;\n var is_double_click = now - this.last_mouseclick < 300;\n this.mouse[0] = e.clientX;\n this.mouse[1] = e.clientY;\n this.graph_mouse[0] = e.canvasX;\n this.graph_mouse[1] = e.canvasY;\n this.last_click_position = [this.mouse[0], this.mouse[1]];\n if (this.pointer_is_down && is_primary) {\n this.pointer_is_double = true;\n } else {\n this.pointer_is_double = false;\n }\n this.pointer_is_down = true;\n this.canvas.focus();\n LiteGraph.closeAllContextMenus(ref_window2);\n if (this.onMouse) {\n if (this.onMouse(e) == true)\n return;\n }\n if (e.which == 1 && !this.pointer_is_double) {\n if (e.ctrlKey && !e.altKey) {\n this.dragging_rectangle = new Float32Array(4);\n this.dragging_rectangle[0] = e.canvasX;\n this.dragging_rectangle[1] = e.canvasY;\n this.dragging_rectangle[2] = 1;\n this.dragging_rectangle[3] = 1;\n skip_action = true;\n }\n if (LiteGraph.alt_drag_do_clone_nodes && e.altKey && !e.ctrlKey && node2 && this.allow_interaction && !skip_action && !this.read_only) {\n const cloned = node2.clone();\n if (cloned) {\n cloned.pos[0] += 5;\n cloned.pos[1] += 5;\n this.graph.add(cloned, false, { doCalcSize: false });\n node2 = cloned;\n skip_action = true;\n if (!block_drag_node) {\n if (this.allow_dragnodes) {\n this.graph.beforeChange();\n this.node_dragged = node2;\n }\n if (!this.selected_nodes[node2.id]) {\n this.processNodeSelected(node2, e);\n }\n }\n }\n }\n var clicking_canvas_bg = false;\n if (node2 && (this.allow_interaction || node2.flags.allow_interaction) && !skip_action && !this.read_only) {\n if (!this.live_mode && !node2.flags.pinned) {\n this.bringToFront(node2);\n }\n if (this.allow_interaction && !this.connecting_links && !node2.flags.collapsed && !this.live_mode) {\n if (!skip_action && node2.resizable !== false && node2.inResizeCorner(e.canvasX, e.canvasY)) {\n this.graph.beforeChange();\n this.resizing_node = node2;\n this.canvas.style.cursor = \"se-resize\";\n skip_action = true;\n } else {\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n var output = node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n if (isInsideRectangle(\n e.canvasX,\n e.canvasY,\n link_pos[0] - 15,\n link_pos[1] - 10,\n 30,\n 20\n )) {\n if (e.shiftKey) {\n if (((_a = output.links) == null ? void 0 : _a.length) > 0) {\n this.connecting_links = [];\n for (const linkId of output.links) {\n const link2 = this.graph.links[linkId];\n const slot = link2.target_slot;\n const linked_node = this.graph._nodes_by_id[link2.target_id];\n const input2 = linked_node.inputs[slot];\n const pos3 = linked_node.getConnectionPos(true, slot);\n this.connecting_links.push({\n node: linked_node,\n slot,\n input: input2,\n output: null,\n pos: pos3\n });\n }\n skip_action = true;\n break;\n }\n }\n output.slot_index = i2;\n this.connecting_links = [\n {\n node: node2,\n slot: i2,\n input: null,\n output,\n pos: link_pos\n }\n ];\n if (LiteGraph.shift_click_do_break_link_from) {\n if (e.shiftKey) {\n node2.disconnectOutput(i2);\n }\n } else if (LiteGraph.ctrl_alt_click_do_break_link) {\n if (e.ctrlKey && e.altKey && !e.shiftKey) {\n node2.disconnectOutput(i2);\n }\n }\n if (is_double_click) {\n if (node2.onOutputDblClick) {\n node2.onOutputDblClick(i2, e);\n }\n } else {\n if (node2.onOutputClick) {\n node2.onOutputClick(i2, e);\n }\n }\n skip_action = true;\n break;\n }\n }\n }\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n if (isInsideRectangle(\n e.canvasX,\n e.canvasY,\n link_pos[0] - 15,\n link_pos[1] - 10,\n 30,\n 20\n )) {\n if (is_double_click) {\n if (node2.onInputDblClick) {\n node2.onInputDblClick(i2, e);\n }\n } else {\n if (node2.onInputClick) {\n node2.onInputClick(i2, e);\n }\n }\n if (input.link !== null) {\n var link_info = this.graph.links[input.link];\n if (LiteGraph.click_do_break_link_to || LiteGraph.ctrl_alt_click_do_break_link && e.ctrlKey && e.altKey && !e.shiftKey) {\n node2.disconnectInput(i2);\n } else if (this.allow_reconnect_links || //this.move_destination_link_without_shift ||\n e.shiftKey) {\n if (!LiteGraph.click_do_break_link_to) {\n node2.disconnectInput(i2);\n }\n const linked_node = this.graph._nodes_by_id[link_info.origin_id];\n const slot = link_info.origin_slot;\n this.connecting_links = [\n {\n node: linked_node,\n slot,\n input: null,\n output: linked_node.outputs[slot],\n pos: linked_node.getConnectionPos(false, slot)\n }\n ];\n this.dirty_bgcanvas = true;\n skip_action = true;\n } else ;\n }\n if (!skip_action) {\n this.connecting_links = [\n {\n node: node2,\n slot: i2,\n input,\n output: null,\n pos: link_pos\n }\n ];\n this.dirty_bgcanvas = true;\n skip_action = true;\n }\n break;\n }\n }\n }\n }\n }\n if (!skip_action) {\n var block_drag_node = false;\n if (node2 && node2.flags && node2.flags.pinned) {\n block_drag_node = true;\n }\n var pos2 = [e.canvasX - node2.pos[0], e.canvasY - node2.pos[1]];\n var widget = this.processNodeWidgets(node2, this.graph_mouse, e);\n if (widget) {\n block_drag_node = true;\n this.node_widget = [node2, widget];\n }\n if (this.allow_interaction && is_double_click && this.selected_nodes[node2.id]) {\n if (node2.onDblClick) {\n node2.onDblClick(e, pos2, this);\n }\n this.processNodeDblClicked(node2);\n block_drag_node = true;\n }\n if (node2.onMouseDown && node2.onMouseDown(e, pos2, this)) {\n block_drag_node = true;\n } else {\n if (node2.subgraph && !node2.skip_subgraph_button) {\n if (!node2.flags.collapsed && pos2[0] > node2.size[0] - LiteGraph.NODE_TITLE_HEIGHT && pos2[1] < 0) {\n var that2 = this;\n setTimeout(function() {\n that2.openSubgraph(node2.subgraph);\n }, 10);\n }\n }\n if (this.live_mode) {\n clicking_canvas_bg = true;\n block_drag_node = true;\n }\n }\n if (!block_drag_node) {\n if (this.allow_dragnodes) {\n this.graph.beforeChange();\n this.node_dragged = node2;\n }\n if (!(e.shiftKey && !e.ctrlKey && !e.altKey) || !node2.is_selected) {\n this.processNodeSelected(node2, e);\n }\n } else {\n if (!node2.is_selected) this.processNodeSelected(node2, e);\n }\n this.dirty_canvas = true;\n }\n } else {\n if (!skip_action) {\n if (!this.read_only) {\n for (var i2 = 0; i2 < this.visible_links.length; ++i2) {\n var link = this.visible_links[i2];\n var center = link._pos;\n if (!center || e.canvasX < center[0] - 4 || e.canvasX > center[0] + 4 || e.canvasY < center[1] - 4 || e.canvasY > center[1] + 4) {\n continue;\n }\n this.showLinkMenu(link, e);\n this.over_link_center = null;\n break;\n }\n }\n this.selected_group = this.graph.getGroupOnPos(e.canvasX, e.canvasY);\n this.selected_group_resizing = false;\n if (this.selected_group && !this.read_only) {\n if (e.ctrlKey) {\n this.dragging_rectangle = null;\n }\n var dist = distance([e.canvasX, e.canvasY], [this.selected_group.pos[0] + this.selected_group.size[0], this.selected_group.pos[1] + this.selected_group.size[1]]);\n if (dist * this.ds.scale < 10) {\n this.selected_group_resizing = true;\n } else {\n this.selected_group.recomputeInsideNodes();\n }\n }\n if (is_double_click && !this.read_only) {\n if (this.allow_searchbox) {\n this.showSearchBox(e);\n e.preventDefault();\n e.stopPropagation();\n }\n this.canvas.dispatchEvent(new CustomEvent(\n \"litegraph:canvas\",\n {\n bubbles: true,\n detail: {\n subType: \"empty-double-click\",\n originalEvent: e\n }\n }\n ));\n }\n clicking_canvas_bg = true;\n }\n }\n if (!skip_action && clicking_canvas_bg && this.allow_dragcanvas) {\n this.dragging_canvas = true;\n }\n } else if (e.which == 2) {\n if (LiteGraph.middle_click_slot_add_default_node) {\n if (node2 && this.allow_interaction && !skip_action && !this.read_only) {\n if (!this.connecting_links && !node2.flags.collapsed && !this.live_mode) {\n var mClikSlot = false;\n var mClikSlot_index = false;\n var mClikSlot_isOut = false;\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n var output = node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n if (isInsideRectangle(e.canvasX, e.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {\n mClikSlot = output;\n mClikSlot_index = i2;\n mClikSlot_isOut = true;\n break;\n }\n }\n }\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n if (isInsideRectangle(e.canvasX, e.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {\n mClikSlot = input;\n mClikSlot_index = i2;\n mClikSlot_isOut = false;\n break;\n }\n }\n }\n if (mClikSlot && mClikSlot_index !== false) {\n var alphaPosY = 0.5 - (mClikSlot_index + 1) / (mClikSlot_isOut ? node2.outputs.length : node2.inputs.length);\n var node_bounding = node2.getBounding();\n var posRef = [\n !mClikSlot_isOut ? node_bounding[0] : node_bounding[0] + node_bounding[2],\n e.canvasY - 80\n // + node_bounding[0]/this.canvas.width*66 // vertical \"derive\"\n ];\n this.createDefaultNodeForSlot({\n nodeFrom: !mClikSlot_isOut ? null : node2,\n slotFrom: !mClikSlot_isOut ? null : mClikSlot_index,\n nodeTo: !mClikSlot_isOut ? node2 : null,\n slotTo: !mClikSlot_isOut ? mClikSlot_index : null,\n position: posRef,\n nodeType: \"AUTO\",\n posAdd: [!mClikSlot_isOut ? -30 : 30, -alphaPosY * 130],\n posSizeFix: [!mClikSlot_isOut ? -1 : 0, 0]\n //-alphaPosY*2*/\n });\n skip_action = true;\n }\n }\n }\n }\n if (!skip_action && this.allow_dragcanvas) {\n this.dragging_canvas = true;\n }\n } else if (e.which == 3 || this.pointer_is_double) {\n if (this.allow_interaction && !skip_action && !this.read_only) {\n if (node2) {\n if (Object.keys(this.selected_nodes).length && (this.selected_nodes[node2.id] || e.shiftKey || e.ctrlKey || e.metaKey)) {\n if (!this.selected_nodes[node2.id]) this.selectNodes([node2], true);\n } else {\n this.selectNodes([node2]);\n }\n }\n this.processContextMenu(node2, e);\n }\n }\n this.last_mouse[0] = e.clientX;\n this.last_mouse[1] = e.clientY;\n this.last_mouseclick = LiteGraph.getTime();\n this.last_mouse_dragging = true;\n this.graph.change();\n if (!ref_window2.document.activeElement || ref_window2.document.activeElement.nodeName.toLowerCase() != \"input\" && ref_window2.document.activeElement.nodeName.toLowerCase() != \"textarea\") {\n e.preventDefault();\n }\n e.stopPropagation();\n if (this.onMouseDown) {\n this.onMouseDown(e);\n }\n return false;\n };\n LGraphCanvas.prototype.processMouseMove = function(e) {\n if (this.autoresize) {\n this.resize();\n }\n if (this.set_canvas_dirty_on_mouse_event)\n this.dirty_canvas = true;\n if (!this.graph) {\n return;\n }\n LGraphCanvas.active_canvas = this;\n this.adjustMouseEvent(e);\n var mouse = [e.clientX, e.clientY];\n this.mouse[0] = mouse[0];\n this.mouse[1] = mouse[1];\n var delta2 = [\n mouse[0] - this.last_mouse[0],\n mouse[1] - this.last_mouse[1]\n ];\n this.last_mouse = mouse;\n this.graph_mouse[0] = e.canvasX;\n this.graph_mouse[1] = e.canvasY;\n if (this.block_click) {\n e.preventDefault();\n return false;\n }\n e.dragging = this.last_mouse_dragging;\n if (this.node_widget) {\n this.processNodeWidgets(\n this.node_widget[0],\n this.graph_mouse,\n e,\n this.node_widget[1]\n );\n this.dirty_canvas = true;\n }\n var node2 = this.graph.getNodeOnPos(e.canvasX, e.canvasY, this.visible_nodes);\n if (this.dragging_rectangle) {\n this.dragging_rectangle[2] = e.canvasX - this.dragging_rectangle[0];\n this.dragging_rectangle[3] = e.canvasY - this.dragging_rectangle[1];\n this.dirty_canvas = true;\n } else if (this.selected_group && !this.read_only) {\n if (this.selected_group_resizing) {\n this.selected_group.size = [\n e.canvasX - this.selected_group.pos[0],\n e.canvasY - this.selected_group.pos[1]\n ];\n } else {\n var deltax = delta2[0] / this.ds.scale;\n var deltay = delta2[1] / this.ds.scale;\n this.selected_group.move(deltax, deltay, e.ctrlKey);\n if (this.selected_group._nodes.length) {\n this.dirty_canvas = true;\n }\n }\n this.dirty_bgcanvas = true;\n } else if (this.dragging_canvas) {\n this.ds.offset[0] += delta2[0] / this.ds.scale;\n this.ds.offset[1] += delta2[1] / this.ds.scale;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n } else if ((this.allow_interaction || node2 && node2.flags.allow_interaction) && !this.read_only) {\n if (this.connecting_links) {\n this.dirty_canvas = true;\n }\n for (var i2 = 0, l = this.graph._nodes.length; i2 < l; ++i2) {\n if (this.graph._nodes[i2].mouseOver && node2 != this.graph._nodes[i2]) {\n this.graph._nodes[i2].mouseOver = false;\n if (this.node_over && this.node_over.onMouseLeave) {\n this.node_over.onMouseLeave(e);\n }\n this.node_over = null;\n this.dirty_canvas = true;\n }\n }\n if (node2) {\n if (node2.redraw_on_mouse)\n this.dirty_canvas = true;\n if (!node2.mouseOver) {\n node2.mouseOver = true;\n this.node_over = node2;\n this.dirty_canvas = true;\n if (node2.onMouseEnter) {\n node2.onMouseEnter(e);\n }\n }\n if (node2.onMouseMove) {\n node2.onMouseMove(e, [e.canvasX - node2.pos[0], e.canvasY - node2.pos[1]], this);\n }\n if (this.connecting_links) {\n const firstLink = this.connecting_links[0];\n if (firstLink.output) {\n var pos2 = this._highlight_input || [0, 0];\n if (this.isOverNodeBox(node2, e.canvasX, e.canvasY)) ;\n else {\n var slot = this.isOverNodeInput(node2, e.canvasX, e.canvasY, pos2);\n if (slot != -1 && node2.inputs[slot] && LiteGraph.isValidConnection(firstLink.output.type, node2.inputs[slot].type)) {\n this._highlight_input = pos2;\n this._highlight_input_slot = node2.inputs[slot];\n } else {\n this._highlight_input = null;\n this._highlight_input_slot = null;\n }\n }\n } else if (firstLink.input) {\n var pos2 = this._highlight_output || [0, 0];\n if (this.isOverNodeBox(node2, e.canvasX, e.canvasY)) ;\n else {\n var slot = this.isOverNodeOutput(node2, e.canvasX, e.canvasY, pos2);\n if (slot != -1 && node2.outputs[slot] && LiteGraph.isValidConnection(firstLink.input.type, node2.outputs[slot].type)) {\n this._highlight_output = pos2;\n } else {\n this._highlight_output = null;\n }\n }\n }\n }\n if (this.canvas) {\n if (node2.inResizeCorner(e.canvasX, e.canvasY)) {\n this.canvas.style.cursor = \"se-resize\";\n } else {\n this.canvas.style.cursor = \"crosshair\";\n }\n }\n } else {\n var over_link = null;\n for (var i2 = 0; i2 < this.visible_links.length; ++i2) {\n var link = this.visible_links[i2];\n var center = link._pos;\n if (!center || e.canvasX < center[0] - 4 || e.canvasX > center[0] + 4 || e.canvasY < center[1] - 4 || e.canvasY > center[1] + 4) {\n continue;\n }\n over_link = link;\n break;\n }\n if (over_link != this.over_link_center) {\n this.over_link_center = over_link;\n this.dirty_canvas = true;\n }\n if (this.canvas) {\n this.canvas.style.cursor = \"\";\n }\n }\n if (this.node_capturing_input && this.node_capturing_input != node2 && this.node_capturing_input.onMouseMove) {\n this.node_capturing_input.onMouseMove(e, [e.canvasX - this.node_capturing_input.pos[0], e.canvasY - this.node_capturing_input.pos[1]], this);\n }\n if (this.node_dragged && !this.live_mode) {\n for (var i2 in this.selected_nodes) {\n var n = this.selected_nodes[i2];\n n.pos[0] += delta2[0] / this.ds.scale;\n n.pos[1] += delta2[1] / this.ds.scale;\n if (!n.is_selected) this.processNodeSelected(n, e);\n }\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n }\n if (this.resizing_node && !this.live_mode) {\n var desired_size = [e.canvasX - this.resizing_node.pos[0], e.canvasY - this.resizing_node.pos[1]];\n var min_size = this.resizing_node.computeSize();\n desired_size[0] = Math.max(min_size[0], desired_size[0]);\n desired_size[1] = Math.max(min_size[1], desired_size[1]);\n this.resizing_node.setSize(desired_size);\n this.canvas.style.cursor = \"se-resize\";\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n }\n }\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.processMouseUp = function(e) {\n var is_primary = e.isPrimary === void 0 || e.isPrimary;\n if (!is_primary) {\n return false;\n }\n if (!this.graph)\n return;\n var window2 = this.getCanvasWindow();\n var document2 = window2.document;\n LGraphCanvas.active_canvas = this;\n if (!this.options.skip_events) {\n LiteGraph.pointerListenerRemove(document2, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerAdd(this.canvas, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerRemove(document2, \"up\", this._mouseup_callback, true);\n }\n this.adjustMouseEvent(e);\n var now = LiteGraph.getTime();\n e.click_time = now - this.last_mouseclick;\n this.last_mouse_dragging = false;\n this.last_click_position = null;\n if (this.block_click) {\n this.block_click = false;\n }\n if (e.which == 1) {\n if (this.node_widget) {\n this.processNodeWidgets(this.node_widget[0], this.graph_mouse, e);\n }\n this.node_widget = null;\n if (this.selected_group) {\n var diffx = this.selected_group.pos[0] - Math.round(this.selected_group.pos[0]);\n var diffy = this.selected_group.pos[1] - Math.round(this.selected_group.pos[1]);\n this.selected_group.move(diffx, diffy, e.ctrlKey);\n this.selected_group.pos[0] = Math.round(\n this.selected_group.pos[0]\n );\n this.selected_group.pos[1] = Math.round(\n this.selected_group.pos[1]\n );\n if (this.selected_group._nodes.length) {\n this.dirty_canvas = true;\n }\n this.selected_group = null;\n }\n this.selected_group_resizing = false;\n var node2 = this.graph.getNodeOnPos(\n e.canvasX,\n e.canvasY,\n this.visible_nodes\n );\n if (this.dragging_rectangle) {\n if (this.graph) {\n var nodes = this.graph._nodes;\n var node_bounding = new Float32Array(4);\n var w2 = Math.abs(this.dragging_rectangle[2]);\n var h = Math.abs(this.dragging_rectangle[3]);\n var startx = this.dragging_rectangle[2] < 0 ? this.dragging_rectangle[0] - w2 : this.dragging_rectangle[0];\n var starty = this.dragging_rectangle[3] < 0 ? this.dragging_rectangle[1] - h : this.dragging_rectangle[1];\n this.dragging_rectangle[0] = startx;\n this.dragging_rectangle[1] = starty;\n this.dragging_rectangle[2] = w2;\n this.dragging_rectangle[3] = h;\n if (!node2 || w2 > 10 && h > 10) {\n var to_select = [];\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n var nodeX = nodes[i2];\n nodeX.getBounding(node_bounding);\n if (!overlapBounding(\n this.dragging_rectangle,\n node_bounding\n )) {\n continue;\n }\n to_select.push(nodeX);\n }\n if (to_select.length) {\n this.selectNodes(to_select, e.shiftKey);\n }\n } else {\n this.selectNodes([node2], e.shiftKey || e.ctrlKey);\n }\n }\n this.dragging_rectangle = null;\n } else if (this.connecting_links) {\n if (node2) {\n for (const link of this.connecting_links) {\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n if (link.output) {\n var slot = this.isOverNodeInput(\n node2,\n e.canvasX,\n e.canvasY\n );\n if (slot != -1) {\n link.node.connect(link.slot, node2, slot);\n } else {\n link.node.connectByType(link.slot, node2, link.output.type);\n }\n } else if (link.input) {\n var slot = this.isOverNodeOutput(\n node2,\n e.canvasX,\n e.canvasY\n );\n if (slot != -1) {\n node2.connect(slot, link.node, link.slot);\n } else {\n link.node.connectByTypeOutput(link.slot, node2, link.input.type);\n }\n }\n }\n } else {\n const firstLink = this.connecting_links[0];\n const linkReleaseContext = firstLink.output ? {\n node_from: firstLink.node,\n slot_from: firstLink.output,\n type_filter_in: firstLink.output.type\n } : {\n node_to: firstLink.node,\n slot_from: firstLink.input,\n type_filter_out: firstLink.input.type\n };\n const linkReleaseContextExtended = {\n links: this.connecting_links\n };\n this.canvas.dispatchEvent(new CustomEvent(\n \"litegraph:canvas\",\n {\n bubbles: true,\n detail: {\n subType: \"empty-release\",\n originalEvent: e,\n linkReleaseContext: linkReleaseContextExtended\n }\n }\n ));\n if (LiteGraph.release_link_on_empty_shows_menu) {\n if (e.shiftKey) {\n if (this.allow_searchbox) {\n this.showSearchBox(e, linkReleaseContext);\n }\n } else {\n if (firstLink.output) {\n this.showConnectionMenu({ nodeFrom: firstLink.node, slotFrom: firstLink.output, e });\n } else if (firstLink.input) {\n this.showConnectionMenu({ nodeTo: firstLink.node, slotTo: firstLink.input, e });\n }\n }\n }\n }\n this.connecting_links = null;\n } else if (this.resizing_node) {\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.graph.afterChange(this.resizing_node);\n this.resizing_node = null;\n } else if (this.node_dragged) {\n var node2 = this.node_dragged;\n if (node2 && e.click_time < 300 && isInsideRectangle(e.canvasX, e.canvasY, node2.pos[0], node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT)) {\n node2.collapse();\n }\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.node_dragged.pos[0] = Math.round(this.node_dragged.pos[0]);\n this.node_dragged.pos[1] = Math.round(this.node_dragged.pos[1]);\n if (this.graph.config.align_to_grid || this.align_to_grid) {\n this.node_dragged.alignToGrid();\n }\n if (this.onNodeMoved)\n this.onNodeMoved(this.node_dragged);\n this.graph.afterChange(this.node_dragged);\n this.node_dragged = null;\n } else {\n var node2 = this.graph.getNodeOnPos(\n e.canvasX,\n e.canvasY,\n this.visible_nodes\n );\n if (!node2 && e.click_time < 300) {\n this.deselectAllNodes();\n }\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n if (this.node_over && this.node_over.onMouseUp) {\n this.node_over.onMouseUp(e, [e.canvasX - this.node_over.pos[0], e.canvasY - this.node_over.pos[1]], this);\n }\n if (this.node_capturing_input && this.node_capturing_input.onMouseUp) {\n this.node_capturing_input.onMouseUp(e, [\n e.canvasX - this.node_capturing_input.pos[0],\n e.canvasY - this.node_capturing_input.pos[1]\n ]);\n }\n }\n } else if (e.which == 2) {\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n } else if (e.which == 3) {\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n }\n if (is_primary) {\n this.pointer_is_down = false;\n this.pointer_is_double = false;\n }\n this.graph.change();\n e.stopPropagation();\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.processMouseWheel = function(e) {\n if (!this.graph || !this.allow_dragcanvas) {\n return;\n }\n var delta2 = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60;\n this.adjustMouseEvent(e);\n var x2 = e.clientX;\n var y2 = e.clientY;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!is_inside)\n return;\n var scale = this.ds.scale;\n if (delta2 > 0) {\n scale *= 1.1;\n } else if (delta2 < 0) {\n scale *= 1 / 1.1;\n }\n this.ds.changeScale(scale, [e.clientX, e.clientY]);\n this.graph.change();\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.isOverNodeBox = function(node2, canvasx, canvasy) {\n var title_height = LiteGraph.NODE_TITLE_HEIGHT;\n if (isInsideRectangle(\n canvasx,\n canvasy,\n node2.pos[0] + 2,\n node2.pos[1] + 2 - title_height,\n title_height - 4,\n title_height - 4\n )) {\n return true;\n }\n return false;\n };\n LGraphCanvas.prototype.isOverNodeInput = function(node2, canvasx, canvasy, slot_pos) {\n var _a, _b;\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n var is_inside = false;\n if (node2.horizontal) {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 5,\n link_pos[1] - 10,\n 10,\n 20\n );\n } else {\n const width2 = 20 + ((((_a = input.label) == null ? void 0 : _a.length) ?? ((_b = input.name) == null ? void 0 : _b.length)) || 3) * 7;\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 10,\n link_pos[1] - 10,\n width2,\n 20\n );\n }\n if (is_inside) {\n if (slot_pos) {\n slot_pos[0] = link_pos[0];\n slot_pos[1] = link_pos[1];\n }\n return i2;\n }\n }\n }\n return -1;\n };\n LGraphCanvas.prototype.isOverNodeOutput = function(node2, canvasx, canvasy, slot_pos) {\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n var is_inside = false;\n if (node2.horizontal) {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 5,\n link_pos[1] - 10,\n 10,\n 20\n );\n } else {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 10,\n link_pos[1] - 10,\n 40,\n 20\n );\n }\n if (is_inside) {\n if (slot_pos) {\n slot_pos[0] = link_pos[0];\n slot_pos[1] = link_pos[1];\n }\n return i2;\n }\n }\n }\n return -1;\n };\n LGraphCanvas.prototype.processKey = function(e) {\n if (!this.graph) {\n return;\n }\n var block_default = false;\n if (e.target.localName == \"input\") {\n return;\n }\n if (e.type == \"keydown\") {\n if (e.keyCode == 32) {\n this.dragging_canvas = true;\n block_default = true;\n }\n if (e.keyCode == 27) {\n if (this.node_panel) this.node_panel.close();\n if (this.options_panel) this.options_panel.close();\n block_default = true;\n }\n if (e.keyCode == 65 && e.ctrlKey) {\n this.selectNodes();\n block_default = true;\n }\n if (e.keyCode === 67 && (e.metaKey || e.ctrlKey) && !e.shiftKey) {\n if (this.selected_nodes) {\n this.copyToClipboard();\n block_default = true;\n }\n }\n if (e.keyCode === 86 && (e.metaKey || e.ctrlKey)) {\n this.pasteFromClipboard(e.shiftKey);\n }\n if (e.keyCode == 46 || e.keyCode == 8) {\n if (e.target.localName != \"input\" && e.target.localName != \"textarea\") {\n this.deleteSelectedNodes();\n block_default = true;\n }\n }\n if (this.selected_nodes) {\n for (var i2 in this.selected_nodes) {\n if (this.selected_nodes[i2].onKeyDown) {\n this.selected_nodes[i2].onKeyDown(e);\n }\n }\n }\n } else if (e.type == \"keyup\") {\n if (e.keyCode == 32) {\n this.dragging_canvas = false;\n }\n if (this.selected_nodes) {\n for (var i2 in this.selected_nodes) {\n if (this.selected_nodes[i2].onKeyUp) {\n this.selected_nodes[i2].onKeyUp(e);\n }\n }\n }\n }\n this.graph.change();\n if (block_default) {\n e.preventDefault();\n e.stopImmediatePropagation();\n return false;\n }\n };\n LGraphCanvas.prototype.copyToClipboard = function(nodes) {\n var clipboard_info = {\n nodes: [],\n links: []\n };\n var index2 = 0;\n var selected_nodes_array = [];\n if (!nodes) nodes = this.selected_nodes;\n for (var i2 in nodes) {\n var node2 = nodes[i2];\n if (node2.clonable === false)\n continue;\n node2._relative_id = index2;\n selected_nodes_array.push(node2);\n index2 += 1;\n }\n for (var i2 = 0; i2 < selected_nodes_array.length; ++i2) {\n var node2 = selected_nodes_array[i2];\n var cloned = node2.clone();\n if (!cloned) {\n console.warn(\"node type not found: \" + node2.type);\n continue;\n }\n clipboard_info.nodes.push(cloned.serialize());\n if (node2.inputs && node2.inputs.length) {\n for (var j = 0; j < node2.inputs.length; ++j) {\n var input = node2.inputs[j];\n if (!input || input.link == null) {\n continue;\n }\n var link_info = this.graph.links[input.link];\n if (!link_info) {\n continue;\n }\n var target_node = this.graph.getNodeById(\n link_info.origin_id\n );\n if (!target_node) {\n continue;\n }\n clipboard_info.links.push([\n target_node._relative_id,\n link_info.origin_slot,\n //j,\n node2._relative_id,\n link_info.target_slot,\n target_node.id\n ]);\n }\n }\n }\n localStorage.setItem(\n \"litegrapheditor_clipboard\",\n JSON.stringify(clipboard_info)\n );\n };\n LGraphCanvas.prototype.pasteFromClipboard = function(isConnectUnselected = false) {\n if (!LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) {\n return;\n }\n var data = localStorage.getItem(\"litegrapheditor_clipboard\");\n if (!data) {\n return;\n }\n this.graph.beforeChange();\n var clipboard_info = JSON.parse(data);\n var posMin = false;\n var posMinIndexes = false;\n for (var i2 = 0; i2 < clipboard_info.nodes.length; ++i2) {\n if (posMin) {\n if (posMin[0] > clipboard_info.nodes[i2].pos[0]) {\n posMin[0] = clipboard_info.nodes[i2].pos[0];\n posMinIndexes[0] = i2;\n }\n if (posMin[1] > clipboard_info.nodes[i2].pos[1]) {\n posMin[1] = clipboard_info.nodes[i2].pos[1];\n posMinIndexes[1] = i2;\n }\n } else {\n posMin = [clipboard_info.nodes[i2].pos[0], clipboard_info.nodes[i2].pos[1]];\n posMinIndexes = [i2, i2];\n }\n }\n var nodes = [];\n for (var i2 = 0; i2 < clipboard_info.nodes.length; ++i2) {\n var node_data = clipboard_info.nodes[i2];\n var node2 = LiteGraph.createNode(node_data.type);\n if (node2) {\n node2.configure(node_data);\n node2.pos[0] += this.graph_mouse[0] - posMin[0];\n node2.pos[1] += this.graph_mouse[1] - posMin[1];\n this.graph.add(node2, { doProcessChange: false });\n nodes.push(node2);\n }\n }\n for (var i2 = 0; i2 < clipboard_info.links.length; ++i2) {\n var link_info = clipboard_info.links[i2];\n var origin_node = void 0;\n var origin_node_relative_id = link_info[0];\n if (origin_node_relative_id != null) {\n origin_node = nodes[origin_node_relative_id];\n } else if (LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) {\n var origin_node_id = link_info[4];\n if (origin_node_id) {\n origin_node = this.graph.getNodeById(origin_node_id);\n }\n }\n var target_node = nodes[link_info[2]];\n if (origin_node && target_node)\n origin_node.connect(link_info[1], target_node, link_info[3]);\n else\n console.warn(\"Warning, nodes missing on pasting\");\n }\n this.selectNodes(nodes);\n this.graph.afterChange();\n };\n LGraphCanvas.prototype.processDrop = function(e) {\n e.preventDefault();\n this.adjustMouseEvent(e);\n var x2 = e.clientX;\n var y2 = e.clientY;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!is_inside) {\n return;\n }\n var pos2 = [e.canvasX, e.canvasY];\n var node2 = this.graph ? this.graph.getNodeOnPos(pos2[0], pos2[1]) : null;\n if (!node2) {\n var r = null;\n if (this.onDropItem) {\n r = this.onDropItem(event);\n }\n if (!r) {\n this.checkDropItem(e);\n }\n return;\n }\n if (node2.onDropFile || node2.onDropData) {\n var files = e.dataTransfer.files;\n if (files && files.length) {\n for (var i2 = 0; i2 < files.length; i2++) {\n var file = e.dataTransfer.files[0];\n var filename = file.name;\n LGraphCanvas.getFileExtension(filename);\n if (node2.onDropFile) {\n node2.onDropFile(file);\n }\n if (node2.onDropData) {\n var reader = new FileReader();\n reader.onload = function(event2) {\n var data = event2.target.result;\n node2.onDropData(data, filename, file);\n };\n var type = file.type.split(\"/\")[0];\n if (type == \"text\" || type == \"\") {\n reader.readAsText(file);\n } else if (type == \"image\") {\n reader.readAsDataURL(file);\n } else {\n reader.readAsArrayBuffer(file);\n }\n }\n }\n }\n }\n if (node2.onDropItem) {\n if (node2.onDropItem(event)) {\n return true;\n }\n }\n if (this.onDropItem) {\n return this.onDropItem(event);\n }\n return false;\n };\n LGraphCanvas.prototype.checkDropItem = function(e) {\n if (e.dataTransfer.files.length) {\n var file = e.dataTransfer.files[0];\n var ext = LGraphCanvas.getFileExtension(file.name).toLowerCase();\n var nodetype = LiteGraph.node_types_by_file_extension[ext];\n if (nodetype) {\n this.graph.beforeChange();\n var node2 = LiteGraph.createNode(nodetype.type);\n node2.pos = [e.canvasX, e.canvasY];\n this.graph.add(node2);\n if (node2.onDropFile) {\n node2.onDropFile(file);\n }\n this.graph.afterChange();\n }\n }\n };\n LGraphCanvas.prototype.processNodeDblClicked = function(n) {\n if (this.onShowNodePanel) {\n this.onShowNodePanel(n);\n }\n if (this.onNodeDblClicked) {\n this.onNodeDblClicked(n);\n }\n this.setDirty(true);\n };\n LGraphCanvas.prototype.processNodeSelected = function(node2, e) {\n this.selectNode(node2, e && (e.shiftKey || e.ctrlKey || this.multi_select));\n if (this.onNodeSelected) {\n this.onNodeSelected(node2);\n }\n };\n LGraphCanvas.prototype.selectNode = function(node2, add_to_current_selection) {\n if (node2 == null) {\n this.deselectAllNodes();\n } else {\n this.selectNodes([node2], add_to_current_selection);\n }\n };\n LGraphCanvas.prototype.selectNodes = function(nodes, add_to_current_selection) {\n if (!add_to_current_selection) {\n this.deselectAllNodes();\n }\n nodes = nodes || this.graph._nodes;\n if (typeof nodes == \"string\") nodes = [nodes];\n for (var i2 in nodes) {\n var node2 = nodes[i2];\n if (node2.is_selected) {\n this.deselectNode(node2);\n continue;\n }\n if (!node2.is_selected && node2.onSelected) {\n node2.onSelected();\n }\n node2.is_selected = true;\n this.selected_nodes[node2.id] = node2;\n if (node2.inputs) {\n for (var j = 0; j < node2.inputs.length; ++j) {\n this.highlighted_links[node2.inputs[j].link] = true;\n }\n }\n if (node2.outputs) {\n for (var j = 0; j < node2.outputs.length; ++j) {\n var out = node2.outputs[j];\n if (out.links) {\n for (var k = 0; k < out.links.length; ++k) {\n this.highlighted_links[out.links[k]] = true;\n }\n }\n }\n }\n }\n if (this.onSelectionChange)\n this.onSelectionChange(this.selected_nodes);\n this.setDirty(true);\n };\n LGraphCanvas.prototype.deselectNode = function(node2) {\n if (!node2.is_selected) {\n return;\n }\n if (node2.onDeselected) {\n node2.onDeselected();\n }\n node2.is_selected = false;\n delete this.selected_nodes[node2.id];\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n delete this.highlighted_links[node2.inputs[i2].link];\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; ++i2) {\n var out = node2.outputs[i2];\n if (out.links) {\n for (var j = 0; j < out.links.length; ++j) {\n delete this.highlighted_links[out.links[j]];\n }\n }\n }\n }\n };\n LGraphCanvas.prototype.deselectAllNodes = function() {\n if (!this.graph) {\n return;\n }\n var nodes = this.graph._nodes;\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var node2 = nodes[i2];\n if (!node2.is_selected) {\n continue;\n }\n if (node2.onDeselected) {\n node2.onDeselected();\n }\n node2.is_selected = false;\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n }\n this.selected_nodes = {};\n this.current_node = null;\n this.highlighted_links = {};\n if (this.onSelectionChange)\n this.onSelectionChange(this.selected_nodes);\n this.setDirty(true);\n };\n LGraphCanvas.prototype.deleteSelectedNodes = function() {\n this.graph.beforeChange();\n for (var i2 in this.selected_nodes) {\n var node2 = this.selected_nodes[i2];\n if (node2.block_delete)\n continue;\n if (node2.inputs && node2.inputs.length && node2.outputs && node2.outputs.length && LiteGraph.isValidConnection(node2.inputs[0].type, node2.outputs[0].type) && node2.inputs[0].link && node2.outputs[0].links && node2.outputs[0].links.length) {\n var input_link = node2.graph.links[node2.inputs[0].link];\n var output_link = node2.graph.links[node2.outputs[0].links[0]];\n var input_node = node2.getInputNode(0);\n var output_node = node2.getOutputNodes(0)[0];\n if (input_node && output_node)\n input_node.connect(input_link.origin_slot, output_node, output_link.target_slot);\n }\n this.graph.remove(node2);\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n }\n this.selected_nodes = {};\n this.current_node = null;\n this.highlighted_links = {};\n this.setDirty(true);\n this.graph.afterChange();\n };\n LGraphCanvas.prototype.centerOnNode = function(node2) {\n const dpi = (window == null ? void 0 : window.devicePixelRatio) || 1;\n this.ds.offset[0] = -node2.pos[0] - node2.size[0] * 0.5 + this.canvas.width * 0.5 / (this.ds.scale * dpi);\n this.ds.offset[1] = -node2.pos[1] - node2.size[1] * 0.5 + this.canvas.height * 0.5 / (this.ds.scale * dpi);\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.adjustMouseEvent = function(e) {\n var clientX_rel = 0;\n var clientY_rel = 0;\n if (this.canvas) {\n var b = this.canvas.getBoundingClientRect();\n clientX_rel = e.clientX - b.left;\n clientY_rel = e.clientY - b.top;\n } else {\n clientX_rel = e.clientX;\n clientY_rel = e.clientY;\n }\n if (e.deltaX === void 0)\n e.deltaX = clientX_rel - this.last_mouse_position[0];\n if (e.deltaY === void 0)\n e.deltaY = clientY_rel - this.last_mouse_position[1];\n this.last_mouse_position[0] = clientX_rel;\n this.last_mouse_position[1] = clientY_rel;\n e.canvasX = clientX_rel / this.ds.scale - this.ds.offset[0];\n e.canvasY = clientY_rel / this.ds.scale - this.ds.offset[1];\n };\n LGraphCanvas.prototype.setZoom = function(value, zooming_center) {\n this.ds.changeScale(value, zooming_center);\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n };\n LGraphCanvas.prototype.convertOffsetToCanvas = function(pos2, out) {\n return this.ds.convertOffsetToCanvas(pos2, out);\n };\n LGraphCanvas.prototype.convertCanvasToOffset = function(pos2, out) {\n return this.ds.convertCanvasToOffset(pos2, out);\n };\n LGraphCanvas.prototype.convertEventToCanvasOffset = function(e) {\n var rect = this.canvas.getBoundingClientRect();\n return this.convertCanvasToOffset([\n e.clientX - rect.left,\n e.clientY - rect.top\n ]);\n };\n LGraphCanvas.prototype.bringToFront = function(node2) {\n var i2 = this.graph._nodes.indexOf(node2);\n if (i2 == -1) {\n return;\n }\n this.graph._nodes.splice(i2, 1);\n this.graph._nodes.push(node2);\n };\n LGraphCanvas.prototype.sendToBack = function(node2) {\n var i2 = this.graph._nodes.indexOf(node2);\n if (i2 == -1) {\n return;\n }\n this.graph._nodes.splice(i2, 1);\n this.graph._nodes.unshift(node2);\n };\n var temp = new Float32Array(4);\n LGraphCanvas.prototype.computeVisibleNodes = function(nodes, out) {\n var visible_nodes = out || [];\n visible_nodes.length = 0;\n nodes = nodes || this.graph._nodes;\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n = nodes[i2];\n if (this.live_mode && !n.onDrawBackground && !n.onDrawForeground) {\n continue;\n }\n if (!overlapBounding(this.visible_area, n.getBounding(temp, true))) {\n continue;\n }\n visible_nodes.push(n);\n }\n return visible_nodes;\n };\n LGraphCanvas.prototype.draw = function(force_canvas, force_bgcanvas) {\n if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0) {\n return;\n }\n var now = LiteGraph.getTime();\n this.render_time = (now - this.last_draw_time) * 1e-3;\n this.last_draw_time = now;\n if (this.graph) {\n this.ds.computeVisibleArea(this.viewport);\n }\n if (this.dirty_bgcanvas || force_bgcanvas || this.always_render_background || this.graph && this.graph._last_trigger_time && now - this.graph._last_trigger_time < 1e3) {\n this.drawBackCanvas();\n }\n if (this.dirty_canvas || force_canvas) {\n this.drawFrontCanvas();\n }\n this.fps = this.render_time ? 1 / this.render_time : 0;\n this.frame += 1;\n };\n LGraphCanvas.prototype.drawFrontCanvas = function() {\n this.dirty_canvas = false;\n if (!this.ctx) {\n this.ctx = this.bgcanvas.getContext(\"2d\");\n }\n var ctx = this.ctx;\n if (!ctx) {\n return;\n }\n var canvas = this.canvas;\n if (ctx.start2D && !this.viewport) {\n ctx.start2D();\n ctx.restore();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n }\n var area = this.viewport || this.dirty_area;\n if (area) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area[0], area[1], area[2], area[3]);\n ctx.clip();\n }\n if (this.clear_background) {\n if (area)\n ctx.clearRect(area[0], area[1], area[2], area[3]);\n else\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }\n if (this.bgcanvas == this.canvas) {\n this.drawBackCanvas();\n } else {\n ctx.drawImage(this.bgcanvas, 0, 0);\n }\n if (this.onRender) {\n this.onRender(canvas, ctx);\n }\n if (this.show_info) {\n this.renderInfo(ctx, area ? area[0] : 0, area ? area[1] : 0);\n }\n if (this.graph) {\n ctx.save();\n this.ds.toCanvasContext(ctx);\n var visible_nodes = this.computeVisibleNodes(\n null,\n this.visible_nodes\n );\n for (var i2 = 0; i2 < visible_nodes.length; ++i2) {\n var node2 = visible_nodes[i2];\n ctx.save();\n ctx.translate(node2.pos[0], node2.pos[1]);\n this.drawNode(node2, ctx);\n ctx.restore();\n }\n if (this.render_execution_order) {\n this.drawExecutionOrder(ctx);\n }\n if (this.graph.config.links_ontop) {\n if (!this.live_mode) {\n this.drawConnections(ctx);\n }\n }\n if (this.connecting_links) {\n for (const link of this.connecting_links) {\n ctx.lineWidth = this.connections_width;\n var link_color = null;\n var connInOrOut = link.output || link.input;\n var connType = connInOrOut.type;\n var connDir = connInOrOut.dir;\n if (connDir == null) {\n if (link.output)\n connDir = link.node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT;\n else\n connDir = link.node.horizontal ? LiteGraph.UP : LiteGraph.LEFT;\n }\n var connShape = connInOrOut.shape;\n switch (connType) {\n case LiteGraph.EVENT:\n link_color = LiteGraph.EVENT_LINK_COLOR;\n break;\n default:\n link_color = LiteGraph.CONNECTING_LINK_COLOR;\n }\n this.renderLink(\n ctx,\n link.pos,\n [this.graph_mouse[0], this.graph_mouse[1]],\n null,\n false,\n null,\n link_color,\n connDir,\n LiteGraph.CENTER\n );\n ctx.beginPath();\n if (connType === LiteGraph.EVENT || connShape === LiteGraph.BOX_SHAPE) {\n ctx.rect(\n link.pos[0] - 6 + 0.5,\n link.pos[1] - 5 + 0.5,\n 14,\n 10\n );\n ctx.fill();\n ctx.beginPath();\n ctx.rect(\n this.graph_mouse[0] - 6 + 0.5,\n this.graph_mouse[1] - 5 + 0.5,\n 14,\n 10\n );\n } else if (connShape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(link.pos[0] + 8, link.pos[1] + 0.5);\n ctx.lineTo(link.pos[0] - 4, link.pos[1] + 6 + 0.5);\n ctx.lineTo(link.pos[0] - 4, link.pos[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n link.pos[0],\n link.pos[1],\n 4,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n ctx.beginPath();\n ctx.arc(\n this.graph_mouse[0],\n this.graph_mouse[1],\n 4,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n ctx.fillStyle = \"#ffcc00\";\n if (this._highlight_input) {\n ctx.beginPath();\n var shape = this._highlight_input_slot.shape;\n if (shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(this._highlight_input[0] + 8, this._highlight_input[1] + 0.5);\n ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] + 6 + 0.5);\n ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n this._highlight_input[0],\n this._highlight_input[1],\n 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n }\n if (this._highlight_output) {\n ctx.beginPath();\n if (shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(this._highlight_output[0] + 8, this._highlight_output[1] + 0.5);\n ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] + 6 + 0.5);\n ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n this._highlight_output[0],\n this._highlight_output[1],\n 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n }\n }\n }\n if (this.dragging_rectangle) {\n ctx.strokeStyle = \"#FFF\";\n ctx.strokeRect(\n this.dragging_rectangle[0],\n this.dragging_rectangle[1],\n this.dragging_rectangle[2],\n this.dragging_rectangle[3]\n );\n }\n if (this.over_link_center && this.render_link_tooltip)\n this.drawLinkTooltip(ctx, this.over_link_center);\n else if (this.onDrawLinkTooltip)\n this.onDrawLinkTooltip(ctx, null);\n if (this.onDrawForeground) {\n this.onDrawForeground(ctx, this.visible_rect);\n }\n ctx.restore();\n }\n if (this._graph_stack && this._graph_stack.length) {\n this.drawSubgraphPanel(ctx);\n }\n if (this.onDrawOverlay) {\n this.onDrawOverlay(ctx);\n }\n if (area) {\n ctx.restore();\n }\n if (ctx.finish2D) {\n ctx.finish2D();\n }\n };\n LGraphCanvas.prototype.drawSubgraphPanel = function(ctx) {\n var subgraph = this.graph;\n var subnode = subgraph._subgraph_node;\n if (!subnode) {\n console.warn(\"subgraph without subnode\");\n return;\n }\n this.drawSubgraphPanelLeft(subgraph, subnode, ctx);\n this.drawSubgraphPanelRight(subgraph, subnode, ctx);\n };\n LGraphCanvas.prototype.drawSubgraphPanelLeft = function(subgraph, subnode, ctx) {\n var num = subnode.inputs ? subnode.inputs.length : 0;\n var w2 = 200;\n var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6);\n ctx.fillStyle = \"#111\";\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n ctx.roundRect(10, 10, w2, (num + 1) * h + 50, [8]);\n ctx.fill();\n ctx.globalAlpha = 1;\n ctx.fillStyle = \"#888\";\n ctx.font = \"14px Arial\";\n ctx.textAlign = \"left\";\n ctx.fillText(\"Graph Inputs\", 20, 34);\n if (this.drawButton(w2 - 20, 20, 20, 20, \"X\", \"#151515\")) {\n this.closeSubgraph();\n return;\n }\n var y2 = 50;\n ctx.font = \"14px Arial\";\n if (subnode.inputs)\n for (var i2 = 0; i2 < subnode.inputs.length; ++i2) {\n var input = subnode.inputs[i2];\n if (input.not_subgraph_input)\n continue;\n if (this.drawButton(20, y2 + 2, w2 - 20, h - 2)) {\n var type = subnode.constructor.input_node_type || \"graph/input\";\n this.graph.beforeChange();\n var newnode = LiteGraph.createNode(type);\n if (newnode) {\n subgraph.add(newnode);\n this.block_click = false;\n this.last_click_position = null;\n this.selectNodes([newnode]);\n this.node_dragged = newnode;\n this.dragging_canvas = false;\n newnode.setProperty(\"name\", input.name);\n newnode.setProperty(\"type\", input.type);\n this.node_dragged.pos[0] = this.graph_mouse[0] - 5;\n this.node_dragged.pos[1] = this.graph_mouse[1] - 5;\n this.graph.afterChange();\n } else\n console.error(\"graph input node not found:\", type);\n }\n ctx.fillStyle = \"#9C9\";\n ctx.beginPath();\n ctx.arc(w2 - 16, y2 + h * 0.5, 5, 0, 2 * Math.PI);\n ctx.fill();\n ctx.fillStyle = \"#AAA\";\n ctx.fillText(input.name, 30, y2 + h * 0.75);\n ctx.fillStyle = \"#777\";\n ctx.fillText(input.type, 130, y2 + h * 0.75);\n y2 += h;\n }\n if (this.drawButton(20, y2 + 2, w2 - 20, h - 2, \"+\", \"#151515\", \"#222\")) {\n this.showSubgraphPropertiesDialog(subnode);\n }\n };\n LGraphCanvas.prototype.drawSubgraphPanelRight = function(subgraph, subnode, ctx) {\n var num = subnode.outputs ? subnode.outputs.length : 0;\n var canvas_w = this.bgcanvas.width;\n var w2 = 200;\n var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6);\n ctx.fillStyle = \"#111\";\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n ctx.roundRect(canvas_w - w2 - 10, 10, w2, (num + 1) * h + 50, [8]);\n ctx.fill();\n ctx.globalAlpha = 1;\n ctx.fillStyle = \"#888\";\n ctx.font = \"14px Arial\";\n ctx.textAlign = \"left\";\n var title_text = \"Graph Outputs\";\n var tw = ctx.measureText(title_text).width;\n ctx.fillText(title_text, canvas_w - tw - 20, 34);\n if (this.drawButton(canvas_w - w2, 20, 20, 20, \"X\", \"#151515\")) {\n this.closeSubgraph();\n return;\n }\n var y2 = 50;\n ctx.font = \"14px Arial\";\n if (subnode.outputs)\n for (var i2 = 0; i2 < subnode.outputs.length; ++i2) {\n var output = subnode.outputs[i2];\n if (output.not_subgraph_input)\n continue;\n if (this.drawButton(canvas_w - w2, y2 + 2, w2 - 20, h - 2)) {\n var type = subnode.constructor.output_node_type || \"graph/output\";\n this.graph.beforeChange();\n var newnode = LiteGraph.createNode(type);\n if (newnode) {\n subgraph.add(newnode);\n this.block_click = false;\n this.last_click_position = null;\n this.selectNodes([newnode]);\n this.node_dragged = newnode;\n this.dragging_canvas = false;\n newnode.setProperty(\"name\", output.name);\n newnode.setProperty(\"type\", output.type);\n this.node_dragged.pos[0] = this.graph_mouse[0] - 5;\n this.node_dragged.pos[1] = this.graph_mouse[1] - 5;\n this.graph.afterChange();\n } else\n console.error(\"graph input node not found:\", type);\n }\n ctx.fillStyle = \"#9C9\";\n ctx.beginPath();\n ctx.arc(canvas_w - w2 + 16, y2 + h * 0.5, 5, 0, 2 * Math.PI);\n ctx.fill();\n ctx.fillStyle = \"#AAA\";\n ctx.fillText(output.name, canvas_w - w2 + 30, y2 + h * 0.75);\n ctx.fillStyle = \"#777\";\n ctx.fillText(output.type, canvas_w - w2 + 130, y2 + h * 0.75);\n y2 += h;\n }\n if (this.drawButton(canvas_w - w2, y2 + 2, w2 - 20, h - 2, \"+\", \"#151515\", \"#222\")) {\n this.showSubgraphPropertiesDialogRight(subnode);\n }\n };\n LGraphCanvas.prototype.drawButton = function(x2, y2, w2, h, text, bgcolor, hovercolor, textcolor) {\n var ctx = this.ctx;\n bgcolor = bgcolor || LiteGraph.NODE_DEFAULT_COLOR;\n hovercolor = hovercolor || \"#555\";\n textcolor = textcolor || LiteGraph.NODE_TEXT_COLOR;\n var pos2 = this.ds.convertOffsetToCanvas(this.graph_mouse);\n var hover = LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n pos2 = this.last_click_position ? [this.last_click_position[0], this.last_click_position[1]] : null;\n if (pos2) {\n var rect = this.canvas.getBoundingClientRect();\n pos2[0] -= rect.left;\n pos2[1] -= rect.top;\n }\n var clicked = pos2 && LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n ctx.fillStyle = hover ? hovercolor : bgcolor;\n if (clicked)\n ctx.fillStyle = \"#AAA\";\n ctx.beginPath();\n ctx.roundRect(x2, y2, w2, h, [4]);\n ctx.fill();\n if (text != null) {\n if (text.constructor == String) {\n ctx.fillStyle = textcolor;\n ctx.textAlign = \"center\";\n ctx.font = (h * 0.65 | 0) + \"px Arial\";\n ctx.fillText(text, x2 + w2 * 0.5, y2 + h * 0.75);\n ctx.textAlign = \"left\";\n }\n }\n var was_clicked = clicked && !this.block_click;\n if (clicked)\n this.blockClick();\n return was_clicked;\n };\n LGraphCanvas.prototype.isAreaClicked = function(x2, y2, w2, h, hold_click) {\n var pos2 = this.mouse;\n LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n pos2 = this.last_click_position;\n var clicked = pos2 && LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n var was_clicked = clicked && !this.block_click;\n if (clicked && hold_click)\n this.blockClick();\n return was_clicked;\n };\n LGraphCanvas.prototype.renderInfo = function(ctx, x2, y2) {\n x2 = x2 || 10;\n y2 = y2 || this.canvas.offsetHeight - 80;\n ctx.save();\n ctx.translate(x2, y2);\n ctx.font = \"10px Arial\";\n ctx.fillStyle = \"#888\";\n ctx.textAlign = \"left\";\n if (this.graph) {\n ctx.fillText(\"T: \" + this.graph.globaltime.toFixed(2) + \"s\", 5, 13 * 1);\n ctx.fillText(\"I: \" + this.graph.iteration, 5, 13 * 2);\n ctx.fillText(\"N: \" + this.graph._nodes.length + \" [\" + this.visible_nodes.length + \"]\", 5, 13 * 3);\n ctx.fillText(\"V: \" + this.graph._version, 5, 13 * 4);\n ctx.fillText(\"FPS:\" + this.fps.toFixed(2), 5, 13 * 5);\n } else {\n ctx.fillText(\"No graph selected\", 5, 13 * 1);\n }\n ctx.restore();\n };\n LGraphCanvas.prototype.drawBackCanvas = function() {\n var canvas = this.bgcanvas;\n if (canvas.width != this.canvas.width || canvas.height != this.canvas.height) {\n canvas.width = this.canvas.width;\n canvas.height = this.canvas.height;\n }\n if (!this.bgctx) {\n this.bgctx = this.bgcanvas.getContext(\"2d\");\n }\n var ctx = this.bgctx;\n if (ctx.start) {\n ctx.start();\n }\n var viewport = this.viewport || [0, 0, ctx.canvas.width, ctx.canvas.height];\n if (this.clear_background) {\n ctx.clearRect(viewport[0], viewport[1], viewport[2], viewport[3]);\n }\n if (this._graph_stack && this._graph_stack.length) {\n ctx.save();\n this._graph_stack[this._graph_stack.length - 1];\n var subgraph_node = this.graph._subgraph_node;\n ctx.strokeStyle = subgraph_node.bgcolor;\n ctx.lineWidth = 10;\n ctx.strokeRect(1, 1, canvas.width - 2, canvas.height - 2);\n ctx.lineWidth = 1;\n ctx.font = \"40px Arial\";\n ctx.textAlign = \"center\";\n ctx.fillStyle = subgraph_node.bgcolor || \"#AAA\";\n var title = \"\";\n for (var i2 = 1; i2 < this._graph_stack.length; ++i2) {\n title += this._graph_stack[i2]._subgraph_node.getTitle() + \" >> \";\n }\n ctx.fillText(\n title + subgraph_node.getTitle(),\n canvas.width * 0.5,\n 40\n );\n ctx.restore();\n }\n var bg_already_painted = false;\n if (this.onRenderBackground) {\n bg_already_painted = this.onRenderBackground(canvas, ctx);\n }\n if (!this.viewport) {\n ctx.restore();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n }\n this.visible_links.length = 0;\n if (this.graph) {\n ctx.save();\n this.ds.toCanvasContext(ctx);\n if (this.ds.scale < 1.5 && !bg_already_painted && this.clear_background_color) {\n ctx.fillStyle = this.clear_background_color;\n ctx.fillRect(\n this.visible_area[0],\n this.visible_area[1],\n this.visible_area[2],\n this.visible_area[3]\n );\n }\n if (this.background_image && this.ds.scale > 0.5 && !bg_already_painted) {\n if (this.zoom_modify_alpha) {\n ctx.globalAlpha = (1 - 0.5 / this.ds.scale) * this.editor_alpha;\n } else {\n ctx.globalAlpha = this.editor_alpha;\n }\n ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = false;\n if (!this._bg_img || this._bg_img.name != this.background_image) {\n this._bg_img = new Image();\n this._bg_img.name = this.background_image;\n this._bg_img.src = this.background_image;\n var that2 = this;\n this._bg_img.onload = function() {\n that2.draw(true, true);\n };\n }\n var pattern = null;\n if (this._pattern == null && this._bg_img.width > 0) {\n pattern = ctx.createPattern(this._bg_img, \"repeat\");\n this._pattern_img = this._bg_img;\n this._pattern = pattern;\n } else {\n pattern = this._pattern;\n }\n if (pattern) {\n ctx.fillStyle = pattern;\n ctx.fillRect(\n this.visible_area[0],\n this.visible_area[1],\n this.visible_area[2],\n this.visible_area[3]\n );\n ctx.fillStyle = \"transparent\";\n }\n ctx.globalAlpha = 1;\n ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = true;\n }\n if (this.graph._groups.length && !this.live_mode) {\n this.drawGroups(canvas, ctx);\n }\n if (this.onDrawBackground) {\n this.onDrawBackground(ctx, this.visible_area);\n }\n if (this.onBackgroundRender) {\n console.error(\n \"WARNING! onBackgroundRender deprecated, now is named onDrawBackground \"\n );\n this.onBackgroundRender = null;\n }\n if (this.render_canvas_border) {\n ctx.strokeStyle = \"#235\";\n ctx.strokeRect(0, 0, canvas.width, canvas.height);\n }\n if (this.render_connections_shadows) {\n ctx.shadowColor = \"#000\";\n ctx.shadowOffsetX = 0;\n ctx.shadowOffsetY = 0;\n ctx.shadowBlur = 6;\n } else {\n ctx.shadowColor = \"rgba(0,0,0,0)\";\n }\n if (!this.live_mode) {\n this.drawConnections(ctx);\n }\n ctx.shadowColor = \"rgba(0,0,0,0)\";\n ctx.restore();\n }\n if (ctx.finish) {\n ctx.finish();\n }\n this.dirty_bgcanvas = false;\n this.dirty_canvas = true;\n };\n var temp_vec2 = new Float32Array(2);\n LGraphCanvas.prototype.drawNode = function(node2, ctx) {\n this.current_node = node2;\n var color = node2.color || node2.constructor.color || LiteGraph.NODE_DEFAULT_COLOR;\n var bgcolor = node2.bgcolor || node2.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR;\n if (node2.mouseOver) ;\n var low_quality = this.ds.scale < 0.6;\n if (this.live_mode) {\n if (!node2.flags.collapsed) {\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawForeground) {\n node2.onDrawForeground(ctx, this, this.canvas);\n }\n }\n return;\n }\n var editor_alpha = this.editor_alpha;\n ctx.globalAlpha = editor_alpha;\n if (this.render_shadows && !low_quality) {\n ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;\n ctx.shadowOffsetX = 2 * this.ds.scale;\n ctx.shadowOffsetY = 2 * this.ds.scale;\n ctx.shadowBlur = 3 * this.ds.scale;\n } else {\n ctx.shadowColor = \"transparent\";\n }\n if (node2.flags.collapsed && node2.onDrawCollapsed && node2.onDrawCollapsed(ctx, this) == true) {\n return;\n }\n var shape = node2._shape || LiteGraph.BOX_SHAPE;\n var size = temp_vec2;\n temp_vec2.set(node2.size);\n var horizontal = node2.horizontal;\n if (node2.flags.collapsed) {\n ctx.font = this.inner_text_font;\n var title = node2.getTitle ? node2.getTitle() : node2.title;\n if (title != null) {\n node2._collapsed_width = Math.min(\n node2.size[0],\n ctx.measureText(title).width + LiteGraph.NODE_TITLE_HEIGHT * 2\n );\n size[0] = node2._collapsed_width;\n size[1] = 0;\n }\n }\n if (node2.clip_area) {\n ctx.save();\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE) {\n ctx.rect(0, 0, size[0], size[1]);\n } else if (shape == LiteGraph.ROUND_SHAPE) {\n ctx.roundRect(0, 0, size[0], size[1], [10]);\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5,\n 0,\n Math.PI * 2\n );\n }\n ctx.clip();\n }\n if (node2.has_errors) {\n bgcolor = \"red\";\n }\n this.drawNodeShape(\n node2,\n ctx,\n size,\n color,\n bgcolor,\n node2.is_selected,\n node2.mouseOver\n );\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawForeground) {\n node2.onDrawForeground(ctx, this, this.canvas);\n }\n ctx.textAlign = horizontal ? \"center\" : \"left\";\n ctx.font = this.inner_text_font;\n var render_text = !low_quality;\n var out_slot = this.connecting_links ? this.connecting_links[0].output : null;\n var in_slot = this.connecting_links ? this.connecting_links[0].input : null;\n ctx.lineWidth = 1;\n var max_y = 0;\n var slot_pos = new Float32Array(2);\n if (!node2.flags.collapsed) {\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n var slot_type = slot.type;\n var slot_shape = slot.shape;\n ctx.globalAlpha = editor_alpha;\n if (out_slot && !LiteGraph.isValidConnection(slot.type, out_slot.type)) {\n ctx.globalAlpha = 0.4 * editor_alpha;\n }\n ctx.fillStyle = slot.link != null ? slot.color_on || this.default_connection_color_byType[slot_type] || this.default_connection_color.input_on : slot.color_off || this.default_connection_color_byTypeOff[slot_type] || this.default_connection_color_byType[slot_type] || this.default_connection_color.input_off;\n var pos2 = node2.getConnectionPos(true, i2, slot_pos);\n pos2[0] -= node2.pos[0];\n pos2[1] -= node2.pos[1];\n if (max_y < pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) {\n max_y = pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n }\n ctx.beginPath();\n if (slot_type == \"array\") {\n slot_shape = LiteGraph.GRID_SHAPE;\n }\n var doStroke = true;\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n if (horizontal) {\n ctx.rect(\n pos2[0] - 5 + 0.5,\n pos2[1] - 8 + 0.5,\n 10,\n 14\n );\n } else {\n ctx.rect(\n pos2[0] - 6 + 0.5,\n pos2[1] - 5 + 0.5,\n 14,\n 10\n );\n }\n } else if (slot_shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(pos2[0] + 8, pos2[1] + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] + 6 + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] - 6 + 0.5);\n ctx.closePath();\n } else if (slot_shape === LiteGraph.GRID_SHAPE) {\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] + 2, 2, 2);\n doStroke = false;\n } else {\n if (low_quality)\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 8, 8);\n else\n ctx.arc(pos2[0], pos2[1], 4, 0, Math.PI * 2);\n }\n ctx.fill();\n if (render_text) {\n var text = slot.label != null ? slot.label : slot.name;\n if (text) {\n ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR;\n if (horizontal || slot.dir == LiteGraph.UP) {\n ctx.fillText(text, pos2[0], pos2[1] - 10);\n } else {\n ctx.fillText(text, pos2[0] + 10, pos2[1] + 5);\n }\n }\n }\n }\n }\n ctx.textAlign = horizontal ? \"center\" : \"right\";\n ctx.strokeStyle = \"black\";\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n var slot_type = slot.type;\n var slot_shape = slot.shape;\n if (in_slot && !LiteGraph.isValidConnection(slot_type, in_slot.type)) {\n ctx.globalAlpha = 0.4 * editor_alpha;\n }\n var pos2 = node2.getConnectionPos(false, i2, slot_pos);\n pos2[0] -= node2.pos[0];\n pos2[1] -= node2.pos[1];\n if (max_y < pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) {\n max_y = pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n }\n ctx.fillStyle = slot.links && slot.links.length ? slot.color_on || this.default_connection_color_byType[slot_type] || this.default_connection_color.output_on : slot.color_off || this.default_connection_color_byTypeOff[slot_type] || this.default_connection_color_byType[slot_type] || this.default_connection_color.output_off;\n ctx.beginPath();\n if (slot_type == \"array\") {\n slot_shape = LiteGraph.GRID_SHAPE;\n }\n var doStroke = true;\n if (slot_type === LiteGraph.EVENT || slot_shape === LiteGraph.BOX_SHAPE) {\n if (horizontal) {\n ctx.rect(\n pos2[0] - 5 + 0.5,\n pos2[1] - 8 + 0.5,\n 10,\n 14\n );\n } else {\n ctx.rect(\n pos2[0] - 6 + 0.5,\n pos2[1] - 5 + 0.5,\n 14,\n 10\n );\n }\n } else if (slot_shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(pos2[0] + 8, pos2[1] + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] + 6 + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] - 6 + 0.5);\n ctx.closePath();\n } else if (slot_shape === LiteGraph.GRID_SHAPE) {\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] + 2, 2, 2);\n doStroke = false;\n } else {\n if (low_quality)\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 8, 8);\n else\n ctx.arc(pos2[0], pos2[1], 4, 0, Math.PI * 2);\n }\n ctx.fill();\n if (!low_quality && doStroke)\n ctx.stroke();\n if (render_text) {\n var text = slot.label != null ? slot.label : slot.name;\n if (text) {\n ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR;\n if (horizontal || slot.dir == LiteGraph.DOWN) {\n ctx.fillText(text, pos2[0], pos2[1] - 8);\n } else {\n ctx.fillText(text, pos2[0] - 10, pos2[1] + 5);\n }\n }\n }\n }\n }\n ctx.textAlign = \"left\";\n ctx.globalAlpha = 1;\n if (node2.widgets) {\n var widgets_y = max_y;\n if (horizontal || node2.widgets_up) {\n widgets_y = 2;\n }\n if (node2.widgets_start_y != null)\n widgets_y = node2.widgets_start_y;\n this.drawNodeWidgets(\n node2,\n widgets_y,\n ctx,\n this.node_widget && this.node_widget[0] == node2 ? this.node_widget[1] : null\n );\n }\n } else if (this.render_collapsed_slots) {\n var input_slot = null;\n var output_slot = null;\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n if (slot.link == null) {\n continue;\n }\n input_slot = slot;\n break;\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n if (!slot.links || !slot.links.length) {\n continue;\n }\n output_slot = slot;\n }\n }\n if (input_slot) {\n var x2 = 0;\n var y2 = LiteGraph.NODE_TITLE_HEIGHT * -0.5;\n if (horizontal) {\n x2 = node2._collapsed_width * 0.5;\n y2 = -LiteGraph.NODE_TITLE_HEIGHT;\n }\n ctx.fillStyle = \"#686\";\n ctx.beginPath();\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n ctx.rect(x2 - 7 + 0.5, y2 - 4, 14, 8);\n } else if (slot.shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(x2 + 8, y2);\n ctx.lineTo(x2 + -4, y2 - 4);\n ctx.lineTo(x2 + -4, y2 + 4);\n ctx.closePath();\n } else {\n ctx.arc(x2, y2, 4, 0, Math.PI * 2);\n }\n ctx.fill();\n }\n if (output_slot) {\n var x2 = node2._collapsed_width;\n var y2 = LiteGraph.NODE_TITLE_HEIGHT * -0.5;\n if (horizontal) {\n x2 = node2._collapsed_width * 0.5;\n y2 = 0;\n }\n ctx.fillStyle = \"#686\";\n ctx.strokeStyle = \"black\";\n ctx.beginPath();\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n ctx.rect(x2 - 7 + 0.5, y2 - 4, 14, 8);\n } else if (slot.shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(x2 + 6, y2);\n ctx.lineTo(x2 - 6, y2 - 4);\n ctx.lineTo(x2 - 6, y2 + 4);\n ctx.closePath();\n } else {\n ctx.arc(x2, y2, 4, 0, Math.PI * 2);\n }\n ctx.fill();\n }\n }\n if (node2.clip_area) {\n ctx.restore();\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.drawLinkTooltip = function(ctx, link) {\n var pos2 = link._pos;\n ctx.fillStyle = \"black\";\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 3, 0, Math.PI * 2);\n ctx.fill();\n if (link.data == null)\n return;\n if (this.onDrawLinkTooltip) {\n if (this.onDrawLinkTooltip(ctx, link, this) == true)\n return;\n }\n var data = link.data;\n var text = null;\n if (data.constructor === Number)\n text = data.toFixed(2);\n else if (data.constructor === String)\n text = '\"' + data + '\"';\n else if (data.constructor === Boolean)\n text = String(data);\n else if (data.toToolTip)\n text = data.toToolTip();\n else\n text = \"[\" + data.constructor.name + \"]\";\n if (text == null)\n return;\n text = text.substr(0, 30);\n ctx.font = \"14px Courier New\";\n var info = ctx.measureText(text);\n var w2 = info.width + 20;\n var h = 24;\n ctx.shadowColor = \"black\";\n ctx.shadowOffsetX = 2;\n ctx.shadowOffsetY = 2;\n ctx.shadowBlur = 3;\n ctx.fillStyle = \"#454\";\n ctx.beginPath();\n ctx.roundRect(pos2[0] - w2 * 0.5, pos2[1] - 15 - h, w2, h, [3]);\n ctx.moveTo(pos2[0] - 10, pos2[1] - 15);\n ctx.lineTo(pos2[0] + 10, pos2[1] - 15);\n ctx.lineTo(pos2[0], pos2[1] - 5);\n ctx.fill();\n ctx.shadowColor = \"transparent\";\n ctx.textAlign = \"center\";\n ctx.fillStyle = \"#CEC\";\n ctx.fillText(text, pos2[0], pos2[1] - 15 - h * 0.3);\n };\n var tmp_area = new Float32Array(4);\n LGraphCanvas.prototype.drawNodeShape = function(node2, ctx, size, fgcolor, bgcolor, selected, mouse_over) {\n ctx.strokeStyle = fgcolor;\n ctx.fillStyle = bgcolor;\n var title_height = LiteGraph.NODE_TITLE_HEIGHT;\n var low_quality = this.ds.scale < 0.5;\n var shape = node2._shape || node2.constructor.shape || LiteGraph.ROUND_SHAPE;\n var title_mode = node2.constructor.title_mode;\n var render_title = true;\n if (title_mode == LiteGraph.TRANSPARENT_TITLE || title_mode == LiteGraph.NO_TITLE) {\n render_title = false;\n } else if (title_mode == LiteGraph.AUTOHIDE_TITLE && mouse_over) {\n render_title = true;\n }\n var area = tmp_area;\n area[0] = 0;\n area[1] = render_title ? -title_height : 0;\n area[2] = size[0] + 1;\n area[3] = render_title ? size[1] + title_height : size[1];\n var old_alpha = ctx.globalAlpha;\n {\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE || low_quality) {\n ctx.fillRect(area[0], area[1], area[2], area[3]);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n area[0],\n area[1],\n area[2],\n area[3],\n shape == LiteGraph.CARD_SHAPE ? [this.round_radius, this.round_radius, 0, 0] : [this.round_radius]\n );\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n if (!node2.flags.collapsed && render_title) {\n ctx.shadowColor = \"transparent\";\n ctx.fillStyle = \"rgba(0,0,0,0.2)\";\n ctx.fillRect(0, -1, area[2], 2);\n }\n }\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawBackground) {\n node2.onDrawBackground(ctx, this, this.canvas, this.graph_mouse);\n }\n if (render_title || title_mode == LiteGraph.TRANSPARENT_TITLE) {\n if (node2.onDrawTitleBar) {\n node2.onDrawTitleBar(ctx, title_height, size, this.ds.scale, fgcolor);\n } else if (title_mode != LiteGraph.TRANSPARENT_TITLE && (node2.constructor.title_color || this.render_title_colored)) {\n var title_color = node2.constructor.title_color || fgcolor;\n if (node2.flags.collapsed) {\n ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;\n }\n if (this.use_gradients) {\n var grad = LGraphCanvas.gradients[title_color];\n if (!grad) {\n grad = LGraphCanvas.gradients[title_color] = ctx.createLinearGradient(0, 0, 400, 0);\n grad.addColorStop(0, title_color);\n grad.addColorStop(1, \"#000\");\n }\n ctx.fillStyle = grad;\n } else {\n ctx.fillStyle = title_color;\n }\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE || low_quality) {\n ctx.rect(0, -title_height, size[0] + 1, title_height);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n 0,\n -title_height,\n size[0] + 1,\n title_height,\n node2.flags.collapsed ? [this.round_radius] : [this.round_radius, this.round_radius, 0, 0]\n );\n }\n ctx.fill();\n ctx.shadowColor = \"transparent\";\n }\n var colState = false;\n if (LiteGraph.node_box_coloured_by_mode) {\n if (LiteGraph.NODE_MODES_COLORS[node2.mode]) {\n colState = LiteGraph.NODE_MODES_COLORS[node2.mode];\n }\n }\n if (LiteGraph.node_box_coloured_when_on) {\n colState = node2.action_triggered ? \"#FFF\" : node2.execute_triggered ? \"#AAA\" : colState;\n }\n var box_size = 10;\n if (node2.onDrawTitleBox) {\n node2.onDrawTitleBox(ctx, title_height, size, this.ds.scale);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CIRCLE_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n if (low_quality) {\n ctx.fillStyle = \"black\";\n ctx.beginPath();\n ctx.arc(\n title_height * 0.5,\n title_height * -0.5,\n box_size * 0.5 + 1,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n }\n ctx.fillStyle = node2.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR;\n if (low_quality)\n ctx.fillRect(title_height * 0.5 - box_size * 0.5, title_height * -0.5 - box_size * 0.5, box_size, box_size);\n else {\n ctx.beginPath();\n ctx.arc(\n title_height * 0.5,\n title_height * -0.5,\n box_size * 0.5,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n }\n } else {\n if (low_quality) {\n ctx.fillStyle = \"black\";\n ctx.fillRect(\n (title_height - box_size) * 0.5 - 1,\n (title_height + box_size) * -0.5 - 1,\n box_size + 2,\n box_size + 2\n );\n }\n ctx.fillStyle = node2.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR;\n ctx.fillRect(\n (title_height - box_size) * 0.5,\n (title_height + box_size) * -0.5,\n box_size,\n box_size\n );\n }\n ctx.globalAlpha = old_alpha;\n if (node2.onDrawTitleText) {\n node2.onDrawTitleText(\n ctx,\n title_height,\n size,\n this.ds.scale,\n this.title_text_font,\n selected\n );\n }\n if (!low_quality) {\n ctx.font = this.title_text_font;\n var title = String(node2.getTitle());\n if (title) {\n if (selected) {\n ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR;\n } else {\n ctx.fillStyle = node2.constructor.title_text_color || this.node_title_color;\n }\n if (node2.flags.collapsed) {\n ctx.textAlign = \"left\";\n ctx.measureText(title);\n ctx.fillText(\n title.substr(0, 20),\n //avoid urls too long\n title_height,\n // + measure.width * 0.5,\n LiteGraph.NODE_TITLE_TEXT_Y - title_height\n );\n ctx.textAlign = \"left\";\n } else {\n ctx.textAlign = \"left\";\n ctx.fillText(\n title,\n title_height,\n LiteGraph.NODE_TITLE_TEXT_Y - title_height\n );\n }\n }\n }\n if (!node2.flags.collapsed && node2.subgraph && !node2.skip_subgraph_button) {\n var w2 = LiteGraph.NODE_TITLE_HEIGHT;\n var x2 = node2.size[0] - w2;\n var over = LiteGraph.isInsideRectangle(this.graph_mouse[0] - node2.pos[0], this.graph_mouse[1] - node2.pos[1], x2 + 2, -w2 + 2, w2 - 4, w2 - 4);\n ctx.fillStyle = over ? \"#888\" : \"#555\";\n if (shape == LiteGraph.BOX_SHAPE || low_quality)\n ctx.fillRect(x2 + 2, -w2 + 2, w2 - 4, w2 - 4);\n else {\n ctx.beginPath();\n ctx.roundRect(x2 + 2, -w2 + 2, w2 - 4, w2 - 4, [4]);\n ctx.fill();\n }\n ctx.fillStyle = \"#333\";\n ctx.beginPath();\n ctx.moveTo(x2 + w2 * 0.2, -w2 * 0.6);\n ctx.lineTo(x2 + w2 * 0.8, -w2 * 0.6);\n ctx.lineTo(x2 + w2 * 0.5, -w2 * 0.3);\n ctx.fill();\n }\n if (node2.onDrawTitle) {\n node2.onDrawTitle(ctx);\n }\n }\n if (selected) {\n if (node2.onBounding) {\n node2.onBounding(area);\n }\n if (title_mode == LiteGraph.TRANSPARENT_TITLE) {\n area[1] -= title_height;\n area[3] += title_height;\n }\n ctx.lineWidth = 1;\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE) {\n ctx.rect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3]\n );\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE && node2.flags.collapsed) {\n ctx.roundRect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3],\n [this.round_radius * 2]\n );\n } else if (shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3],\n [this.round_radius * 2, 2, this.round_radius * 2, 2]\n );\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5 + 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.strokeStyle = LiteGraph.NODE_BOX_OUTLINE_COLOR;\n ctx.stroke();\n ctx.strokeStyle = fgcolor;\n ctx.globalAlpha = 1;\n }\n if (node2.execute_triggered > 0) node2.execute_triggered--;\n if (node2.action_triggered > 0) node2.action_triggered--;\n };\n var margin_area = new Float32Array(4);\n var link_bounding = new Float32Array(4);\n var tempA = new Float32Array(2);\n var tempB = new Float32Array(2);\n LGraphCanvas.prototype.drawConnections = function(ctx) {\n var now = LiteGraph.getTime();\n var visible_area = this.visible_area;\n margin_area[0] = visible_area[0] - 20;\n margin_area[1] = visible_area[1] - 20;\n margin_area[2] = visible_area[2] + 40;\n margin_area[3] = visible_area[3] + 40;\n ctx.lineWidth = this.connections_width;\n ctx.fillStyle = \"#AAA\";\n ctx.strokeStyle = \"#AAA\";\n ctx.globalAlpha = this.editor_alpha;\n var nodes = this.graph._nodes;\n for (var n = 0, l = nodes.length; n < l; ++n) {\n var node2 = nodes[n];\n if (!node2.inputs || !node2.inputs.length) {\n continue;\n }\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n var input = node2.inputs[i2];\n if (!input || input.link == null) {\n continue;\n }\n var link_id = input.link;\n var link = this.graph.links[link_id];\n if (!link) {\n continue;\n }\n var start_node = this.graph.getNodeById(link.origin_id);\n if (start_node == null) {\n continue;\n }\n var start_node_slot = link.origin_slot;\n var start_node_slotpos = null;\n if (start_node_slot == -1) {\n start_node_slotpos = [\n start_node.pos[0] + 10,\n start_node.pos[1] + 10\n ];\n } else {\n start_node_slotpos = start_node.getConnectionPos(\n false,\n start_node_slot,\n tempA\n );\n }\n var end_node_slotpos = node2.getConnectionPos(true, i2, tempB);\n link_bounding[0] = start_node_slotpos[0];\n link_bounding[1] = start_node_slotpos[1];\n link_bounding[2] = end_node_slotpos[0] - start_node_slotpos[0];\n link_bounding[3] = end_node_slotpos[1] - start_node_slotpos[1];\n if (link_bounding[2] < 0) {\n link_bounding[0] += link_bounding[2];\n link_bounding[2] = Math.abs(link_bounding[2]);\n }\n if (link_bounding[3] < 0) {\n link_bounding[1] += link_bounding[3];\n link_bounding[3] = Math.abs(link_bounding[3]);\n }\n if (!overlapBounding(link_bounding, margin_area)) {\n continue;\n }\n var start_slot = start_node.outputs[start_node_slot];\n var end_slot = node2.inputs[i2];\n if (!start_slot || !end_slot) {\n continue;\n }\n var start_dir = start_slot.dir || (start_node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT);\n var end_dir = end_slot.dir || (node2.horizontal ? LiteGraph.UP : LiteGraph.LEFT);\n this.renderLink(\n ctx,\n start_node_slotpos,\n end_node_slotpos,\n link,\n false,\n 0,\n null,\n start_dir,\n end_dir\n );\n if (link && link._last_time && now - link._last_time < 1e3) {\n var f = 2 - (now - link._last_time) * 2e-3;\n var tmp = ctx.globalAlpha;\n ctx.globalAlpha = tmp * f;\n this.renderLink(\n ctx,\n start_node_slotpos,\n end_node_slotpos,\n link,\n true,\n f,\n \"white\",\n start_dir,\n end_dir\n );\n ctx.globalAlpha = tmp;\n }\n }\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.renderLink = function(ctx, a, b, link, skip_border, flow, color, start_dir, end_dir, num_sublines) {\n if (link) {\n this.visible_links.push(link);\n }\n if (!color && link) {\n color = link.color || LGraphCanvas.link_type_colors[link.type];\n }\n if (!color) {\n color = this.default_link_color;\n }\n if (link != null && this.highlighted_links[link.id]) {\n color = \"#FFF\";\n }\n start_dir = start_dir || LiteGraph.RIGHT;\n end_dir = end_dir || LiteGraph.LEFT;\n var dist = distance(a, b);\n if (this.render_connections_border && this.ds.scale > 0.6) {\n ctx.lineWidth = this.connections_width + 4;\n }\n ctx.lineJoin = \"round\";\n num_sublines = num_sublines || 1;\n if (num_sublines > 1) {\n ctx.lineWidth = 0.5;\n }\n ctx.beginPath();\n for (var i2 = 0; i2 < num_sublines; i2 += 1) {\n var offsety = (i2 - (num_sublines - 1) * 0.5) * 5;\n if (this.links_render_mode == LiteGraph.SPLINE_LINK) {\n ctx.moveTo(a[0], a[1] + offsety);\n var start_offset_x = 0;\n var start_offset_y = 0;\n var end_offset_x = 0;\n var end_offset_y = 0;\n switch (start_dir) {\n case LiteGraph.LEFT:\n start_offset_x = dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n start_offset_x = dist * 0.25;\n break;\n case LiteGraph.UP:\n start_offset_y = dist * -0.25;\n break;\n case LiteGraph.DOWN:\n start_offset_y = dist * 0.25;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n end_offset_x = dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n end_offset_x = dist * 0.25;\n break;\n case LiteGraph.UP:\n end_offset_y = dist * -0.25;\n break;\n case LiteGraph.DOWN:\n end_offset_y = dist * 0.25;\n break;\n }\n ctx.bezierCurveTo(\n a[0] + start_offset_x,\n a[1] + start_offset_y + offsety,\n b[0] + end_offset_x,\n b[1] + end_offset_y + offsety,\n b[0],\n b[1] + offsety\n );\n } else if (this.links_render_mode == LiteGraph.LINEAR_LINK) {\n ctx.moveTo(a[0], a[1] + offsety);\n var start_offset_x = 0;\n var start_offset_y = 0;\n var end_offset_x = 0;\n var end_offset_y = 0;\n switch (start_dir) {\n case LiteGraph.LEFT:\n start_offset_x = -1;\n break;\n case LiteGraph.RIGHT:\n start_offset_x = 1;\n break;\n case LiteGraph.UP:\n start_offset_y = -1;\n break;\n case LiteGraph.DOWN:\n start_offset_y = 1;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n end_offset_x = -1;\n break;\n case LiteGraph.RIGHT:\n end_offset_x = 1;\n break;\n case LiteGraph.UP:\n end_offset_y = -1;\n break;\n case LiteGraph.DOWN:\n end_offset_y = 1;\n break;\n }\n var l = 15;\n ctx.lineTo(\n a[0] + start_offset_x * l,\n a[1] + start_offset_y * l + offsety\n );\n ctx.lineTo(\n b[0] + end_offset_x * l,\n b[1] + end_offset_y * l + offsety\n );\n ctx.lineTo(b[0], b[1] + offsety);\n } else if (this.links_render_mode == LiteGraph.STRAIGHT_LINK) {\n ctx.moveTo(a[0], a[1]);\n var start_x = a[0];\n var start_y = a[1];\n var end_x = b[0];\n var end_y = b[1];\n if (start_dir == LiteGraph.RIGHT) {\n start_x += 10;\n } else {\n start_y += 10;\n }\n if (end_dir == LiteGraph.LEFT) {\n end_x -= 10;\n } else {\n end_y -= 10;\n }\n ctx.lineTo(start_x, start_y);\n ctx.lineTo((start_x + end_x) * 0.5, start_y);\n ctx.lineTo((start_x + end_x) * 0.5, end_y);\n ctx.lineTo(end_x, end_y);\n ctx.lineTo(b[0], b[1]);\n } else {\n return;\n }\n }\n if (this.render_connections_border && this.ds.scale > 0.6 && !skip_border) {\n ctx.strokeStyle = \"rgba(0,0,0,0.5)\";\n ctx.stroke();\n }\n ctx.lineWidth = this.connections_width;\n ctx.fillStyle = ctx.strokeStyle = color;\n ctx.stroke();\n var pos2 = this.computeConnectionPoint(a, b, 0.5, start_dir, end_dir);\n if (link && link._pos) {\n link._pos[0] = pos2[0];\n link._pos[1] = pos2[1];\n }\n if (this.ds.scale >= 0.6 && this.highquality_render && end_dir != LiteGraph.CENTER) {\n if (this.render_connection_arrows) {\n var posA = this.computeConnectionPoint(\n a,\n b,\n 0.25,\n start_dir,\n end_dir\n );\n var posB = this.computeConnectionPoint(\n a,\n b,\n 0.26,\n start_dir,\n end_dir\n );\n var posC = this.computeConnectionPoint(\n a,\n b,\n 0.75,\n start_dir,\n end_dir\n );\n var posD = this.computeConnectionPoint(\n a,\n b,\n 0.76,\n start_dir,\n end_dir\n );\n var angleA = 0;\n var angleB = 0;\n if (this.render_curved_connections) {\n angleA = -Math.atan2(posB[0] - posA[0], posB[1] - posA[1]);\n angleB = -Math.atan2(posD[0] - posC[0], posD[1] - posC[1]);\n } else {\n angleB = angleA = b[1] > a[1] ? 0 : Math.PI;\n }\n ctx.save();\n ctx.translate(posA[0], posA[1]);\n ctx.rotate(angleA);\n ctx.beginPath();\n ctx.moveTo(-5, -3);\n ctx.lineTo(0, 7);\n ctx.lineTo(5, -3);\n ctx.fill();\n ctx.restore();\n ctx.save();\n ctx.translate(posC[0], posC[1]);\n ctx.rotate(angleB);\n ctx.beginPath();\n ctx.moveTo(-5, -3);\n ctx.lineTo(0, 7);\n ctx.lineTo(5, -3);\n ctx.fill();\n ctx.restore();\n }\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 5, 0, Math.PI * 2);\n ctx.fill();\n }\n if (flow) {\n ctx.fillStyle = color;\n for (var i2 = 0; i2 < 5; ++i2) {\n var f = (LiteGraph.getTime() * 1e-3 + i2 * 0.2) % 1;\n var pos2 = this.computeConnectionPoint(\n a,\n b,\n f,\n start_dir,\n end_dir\n );\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 5, 0, 2 * Math.PI);\n ctx.fill();\n }\n }\n };\n LGraphCanvas.prototype.computeConnectionPoint = function(a, b, t, start_dir, end_dir) {\n start_dir = start_dir || LiteGraph.RIGHT;\n end_dir = end_dir || LiteGraph.LEFT;\n var dist = distance(a, b);\n var p0 = a;\n var p1 = [a[0], a[1]];\n var p2 = [b[0], b[1]];\n var p3 = b;\n switch (start_dir) {\n case LiteGraph.LEFT:\n p1[0] += dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n p1[0] += dist * 0.25;\n break;\n case LiteGraph.UP:\n p1[1] += dist * -0.25;\n break;\n case LiteGraph.DOWN:\n p1[1] += dist * 0.25;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n p2[0] += dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n p2[0] += dist * 0.25;\n break;\n case LiteGraph.UP:\n p2[1] += dist * -0.25;\n break;\n case LiteGraph.DOWN:\n p2[1] += dist * 0.25;\n break;\n }\n var c1 = (1 - t) * (1 - t) * (1 - t);\n var c2 = 3 * ((1 - t) * (1 - t)) * t;\n var c3 = 3 * (1 - t) * (t * t);\n var c4 = t * t * t;\n var x2 = c1 * p0[0] + c2 * p1[0] + c3 * p2[0] + c4 * p3[0];\n var y2 = c1 * p0[1] + c2 * p1[1] + c3 * p2[1] + c4 * p3[1];\n return [x2, y2];\n };\n LGraphCanvas.prototype.drawExecutionOrder = function(ctx) {\n ctx.shadowColor = \"transparent\";\n ctx.globalAlpha = 0.25;\n ctx.textAlign = \"center\";\n ctx.strokeStyle = \"white\";\n ctx.globalAlpha = 0.75;\n var visible_nodes = this.visible_nodes;\n for (var i2 = 0; i2 < visible_nodes.length; ++i2) {\n var node2 = visible_nodes[i2];\n ctx.fillStyle = \"black\";\n ctx.fillRect(\n node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT,\n node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT\n );\n if (node2.order == 0) {\n ctx.strokeRect(\n node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,\n node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,\n LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT\n );\n }\n ctx.fillStyle = \"#FFF\";\n ctx.fillText(\n node2.order,\n node2.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * -0.5,\n node2.pos[1] - 6\n );\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.drawNodeWidgets = function(node2, posY, ctx, active_widget2) {\n if (!node2.widgets || !node2.widgets.length) {\n return 0;\n }\n var width2 = node2.size[0];\n var widgets = node2.widgets;\n posY += 2;\n var H = LiteGraph.NODE_WIDGET_HEIGHT;\n var show_text = this.ds.scale > 0.5;\n ctx.save();\n ctx.globalAlpha = this.editor_alpha;\n var outline_color = LiteGraph.WIDGET_OUTLINE_COLOR;\n var background_color = LiteGraph.WIDGET_BGCOLOR;\n var text_color = LiteGraph.WIDGET_TEXT_COLOR;\n var secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR;\n var margin = 15;\n for (var i2 = 0; i2 < widgets.length; ++i2) {\n var w2 = widgets[i2];\n var y2 = posY;\n if (w2.y) {\n y2 = w2.y;\n }\n w2.last_y = y2;\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = \"#222\";\n ctx.textAlign = \"left\";\n if (w2.disabled)\n ctx.globalAlpha *= 0.5;\n var widget_width2 = w2.width || width2;\n switch (w2.type) {\n case \"button\":\n ctx.fillStyle = background_color;\n if (w2.clicked) {\n ctx.fillStyle = \"#AAA\";\n w2.clicked = false;\n this.dirty_canvas = true;\n }\n ctx.fillRect(margin, y2, widget_width2 - margin * 2, H);\n if (show_text && !w2.disabled)\n ctx.strokeRect(margin, y2, widget_width2 - margin * 2, H);\n if (show_text) {\n ctx.textAlign = \"center\";\n ctx.fillStyle = text_color;\n ctx.fillText(w2.label || w2.name, widget_width2 * 0.5, y2 + H * 0.7);\n }\n break;\n case \"toggle\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text && !w2.disabled)\n ctx.stroke();\n ctx.fillStyle = w2.value ? \"#89A\" : \"#333\";\n ctx.beginPath();\n ctx.arc(widget_width2 - margin * 2, y2 + H * 0.5, H * 0.36, 0, Math.PI * 2);\n ctx.fill();\n if (show_text) {\n ctx.fillStyle = secondary_text_color;\n const label = w2.label || w2.name;\n if (label != null) {\n ctx.fillText(label, margin * 2, y2 + H * 0.7);\n }\n ctx.fillStyle = w2.value ? text_color : secondary_text_color;\n ctx.textAlign = \"right\";\n ctx.fillText(\n w2.value ? w2.options.on || \"true\" : w2.options.off || \"false\",\n widget_width2 - 40,\n y2 + H * 0.7\n );\n }\n break;\n case \"slider\":\n ctx.fillStyle = background_color;\n ctx.fillRect(margin, y2, widget_width2 - margin * 2, H);\n var range = w2.options.max - w2.options.min;\n var nvalue2 = (w2.value - w2.options.min) / range;\n if (nvalue2 < 0) nvalue2 = 0;\n if (nvalue2 > 1) nvalue2 = 1;\n ctx.fillStyle = w2.options.hasOwnProperty(\"slider_color\") ? w2.options.slider_color : active_widget2 == w2 ? \"#89A\" : \"#678\";\n ctx.fillRect(margin, y2, nvalue2 * (widget_width2 - margin * 2), H);\n if (show_text && !w2.disabled)\n ctx.strokeRect(margin, y2, widget_width2 - margin * 2, H);\n if (w2.marker) {\n var marker_nvalue = (w2.marker - w2.options.min) / range;\n if (marker_nvalue < 0) marker_nvalue = 0;\n if (marker_nvalue > 1) marker_nvalue = 1;\n ctx.fillStyle = w2.options.hasOwnProperty(\"marker_color\") ? w2.options.marker_color : \"#AA9\";\n ctx.fillRect(margin + marker_nvalue * (widget_width2 - margin * 2), y2, 2, H);\n }\n if (show_text) {\n ctx.textAlign = \"center\";\n ctx.fillStyle = text_color;\n ctx.fillText(\n w2.label || w2.name + \" \" + Number(w2.value).toFixed(\n w2.options.precision != null ? w2.options.precision : 3\n ),\n widget_width2 * 0.5,\n y2 + H * 0.7\n );\n }\n break;\n case \"number\":\n case \"combo\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text) {\n if (!w2.disabled)\n ctx.stroke();\n ctx.fillStyle = text_color;\n if (!w2.disabled) {\n ctx.beginPath();\n ctx.moveTo(margin + 16, y2 + 5);\n ctx.lineTo(margin + 6, y2 + H * 0.5);\n ctx.lineTo(margin + 16, y2 + H - 5);\n ctx.fill();\n ctx.beginPath();\n ctx.moveTo(widget_width2 - margin - 16, y2 + 5);\n ctx.lineTo(widget_width2 - margin - 6, y2 + H * 0.5);\n ctx.lineTo(widget_width2 - margin - 16, y2 + H - 5);\n ctx.fill();\n }\n ctx.fillStyle = secondary_text_color;\n ctx.fillText(w2.label || w2.name, margin * 2 + 5, y2 + H * 0.7);\n ctx.fillStyle = text_color;\n ctx.textAlign = \"right\";\n if (w2.type == \"number\") {\n ctx.fillText(\n Number(w2.value).toFixed(\n w2.options.precision !== void 0 ? w2.options.precision : 3\n ),\n widget_width2 - margin * 2 - 20,\n y2 + H * 0.7\n );\n } else {\n var v2 = w2.value;\n if (w2.options.values) {\n var values2 = w2.options.values;\n if (values2.constructor === Function)\n values2 = values2();\n if (values2 && values2.constructor !== Array)\n v2 = values2[w2.value];\n }\n const labelWidth = ctx.measureText(w2.label || w2.name).width + margin * 2;\n const inputWidth = widget_width2 - margin * 4;\n const availableWidth = inputWidth - labelWidth;\n const textWidth = ctx.measureText(v2).width;\n if (textWidth > availableWidth) {\n const ELLIPSIS = \"…\";\n const ellipsisWidth = ctx.measureText(ELLIPSIS).width;\n const charWidthAvg = ctx.measureText(\"a\").width;\n if (availableWidth <= ellipsisWidth) {\n v2 = \"․\";\n } else {\n v2 = `${v2}`;\n const overflowWidth = textWidth + ellipsisWidth - availableWidth;\n if (overflowWidth + charWidthAvg * 3 > availableWidth) {\n const preciseRange = availableWidth + charWidthAvg * 3;\n const preTruncateCt = Math.floor((preciseRange - ellipsisWidth) / charWidthAvg);\n v2 = v2.substr(0, preTruncateCt);\n }\n while (ctx.measureText(v2).width + ellipsisWidth > availableWidth) {\n v2 = v2.substr(0, v2.length - 1);\n }\n v2 += ELLIPSIS;\n }\n }\n ctx.fillText(\n v2,\n widget_width2 - margin * 2 - 20,\n y2 + H * 0.7\n );\n }\n }\n break;\n case \"string\":\n case \"text\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text) {\n if (!w2.disabled)\n ctx.stroke();\n ctx.save();\n ctx.beginPath();\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.clip();\n ctx.fillStyle = secondary_text_color;\n const label = w2.label || w2.name;\n if (label != null) {\n ctx.fillText(label, margin * 2, y2 + H * 0.7);\n }\n ctx.fillStyle = text_color;\n ctx.textAlign = \"right\";\n ctx.fillText(String(w2.value).substr(0, 30), widget_width2 - margin * 2, y2 + H * 0.7);\n ctx.restore();\n }\n break;\n default:\n if (w2.draw) {\n w2.draw(ctx, node2, widget_width2, y2, H);\n }\n break;\n }\n posY += (w2.computeSize ? w2.computeSize(widget_width2)[1] : H) + 4;\n ctx.globalAlpha = this.editor_alpha;\n }\n ctx.restore();\n ctx.textAlign = \"left\";\n };\n LGraphCanvas.prototype.processNodeWidgets = function(node, pos, event, active_widget) {\n if (!node.widgets || !node.widgets.length || !this.allow_interaction && !node.flags.allow_interaction) {\n return null;\n }\n var x = pos[0] - node.pos[0];\n var y = pos[1] - node.pos[1];\n var width = node.size[0];\n var that = this;\n var ref_window = this.getCanvasWindow();\n for (var i = 0; i < node.widgets.length; ++i) {\n var w = node.widgets[i];\n if (!w || w.disabled)\n continue;\n var widget_height = w.computeSize ? w.computeSize(width)[1] : LiteGraph.NODE_WIDGET_HEIGHT;\n var widget_width = w.width || width;\n if (w != active_widget && (x < 6 || x > widget_width - 12 || y < w.last_y || y > w.last_y + widget_height || w.last_y === void 0))\n continue;\n var old_value = w.value;\n switch (w.type) {\n case \"button\":\n if (event.type === LiteGraph.pointerevents_method + \"down\") {\n if (w.callback) {\n setTimeout(function() {\n w.callback(w, that, node, pos, event);\n }, 20);\n }\n w.clicked = true;\n this.dirty_canvas = true;\n }\n break;\n case \"slider\":\n var old_value = w.value;\n var nvalue = clamp((x - 15) / (widget_width - 30), 0, 1);\n if (w.options.read_only) break;\n w.value = w.options.min + (w.options.max - w.options.min) * nvalue;\n if (old_value != w.value) {\n setTimeout(function() {\n inner_value_change(w, w.value);\n }, 20);\n }\n this.dirty_canvas = true;\n break;\n case \"number\":\n case \"combo\":\n var old_value = w.value;\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n var allow_scroll = true;\n if (delta) {\n if (x > -3 && x < widget_width + 3) {\n allow_scroll = false;\n }\n }\n if (allow_scroll && event.type == LiteGraph.pointerevents_method + \"move\" && w.type == \"number\") {\n if (event.deltaX)\n w.value += event.deltaX * 0.1 * (w.options.step || 1);\n if (w.options.min != null && w.value < w.options.min) {\n w.value = w.options.min;\n }\n if (w.options.max != null && w.value > w.options.max) {\n w.value = w.options.max;\n }\n } else if (event.type == LiteGraph.pointerevents_method + \"down\") {\n var values = w.options.values;\n if (values && values.constructor === Function) {\n values = w.options.values(w, node);\n }\n var values_list = null;\n if (w.type != \"number\")\n values_list = values.constructor === Array ? values : Object.keys(values);\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n if (w.type == \"number\") {\n w.value += delta * 0.1 * (w.options.step || 1);\n if (w.options.min != null && w.value < w.options.min) {\n w.value = w.options.min;\n }\n if (w.options.max != null && w.value > w.options.max) {\n w.value = w.options.max;\n }\n } else if (delta) {\n var index = -1;\n this.last_mouseclick = 0;\n if (values.constructor === Object)\n index = values_list.indexOf(String(w.value)) + delta;\n else\n index = values_list.indexOf(w.value) + delta;\n if (index >= values_list.length) {\n index = values_list.length - 1;\n }\n if (index < 0) {\n index = 0;\n }\n if (values.constructor === Array)\n w.value = values[index];\n else\n w.value = index;\n } else {\n let inner_clicked = function(v2, option, event2) {\n if (values != values_list)\n v2 = text_values.indexOf(v2);\n this.value = v2;\n inner_value_change(this, v2);\n that.dirty_canvas = true;\n return false;\n };\n var text_values = values != values_list ? Object.values(values) : values;\n new LiteGraph.ContextMenu(\n text_values,\n {\n scale: Math.max(1, this.ds.scale),\n event,\n className: \"dark\",\n callback: inner_clicked.bind(w)\n },\n ref_window\n );\n }\n } else if (event.type == LiteGraph.pointerevents_method + \"up\" && w.type == \"number\") {\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n if (event.click_time < 200 && delta == 0) {\n this.prompt(\n \"Value\",\n w.value,\n (function(v) {\n if (/^[0-9+\\-*/()\\s]+|\\d+\\.\\d+$/.test(v)) {\n try {\n v = eval(v);\n } catch (e) {\n }\n }\n this.value = Number(v);\n inner_value_change(this, this.value);\n }).bind(w),\n event\n );\n }\n }\n if (old_value != w.value)\n setTimeout(\n (function() {\n inner_value_change(this, this.value);\n }).bind(w),\n 20\n );\n this.dirty_canvas = true;\n break;\n case \"toggle\":\n if (event.type == LiteGraph.pointerevents_method + \"down\") {\n w.value = !w.value;\n setTimeout(function() {\n inner_value_change(w, w.value);\n }, 20);\n }\n break;\n case \"string\":\n case \"text\":\n if (event.type == LiteGraph.pointerevents_method + \"down\") {\n this.prompt(\n \"Value\",\n w.value,\n (function(v2) {\n inner_value_change(this, v2);\n }).bind(w),\n event,\n w.options ? w.options.multiline : false\n );\n }\n break;\n default:\n if (w.mouse) {\n this.dirty_canvas = w.mouse(event, [x, y], node);\n }\n break;\n }\n if (old_value != w.value) {\n if (node.onWidgetChanged)\n node.onWidgetChanged(w.name, w.value, old_value, w);\n node.graph._version++;\n }\n return w;\n }\n function inner_value_change(widget, value) {\n if (widget.type == \"number\") {\n value = Number(value);\n }\n widget.value = value;\n if (widget.options && widget.options.property && node.properties[widget.options.property] !== void 0) {\n node.setProperty(widget.options.property, value);\n }\n if (widget.callback) {\n widget.callback(widget.value, that, node, pos, event);\n }\n }\n return null;\n };\n LGraphCanvas.prototype.drawGroups = function(canvas, ctx) {\n if (!this.graph) {\n return;\n }\n var groups = this.graph._groups;\n ctx.save();\n ctx.globalAlpha = 0.5 * this.editor_alpha;\n for (var i2 = 0; i2 < groups.length; ++i2) {\n var group = groups[i2];\n if (!overlapBounding(this.visible_area, group._bounding)) {\n continue;\n }\n ctx.fillStyle = group.color || \"#335\";\n ctx.strokeStyle = group.color || \"#335\";\n var pos2 = group._pos;\n var size = group._size;\n ctx.globalAlpha = 0.25 * this.editor_alpha;\n ctx.beginPath();\n ctx.rect(pos2[0] + 0.5, pos2[1] + 0.5, size[0], size[1]);\n ctx.fill();\n ctx.globalAlpha = this.editor_alpha;\n ctx.stroke();\n ctx.beginPath();\n ctx.moveTo(pos2[0] + size[0], pos2[1] + size[1]);\n ctx.lineTo(pos2[0] + size[0] - 10, pos2[1] + size[1]);\n ctx.lineTo(pos2[0] + size[0], pos2[1] + size[1] - 10);\n ctx.fill();\n var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;\n ctx.font = font_size + \"px Arial\";\n ctx.textAlign = \"left\";\n ctx.fillText(group.title, pos2[0] + 4, pos2[1] + font_size);\n }\n ctx.restore();\n };\n LGraphCanvas.prototype.adjustNodesSize = function() {\n var nodes = this.graph._nodes;\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].size = nodes[i2].computeSize();\n }\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.resize = function(width2, height) {\n if (!width2 && !height) {\n var parent = this.canvas.parentNode;\n width2 = parent.offsetWidth;\n height = parent.offsetHeight;\n }\n if (this.canvas.width == width2 && this.canvas.height == height) {\n return;\n }\n this.canvas.width = width2;\n this.canvas.height = height;\n this.bgcanvas.width = this.canvas.width;\n this.bgcanvas.height = this.canvas.height;\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.switchLiveMode = function(transition) {\n if (!transition) {\n this.live_mode = !this.live_mode;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n return;\n }\n var self = this;\n var delta2 = this.live_mode ? 1.1 : 0.9;\n if (this.live_mode) {\n this.live_mode = false;\n this.editor_alpha = 0.1;\n }\n var t = setInterval(function() {\n self.editor_alpha *= delta2;\n self.dirty_canvas = true;\n self.dirty_bgcanvas = true;\n if (delta2 < 1 && self.editor_alpha < 0.01) {\n clearInterval(t);\n if (delta2 < 1) {\n self.live_mode = true;\n }\n }\n if (delta2 > 1 && self.editor_alpha > 0.99) {\n clearInterval(t);\n self.editor_alpha = 1;\n }\n }, 1);\n };\n LGraphCanvas.prototype.onNodeSelectionChange = function(node2) {\n return;\n };\n LGraphCanvas.onGroupAdd = function(info, entry, mouse_event) {\n var canvas = LGraphCanvas.active_canvas;\n canvas.getCanvasWindow();\n var group = new LiteGraph.LGraphGroup();\n group.pos = canvas.convertEventToCanvasOffset(mouse_event);\n canvas.graph.add(group);\n };\n LGraphCanvas.getBoundaryNodes = function(nodes) {\n let top = null;\n let right = null;\n let bottom = null;\n let left = null;\n for (const nID in nodes) {\n const node2 = nodes[nID];\n const [x2, y2] = node2.pos;\n const [width2, height] = node2.size;\n if (top === null || y2 < top.pos[1]) {\n top = node2;\n }\n if (right === null || x2 + width2 > right.pos[0] + right.size[0]) {\n right = node2;\n }\n if (bottom === null || y2 + height > bottom.pos[1] + bottom.size[1]) {\n bottom = node2;\n }\n if (left === null || x2 < left.pos[0]) {\n left = node2;\n }\n }\n return {\n \"top\": top,\n \"right\": right,\n \"bottom\": bottom,\n \"left\": left\n };\n };\n LGraphCanvas.prototype.boundaryNodesForSelection = function() {\n return LGraphCanvas.getBoundaryNodes(Object.values(this.selected_nodes));\n };\n LGraphCanvas.alignNodes = function(nodes, direction, align_to) {\n if (!nodes) {\n return;\n }\n const canvas = LGraphCanvas.active_canvas;\n let boundaryNodes = [];\n if (align_to === void 0) {\n boundaryNodes = LGraphCanvas.getBoundaryNodes(nodes);\n } else {\n boundaryNodes = {\n \"top\": align_to,\n \"right\": align_to,\n \"bottom\": align_to,\n \"left\": align_to\n };\n }\n for (const [_, node2] of Object.entries(canvas.selected_nodes)) {\n switch (direction) {\n case \"right\":\n node2.pos[0] = boundaryNodes[\"right\"].pos[0] + boundaryNodes[\"right\"].size[0] - node2.size[0];\n break;\n case \"left\":\n node2.pos[0] = boundaryNodes[\"left\"].pos[0];\n break;\n case \"top\":\n node2.pos[1] = boundaryNodes[\"top\"].pos[1];\n break;\n case \"bottom\":\n node2.pos[1] = boundaryNodes[\"bottom\"].pos[1] + boundaryNodes[\"bottom\"].size[1] - node2.size[1];\n break;\n }\n }\n canvas.dirty_canvas = true;\n canvas.dirty_bgcanvas = true;\n };\n LGraphCanvas.onNodeAlign = function(value, options, event2, prev_menu, node2) {\n new LiteGraph.ContextMenu([\"Top\", \"Bottom\", \"Left\", \"Right\"], {\n event: event2,\n callback: inner_clicked,\n parentMenu: prev_menu\n });\n function inner_clicked(value2) {\n LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value2.toLowerCase(), node2);\n }\n };\n LGraphCanvas.onGroupAlign = function(value, options, event2, prev_menu) {\n new LiteGraph.ContextMenu([\"Top\", \"Bottom\", \"Left\", \"Right\"], {\n event: event2,\n callback: inner_clicked,\n parentMenu: prev_menu\n });\n function inner_clicked(value2) {\n LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value2.toLowerCase());\n }\n };\n LGraphCanvas.onMenuAdd = function(node2, options, e, prev_menu, callback) {\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var graph = canvas.graph;\n if (!graph)\n return;\n function inner_onMenuAdded(base_category, prev_menu2) {\n var categories = LiteGraph.getNodeTypesCategories(canvas.filter || graph.filter).filter(function(category) {\n return category.startsWith(base_category);\n });\n var entries = [];\n categories.map(function(category) {\n if (!category)\n return;\n var base_category_regex = new RegExp(\"^(\" + base_category + \")\");\n var category_name = category.replace(base_category_regex, \"\").split(\"/\")[0];\n var category_path = base_category === \"\" ? category_name + \"/\" : base_category + category_name + \"/\";\n var name = category_name;\n if (name.indexOf(\"::\") != -1)\n name = name.split(\"::\")[1];\n var index2 = entries.findIndex(function(entry) {\n return entry.value === category_path;\n });\n if (index2 === -1) {\n entries.push({ value: category_path, content: name, has_submenu: true, callback: function(value, event2, mouseEvent, contextMenu) {\n inner_onMenuAdded(value.value, contextMenu);\n } });\n }\n });\n var nodes = LiteGraph.getNodeTypesInCategory(base_category.slice(0, -1), canvas.filter || graph.filter);\n nodes.map(function(node3) {\n if (node3.skip_list)\n return;\n var entry = {\n value: node3.type,\n content: node3.title,\n has_submenu: false,\n callback: function(value, event2, mouseEvent, contextMenu) {\n var first_event = contextMenu.getFirstEvent();\n canvas.graph.beforeChange();\n var node4 = LiteGraph.createNode(value.value);\n if (node4) {\n node4.pos = canvas.convertEventToCanvasOffset(first_event);\n canvas.graph.add(node4);\n }\n if (callback)\n callback(node4);\n canvas.graph.afterChange();\n }\n };\n entries.push(entry);\n });\n new LiteGraph.ContextMenu(entries, { event: e, parentMenu: prev_menu2 }, ref_window2);\n }\n inner_onMenuAdded(\"\", prev_menu);\n return false;\n };\n LGraphCanvas.onMenuCollapseAll = function() {\n };\n LGraphCanvas.onMenuNodeEdit = function() {\n };\n LGraphCanvas.showMenuNodeOptionalInputs = function(v2, options, e, prev_menu, node2) {\n if (!node2) {\n return;\n }\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var options = node2.optional_inputs;\n if (node2.onGetInputs) {\n options = node2.onGetInputs();\n }\n var entries = [];\n if (options) {\n for (var i2 = 0; i2 < options.length; i2++) {\n var entry = options[i2];\n if (!entry) {\n entries.push(null);\n continue;\n }\n var label = entry[0];\n if (!entry[2])\n entry[2] = {};\n if (entry[2].label) {\n label = entry[2].label;\n }\n entry[2].removable = true;\n var data = { content: label, value: entry };\n if (entry[1] == LiteGraph.ACTION) {\n data.className = \"event\";\n }\n entries.push(data);\n }\n }\n if (node2.onMenuNodeInputs) {\n var retEntries = node2.onMenuNodeInputs(entries);\n if (retEntries) entries = retEntries;\n }\n if (!entries.length) {\n console.log(\"no input entries\");\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v3, e2, prev) {\n if (!node2) {\n return;\n }\n if (v3.callback) {\n v3.callback.call(that2, node2, v3, e2, prev);\n }\n if (v3.value) {\n node2.graph.beforeChange();\n node2.addInput(v3.value[0], v3.value[1], v3.value[2]);\n if (node2.onNodeInputAdd) {\n node2.onNodeInputAdd(v3.value);\n }\n node2.setDirtyCanvas(true, true);\n node2.graph.afterChange();\n }\n }\n return false;\n };\n LGraphCanvas.showMenuNodeOptionalOutputs = function(v2, options, e, prev_menu, node2) {\n if (!node2) {\n return;\n }\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var options = node2.optional_outputs;\n if (node2.onGetOutputs) {\n options = node2.onGetOutputs();\n }\n var entries = [];\n if (options) {\n for (var i2 = 0; i2 < options.length; i2++) {\n var entry = options[i2];\n if (!entry) {\n entries.push(null);\n continue;\n }\n if (node2.flags && node2.flags.skip_repeated_outputs && node2.findOutputSlot(entry[0]) != -1) {\n continue;\n }\n var label = entry[0];\n if (!entry[2])\n entry[2] = {};\n if (entry[2].label) {\n label = entry[2].label;\n }\n entry[2].removable = true;\n var data = { content: label, value: entry };\n if (entry[1] == LiteGraph.EVENT) {\n data.className = \"event\";\n }\n entries.push(data);\n }\n }\n if (this.onMenuNodeOutputs) {\n entries = this.onMenuNodeOutputs(entries);\n }\n if (LiteGraph.do_add_triggers_slots) {\n if (node2.findOutputSlot(\"onExecuted\") == -1) {\n entries.push({ content: \"On Executed\", value: [\"onExecuted\", LiteGraph.EVENT, { nameLocked: true }], className: \"event\" });\n }\n }\n if (node2.onMenuNodeOutputs) {\n var retEntries = node2.onMenuNodeOutputs(entries);\n if (retEntries) entries = retEntries;\n }\n if (!entries.length) {\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v3, e2, prev) {\n if (!node2) {\n return;\n }\n if (v3.callback) {\n v3.callback.call(that2, node2, v3, e2, prev);\n }\n if (!v3.value) {\n return;\n }\n var value = v3.value[1];\n if (value && (value.constructor === Object || value.constructor === Array)) {\n var entries2 = [];\n for (var i3 in value) {\n entries2.push({ content: i3, value: value[i3] });\n }\n new LiteGraph.ContextMenu(entries2, {\n event: e2,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n });\n return false;\n } else {\n node2.graph.beforeChange();\n node2.addOutput(v3.value[0], v3.value[1], v3.value[2]);\n if (node2.onNodeOutputAdd) {\n node2.onNodeOutputAdd(v3.value);\n }\n node2.setDirtyCanvas(true, true);\n node2.graph.afterChange();\n }\n }\n return false;\n };\n LGraphCanvas.onShowMenuNodeProperties = function(value, options, e, prev_menu, node2) {\n if (!node2 || !node2.properties) {\n return;\n }\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var entries = [];\n for (var i2 in node2.properties) {\n var value = node2.properties[i2] !== void 0 ? node2.properties[i2] : \" \";\n if (typeof value == \"object\")\n value = JSON.stringify(value);\n var info = node2.getPropertyInfo(i2);\n if (info.type == \"enum\" || info.type == \"combo\")\n value = LGraphCanvas.getPropertyPrintableValue(value, info.values);\n value = LGraphCanvas.decodeHTML(value);\n entries.push({\n content: \"\" + (info.label ? info.label : i2) + \"\" + value + \"\",\n value: i2\n });\n }\n if (!entries.length) {\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n allow_html: true,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v2, options2, e2, prev) {\n if (!node2) {\n return;\n }\n var rect = this.getBoundingClientRect();\n canvas.showEditPropertyValue(node2, v2.value, {\n position: [rect.left, rect.top]\n });\n }\n return false;\n };\n LGraphCanvas.decodeHTML = function(str) {\n var e = document.createElement(\"div\");\n e.innerText = str;\n return e.innerHTML;\n };\n LGraphCanvas.onMenuResizeNode = function(value, options, e, menu, node2) {\n if (!node2) {\n return;\n }\n var fApplyMultiNode = function(node3) {\n node3.size = node3.computeSize();\n if (node3.onResize)\n node3.onResize(node3.size);\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.prototype.showLinkMenu = function(link, e) {\n var that2 = this;\n var node_left = that2.graph.getNodeById(link.origin_id);\n var node_right = that2.graph.getNodeById(link.target_id);\n var fromType = false;\n if (node_left && node_left.outputs && node_left.outputs[link.origin_slot]) fromType = node_left.outputs[link.origin_slot].type;\n var destType = false;\n if (node_right && node_right.outputs && node_right.outputs[link.target_slot]) destType = node_right.inputs[link.target_slot].type;\n var options = [\"Add Node\", null, \"Delete\", null];\n var menu = new LiteGraph.ContextMenu(options, {\n event: e,\n title: link.data != null ? link.data.constructor.name : null,\n callback: inner_clicked\n });\n function inner_clicked(v2, options2, e2) {\n switch (v2) {\n case \"Add Node\":\n LGraphCanvas.onMenuAdd(null, null, e2, menu, function(node2) {\n if (!node2.inputs || !node2.inputs.length || !node2.outputs || !node2.outputs.length) {\n return;\n }\n if (node_left.connectByType(link.origin_slot, node2, fromType)) {\n node2.connectByType(link.target_slot, node_right, destType);\n node2.pos[0] -= node2.size[0] * 0.5;\n }\n });\n break;\n case \"Delete\":\n that2.graph.removeLink(link.id);\n break;\n }\n }\n return false;\n };\n LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) {\n var optPass = optPass || {};\n var opts = Object.assign(\n {\n nodeFrom: null,\n slotFrom: null,\n nodeTo: null,\n slotTo: null,\n position: [],\n nodeType: null,\n posAdd: [0, 0],\n posSizeFix: [0, 0]\n // alpha, adjust the position x,y based on the new node size w,h\n },\n optPass\n );\n var that2 = this;\n var isFrom = opts.nodeFrom && opts.slotFrom !== null;\n var isTo = !isFrom && opts.nodeTo && opts.slotTo !== null;\n if (!isFrom && !isTo) {\n console.warn(\"No data passed to createDefaultNodeForSlot \" + opts.nodeFrom + \" \" + opts.slotFrom + \" \" + opts.nodeTo + \" \" + opts.slotTo);\n return false;\n }\n if (!opts.nodeType) {\n console.warn(\"No type to createDefaultNodeForSlot\");\n return false;\n }\n var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;\n var slotX = isFrom ? opts.slotFrom : opts.slotTo;\n var iSlotConn = false;\n switch (typeof slotX) {\n case \"string\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"object\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);\n break;\n case \"number\":\n iSlotConn = slotX;\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"undefined\":\n default:\n console.warn(\"Cant get slot information \" + slotX);\n return false;\n }\n if (slotX === false || iSlotConn === false) {\n console.warn(\"createDefaultNodeForSlot bad slotX \" + slotX + \" \" + iSlotConn);\n }\n var fromSlotType = slotX.type == LiteGraph.EVENT ? \"_event_\" : slotX.type;\n var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;\n if (slotTypesDefault && slotTypesDefault[fromSlotType]) {\n if (slotX.link !== null) ;\n let nodeNewType = false;\n if (typeof slotTypesDefault[fromSlotType] == \"object\" || typeof slotTypesDefault[fromSlotType] == \"array\") {\n for (var typeX in slotTypesDefault[fromSlotType]) {\n if (opts.nodeType == slotTypesDefault[fromSlotType][typeX] || opts.nodeType == \"AUTO\") {\n nodeNewType = slotTypesDefault[fromSlotType][typeX];\n break;\n }\n }\n } else {\n if (opts.nodeType == slotTypesDefault[fromSlotType] || opts.nodeType == \"AUTO\") nodeNewType = slotTypesDefault[fromSlotType];\n }\n if (nodeNewType) {\n var nodeNewOpts = false;\n if (typeof nodeNewType == \"object\" && nodeNewType.node) {\n nodeNewOpts = nodeNewType;\n nodeNewType = nodeNewType.node;\n }\n var newNode = LiteGraph.createNode(nodeNewType);\n if (newNode) {\n if (nodeNewOpts) {\n if (nodeNewOpts.properties) {\n for (var i2 in nodeNewOpts.properties) {\n newNode.addProperty(i2, nodeNewOpts.properties[i2]);\n }\n }\n if (nodeNewOpts.inputs) {\n newNode.inputs = [];\n for (var i2 in nodeNewOpts.inputs) {\n newNode.addOutput(\n nodeNewOpts.inputs[i2][0],\n nodeNewOpts.inputs[i2][1]\n );\n }\n }\n if (nodeNewOpts.outputs) {\n newNode.outputs = [];\n for (var i2 in nodeNewOpts.outputs) {\n newNode.addOutput(\n nodeNewOpts.outputs[i2][0],\n nodeNewOpts.outputs[i2][1]\n );\n }\n }\n if (nodeNewOpts.title) {\n newNode.title = nodeNewOpts.title;\n }\n if (nodeNewOpts.json) {\n newNode.configure(nodeNewOpts.json);\n }\n }\n that2.graph.add(newNode);\n newNode.pos = [\n opts.position[0] + opts.posAdd[0] + (opts.posSizeFix[0] ? opts.posSizeFix[0] * newNode.size[0] : 0),\n opts.position[1] + opts.posAdd[1] + (opts.posSizeFix[1] ? opts.posSizeFix[1] * newNode.size[1] : 0)\n ];\n if (isFrom) {\n opts.nodeFrom.connectByType(iSlotConn, newNode, fromSlotType);\n } else {\n opts.nodeTo.connectByTypeOutput(iSlotConn, newNode, fromSlotType);\n }\n return true;\n } else {\n console.log(\"failed creating \" + nodeNewType);\n }\n }\n }\n return false;\n };\n LGraphCanvas.prototype.showConnectionMenu = function(optPass) {\n var optPass = optPass || {};\n var opts = Object.assign(\n {\n nodeFrom: null,\n slotFrom: null,\n nodeTo: null,\n slotTo: null,\n e: null\n },\n optPass\n );\n var that2 = this;\n var isFrom = opts.nodeFrom && opts.slotFrom;\n var isTo = !isFrom && opts.nodeTo && opts.slotTo;\n if (!isFrom && !isTo) {\n console.warn(\"No data passed to showConnectionMenu\");\n return false;\n }\n var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;\n var slotX = isFrom ? opts.slotFrom : opts.slotTo;\n var iSlotConn = false;\n switch (typeof slotX) {\n case \"string\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"object\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);\n break;\n case \"number\":\n iSlotConn = slotX;\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n default:\n console.warn(\"Cant get slot information \" + slotX);\n return false;\n }\n var options = [\"Add Node\", null];\n if (that2.allow_searchbox) {\n options.push(\"Search\");\n options.push(null);\n }\n var fromSlotType = slotX.type == LiteGraph.EVENT ? \"_event_\" : slotX.type;\n var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;\n if (slotTypesDefault && slotTypesDefault[fromSlotType]) {\n if (typeof slotTypesDefault[fromSlotType] == \"object\" || typeof slotTypesDefault[fromSlotType] == \"array\") {\n for (var typeX in slotTypesDefault[fromSlotType]) {\n options.push(slotTypesDefault[fromSlotType][typeX]);\n }\n } else {\n options.push(slotTypesDefault[fromSlotType]);\n }\n }\n var menu = new LiteGraph.ContextMenu(options, {\n event: opts.e,\n title: (slotX && slotX.name != \"\" ? slotX.name + (fromSlotType ? \" | \" : \"\") : \"\") + (slotX && fromSlotType ? fromSlotType : \"\"),\n callback: inner_clicked\n });\n function inner_clicked(v2, options2, e) {\n switch (v2) {\n case \"Add Node\":\n LGraphCanvas.onMenuAdd(null, null, e, menu, function(node2) {\n if (isFrom) {\n opts.nodeFrom.connectByType(iSlotConn, node2, fromSlotType);\n } else {\n opts.nodeTo.connectByTypeOutput(iSlotConn, node2, fromSlotType);\n }\n });\n break;\n case \"Search\":\n if (isFrom) {\n that2.showSearchBox(e, { node_from: opts.nodeFrom, slot_from: slotX, type_filter_in: fromSlotType });\n } else {\n that2.showSearchBox(e, { node_to: opts.nodeTo, slot_from: slotX, type_filter_out: fromSlotType });\n }\n break;\n default:\n that2.createDefaultNodeForSlot(Object.assign(opts, {\n position: [opts.e.canvasX, opts.e.canvasY],\n nodeType: v2\n }));\n break;\n }\n }\n return false;\n };\n LGraphCanvas.onShowPropertyEditor = function(item, options, e, menu, node2) {\n var property = item.property || \"title\";\n var value = node2[property];\n var dialog = document.createElement(\"div\");\n dialog.is_modified = false;\n dialog.className = \"graphdialog\";\n dialog.innerHTML = \"\";\n dialog.close = function() {\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var title = dialog.querySelector(\".name\");\n title.innerText = property;\n var input = dialog.querySelector(\".value\");\n if (input) {\n input.value = value;\n input.addEventListener(\"blur\", function(e2) {\n this.focus();\n });\n input.addEventListener(\"keydown\", function(e2) {\n dialog.is_modified = true;\n if (e2.keyCode == 27) {\n dialog.close();\n } else if (e2.keyCode == 13) {\n inner();\n } else if (e2.keyCode != 13 && e2.target.localName != \"textarea\") {\n return;\n }\n e2.preventDefault();\n e2.stopPropagation();\n });\n }\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n var rect = canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (event) {\n dialog.style.left = event.clientX + offsetx + \"px\";\n dialog.style.top = event.clientY + offsety + \"px\";\n } else {\n dialog.style.left = canvas.width * 0.5 + offsetx + \"px\";\n dialog.style.top = canvas.height * 0.5 + offsety + \"px\";\n }\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", inner);\n canvas.parentNode.appendChild(dialog);\n if (input) input.focus();\n var dialogCloseTimer = null;\n dialog.addEventListener(\"mouseleave\", function(e2) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n dialog.addEventListener(\"mouseenter\", function(e2) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n function inner() {\n if (input) setValue(input.value);\n }\n function setValue(value2) {\n if (item.type == \"Number\") {\n value2 = Number(value2);\n } else if (item.type == \"Boolean\") {\n value2 = Boolean(value2);\n }\n node2[property] = value2;\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n node2.setDirtyCanvas(true, true);\n }\n };\n LGraphCanvas.prototype.prompt = function(title, value, callback, event2, multiline) {\n var that2 = this;\n title = title || \"\";\n var dialog = document.createElement(\"div\");\n dialog.is_modified = false;\n dialog.className = \"graphdialog rounded\";\n if (multiline)\n dialog.innerHTML = \" \";\n else\n dialog.innerHTML = \" \";\n dialog.close = function() {\n that2.prompt_box = null;\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n canvas.parentNode.appendChild(dialog);\n if (this.ds.scale > 1) {\n dialog.style.transform = \"scale(\" + this.ds.scale + \")\";\n }\n var dialogCloseTimer = null;\n var prevent_timeout = false;\n LiteGraph.pointerListenerAdd(dialog, \"leave\", function(e) {\n if (prevent_timeout)\n return;\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n LiteGraph.pointerListenerAdd(dialog, \"enter\", function(e) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n var selInDia = dialog.querySelectorAll(\"select\");\n if (selInDia) {\n selInDia.forEach(function(selIn) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n });\n }\n if (that2.prompt_box) {\n that2.prompt_box.close();\n }\n that2.prompt_box = dialog;\n var name_element = dialog.querySelector(\".name\");\n name_element.innerText = title;\n var value_element = dialog.querySelector(\".value\");\n value_element.value = value;\n value_element.select();\n var input = value_element;\n input.addEventListener(\"keydown\", function(e) {\n dialog.is_modified = true;\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13 && e.target.localName != \"textarea\") {\n if (callback) {\n callback(this.value);\n }\n dialog.close();\n } else {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", function(e) {\n if (callback) {\n callback(input.value);\n }\n that2.setDirty(true);\n dialog.close();\n });\n var rect = canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (event2) {\n dialog.style.left = event2.clientX + offsetx + \"px\";\n dialog.style.top = event2.clientY + offsety + \"px\";\n } else {\n dialog.style.left = canvas.width * 0.5 + offsetx + \"px\";\n dialog.style.top = canvas.height * 0.5 + offsety + \"px\";\n }\n setTimeout(function() {\n input.focus();\n }, 10);\n return dialog;\n };\n LGraphCanvas.search_limit = -1;\n LGraphCanvas.prototype.showSearchBox = function(event2, options) {\n var def_options = {\n slot_from: null,\n node_from: null,\n node_to: null,\n do_type_filter: LiteGraph.search_filter_enabled,\n type_filter_in: false,\n type_filter_out: false,\n show_general_if_none_on_typefilter: true,\n show_general_after_typefiltered: true,\n hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave,\n show_all_if_empty: true,\n show_all_on_open: LiteGraph.search_show_all_on_open\n };\n options = Object.assign(def_options, options || {});\n var that2 = this;\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n var root_document = canvas.ownerDocument || document;\n var dialog = document.createElement(\"div\");\n dialog.className = \"litegraph litesearchbox graphdialog rounded\";\n dialog.innerHTML = \"Search \";\n if (options.do_type_filter) {\n dialog.innerHTML += \"\";\n dialog.innerHTML += \"\";\n }\n dialog.innerHTML += \"
\";\n if (root_document.fullscreenElement)\n root_document.fullscreenElement.appendChild(dialog);\n else {\n root_document.body.appendChild(dialog);\n root_document.body.style.overflow = \"hidden\";\n }\n if (options.do_type_filter) {\n var selIn = dialog.querySelector(\".slot_in_type_filter\");\n var selOut = dialog.querySelector(\".slot_out_type_filter\");\n }\n dialog.close = function() {\n that2.search_box = null;\n this.blur();\n canvas.focus();\n root_document.body.style.overflow = \"\";\n setTimeout(function() {\n that2.canvas.focus();\n }, 20);\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n if (this.ds.scale > 1) {\n dialog.style.transform = \"scale(\" + this.ds.scale + \")\";\n }\n if (options.hide_on_mouse_leave) {\n var prevent_timeout = false;\n var timeout_close = null;\n LiteGraph.pointerListenerAdd(dialog, \"enter\", function(e) {\n if (timeout_close) {\n clearTimeout(timeout_close);\n timeout_close = null;\n }\n });\n LiteGraph.pointerListenerAdd(dialog, \"leave\", function(e) {\n if (prevent_timeout) {\n return;\n }\n timeout_close = setTimeout(function() {\n dialog.close();\n }, typeof options.hide_on_mouse_leave === \"number\" ? options.hide_on_mouse_leave : 500);\n });\n if (options.do_type_filter) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n selOut.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selOut.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selOut.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n }\n }\n if (that2.search_box) {\n that2.search_box.close();\n }\n that2.search_box = dialog;\n var helper = dialog.querySelector(\".helper\");\n var first = null;\n var timeout = null;\n var selected = null;\n var input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"blur\", function(e) {\n this.focus();\n });\n input.addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 38) {\n changeSelection(false);\n } else if (e.keyCode == 40) {\n changeSelection(true);\n } else if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13) {\n if (selected) {\n select(unescape(selected.dataset[\"type\"]));\n } else if (first) {\n select(first);\n } else {\n dialog.close();\n }\n } else {\n if (timeout) {\n clearInterval(timeout);\n }\n timeout = setTimeout(refreshHelper, 10);\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n return true;\n });\n }\n if (options.do_type_filter) {\n if (selIn) {\n var aSlots = LiteGraph.slot_types_in;\n var nSlots = aSlots.length;\n if (options.type_filter_in == LiteGraph.EVENT || options.type_filter_in == LiteGraph.ACTION)\n options.type_filter_in = \"_event_\";\n for (var iK = 0; iK < nSlots; iK++) {\n var opt = document.createElement(\"option\");\n opt.value = aSlots[iK];\n opt.innerHTML = aSlots[iK];\n selIn.appendChild(opt);\n if (options.type_filter_in !== false && (options.type_filter_in + \"\").toLowerCase() == (aSlots[iK] + \"\").toLowerCase()) {\n opt.selected = true;\n }\n }\n selIn.addEventListener(\"change\", function() {\n refreshHelper();\n });\n }\n if (selOut) {\n var aSlots = LiteGraph.slot_types_out;\n var nSlots = aSlots.length;\n if (options.type_filter_out == LiteGraph.EVENT || options.type_filter_out == LiteGraph.ACTION)\n options.type_filter_out = \"_event_\";\n for (var iK = 0; iK < nSlots; iK++) {\n var opt = document.createElement(\"option\");\n opt.value = aSlots[iK];\n opt.innerHTML = aSlots[iK];\n selOut.appendChild(opt);\n if (options.type_filter_out !== false && (options.type_filter_out + \"\").toLowerCase() == (aSlots[iK] + \"\").toLowerCase()) {\n opt.selected = true;\n }\n }\n selOut.addEventListener(\"change\", function() {\n refreshHelper();\n });\n }\n }\n var rect = canvas.getBoundingClientRect();\n var left = (event2 ? event2.clientX : rect.left + rect.width * 0.5) - 80;\n var top = (event2 ? event2.clientY : rect.top + rect.height * 0.5) - 20;\n dialog.style.left = left + \"px\";\n dialog.style.top = top + \"px\";\n if (event2.layerY > rect.height - 200)\n helper.style.maxHeight = rect.height - event2.layerY - 20 + \"px\";\n input.focus();\n if (options.show_all_on_open) refreshHelper();\n function select(name) {\n if (name) {\n if (that2.onSearchBoxSelection) {\n that2.onSearchBoxSelection(name, event2, graphcanvas);\n } else {\n var extra = LiteGraph.searchbox_extras[name.toLowerCase()];\n if (extra) {\n name = extra.type;\n }\n graphcanvas.graph.beforeChange();\n var node2 = LiteGraph.createNode(name);\n if (node2) {\n node2.pos = graphcanvas.convertEventToCanvasOffset(\n event2\n );\n graphcanvas.graph.add(node2, false);\n }\n if (extra && extra.data) {\n if (extra.data.properties) {\n for (var i2 in extra.data.properties) {\n node2.addProperty(i2, extra.data.properties[i2]);\n }\n }\n if (extra.data.inputs) {\n node2.inputs = [];\n for (var i2 in extra.data.inputs) {\n node2.addOutput(\n extra.data.inputs[i2][0],\n extra.data.inputs[i2][1]\n );\n }\n }\n if (extra.data.outputs) {\n node2.outputs = [];\n for (var i2 in extra.data.outputs) {\n node2.addOutput(\n extra.data.outputs[i2][0],\n extra.data.outputs[i2][1]\n );\n }\n }\n if (extra.data.title) {\n node2.title = extra.data.title;\n }\n if (extra.data.json) {\n node2.configure(extra.data.json);\n }\n }\n if (options.node_from) {\n var iS = false;\n switch (typeof options.slot_from) {\n case \"string\":\n iS = options.node_from.findOutputSlot(options.slot_from);\n break;\n case \"object\":\n if (options.slot_from.name) {\n iS = options.node_from.findOutputSlot(options.slot_from.name);\n } else {\n iS = -1;\n }\n if (iS == -1 && typeof options.slot_from.slot_index !== \"undefined\") iS = options.slot_from.slot_index;\n break;\n case \"number\":\n iS = options.slot_from;\n break;\n default:\n iS = 0;\n }\n if (typeof options.node_from.outputs[iS] !== \"undefined\") {\n if (iS !== false && iS > -1) {\n options.node_from.connectByType(iS, node2, options.node_from.outputs[iS].type);\n }\n }\n }\n if (options.node_to) {\n var iS = false;\n switch (typeof options.slot_from) {\n case \"string\":\n iS = options.node_to.findInputSlot(options.slot_from);\n break;\n case \"object\":\n if (options.slot_from.name) {\n iS = options.node_to.findInputSlot(options.slot_from.name);\n } else {\n iS = -1;\n }\n if (iS == -1 && typeof options.slot_from.slot_index !== \"undefined\") iS = options.slot_from.slot_index;\n break;\n case \"number\":\n iS = options.slot_from;\n break;\n default:\n iS = 0;\n }\n if (typeof options.node_to.inputs[iS] !== \"undefined\") {\n if (iS !== false && iS > -1) {\n options.node_to.connectByTypeOutput(iS, node2, options.node_to.inputs[iS].type);\n }\n }\n }\n graphcanvas.graph.afterChange();\n }\n }\n dialog.close();\n }\n function changeSelection(forward) {\n var prev = selected;\n if (selected) {\n selected.classList.remove(\"selected\");\n }\n if (!selected) {\n selected = forward ? helper.childNodes[0] : helper.childNodes[helper.childNodes.length];\n } else {\n selected = forward ? selected.nextSibling : selected.previousSibling;\n if (!selected) {\n selected = prev;\n }\n }\n if (!selected) {\n return;\n }\n selected.classList.add(\"selected\");\n selected.scrollIntoView({ block: \"end\", behavior: \"smooth\" });\n }\n function refreshHelper() {\n timeout = null;\n var str = input.value;\n first = null;\n helper.innerHTML = \"\";\n if (!str && !options.show_all_if_empty) {\n return;\n }\n if (that2.onSearchBox) {\n var list = that2.onSearchBox(helper, str, graphcanvas);\n if (list) {\n for (var i2 = 0; i2 < list.length; ++i2) {\n addResult(list[i2]);\n }\n }\n } else {\n let inner_test_filter = function(type, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n skipFilter: false,\n inTypeOverride: false,\n outTypeOverride: false\n };\n var opts = Object.assign(optsDef, optsIn);\n var ctor2 = LiteGraph.registered_node_types[type];\n if (filter && ctor2.filter != filter)\n return false;\n if ((!options.show_all_if_empty || str) && type.toLowerCase().indexOf(str) === -1 && (!ctor2.title || ctor2.title.toLowerCase().indexOf(str) === -1))\n return false;\n if (options.do_type_filter && !opts.skipFilter) {\n var sType = type;\n var sV = sIn.value;\n if (opts.inTypeOverride !== false) sV = opts.inTypeOverride;\n if (sIn && sV) {\n if (LiteGraph.registered_slot_in_types[sV] && LiteGraph.registered_slot_in_types[sV].nodes) {\n var doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType);\n if (doesInc !== false) ;\n else {\n return false;\n }\n }\n }\n var sV = sOut.value;\n if (opts.outTypeOverride !== false) sV = opts.outTypeOverride;\n if (sOut && sV) {\n if (LiteGraph.registered_slot_out_types[sV] && LiteGraph.registered_slot_out_types[sV].nodes) {\n var doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType);\n if (doesInc !== false) ;\n else {\n return false;\n }\n }\n }\n }\n return true;\n };\n var c = 0;\n str = str.toLowerCase();\n var filter = graphcanvas.filter || graphcanvas.graph.filter;\n if (options.do_type_filter && that2.search_box) {\n var sIn = that2.search_box.querySelector(\".slot_in_type_filter\");\n var sOut = that2.search_box.querySelector(\".slot_out_type_filter\");\n } else {\n var sIn = false;\n var sOut = false;\n }\n for (var i2 in LiteGraph.searchbox_extras) {\n var extra = LiteGraph.searchbox_extras[i2];\n if ((!options.show_all_if_empty || str) && extra.desc.toLowerCase().indexOf(str) === -1) {\n continue;\n }\n var ctor = LiteGraph.registered_node_types[extra.type];\n if (ctor && ctor.filter != filter)\n continue;\n if (!inner_test_filter(extra.type))\n continue;\n addResult(extra.desc, \"searchbox_extra\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n var filtered = null;\n if (Array.prototype.filter) {\n var keys = Object.keys(LiteGraph.registered_node_types);\n var filtered = keys.filter(inner_test_filter);\n } else {\n filtered = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2))\n filtered.push(i2);\n }\n }\n for (var i2 = 0; i2 < filtered.length; i2++) {\n addResult(filtered[i2]);\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n if (options.show_general_after_typefiltered && (sIn.value || sOut.value)) {\n filtered_extra = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2, { inTypeOverride: sIn && sIn.value ? \"*\" : false, outTypeOverride: sOut && sOut.value ? \"*\" : false }))\n filtered_extra.push(i2);\n }\n for (var i2 = 0; i2 < filtered_extra.length; i2++) {\n addResult(filtered_extra[i2], \"generic_type\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n }\n if ((sIn.value || sOut.value) && (helper.childNodes.length == 0 && options.show_general_if_none_on_typefilter)) {\n filtered_extra = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2, { skipFilter: true }))\n filtered_extra.push(i2);\n }\n for (var i2 = 0; i2 < filtered_extra.length; i2++) {\n addResult(filtered_extra[i2], \"not_in_filter\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n }\n }\n function addResult(type, className) {\n var help = document.createElement(\"div\");\n if (!first) {\n first = type;\n }\n const nodeType = LiteGraph.registered_node_types[type];\n if (nodeType == null ? void 0 : nodeType.title) {\n help.innerText = nodeType == null ? void 0 : nodeType.title;\n const typeEl = document.createElement(\"span\");\n typeEl.className = \"litegraph lite-search-item-type\";\n typeEl.textContent = type;\n help.append(typeEl);\n } else {\n help.innerText = type;\n }\n help.dataset[\"type\"] = escape(type);\n help.className = \"litegraph lite-search-item\";\n if (className) {\n help.className += \" \" + className;\n }\n help.addEventListener(\"click\", function(e) {\n select(unescape(this.dataset[\"type\"]));\n });\n helper.appendChild(help);\n }\n }\n return dialog;\n };\n LGraphCanvas.prototype.showEditPropertyValue = function(node2, property, options) {\n if (!node2 || node2.properties[property] === void 0) {\n return;\n }\n options = options || {};\n var info = node2.getPropertyInfo(property);\n var type = info.type;\n var input_html = \"\";\n if (type == \"string\" || type == \"number\" || type == \"array\" || type == \"object\") {\n input_html = \"\";\n } else if ((type == \"enum\" || type == \"combo\") && info.values) {\n input_html = \"\";\n } else if (type == \"boolean\" || type == \"toggle\") {\n input_html = \"\";\n } else {\n console.warn(\"unknown type: \" + type);\n return;\n }\n var dialog = this.createDialog(\n \"\" + (info.label ? info.label : property) + \"\" + input_html + \"\",\n options\n );\n var input = false;\n if ((type == \"enum\" || type == \"combo\") && info.values) {\n input = dialog.querySelector(\"select\");\n input.addEventListener(\"change\", function(e) {\n dialog.modified();\n setValue(e.target.value);\n });\n } else if (type == \"boolean\" || type == \"toggle\") {\n input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"click\", function(e) {\n dialog.modified();\n setValue(!!input.checked);\n });\n }\n } else {\n input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"blur\", function(e) {\n this.focus();\n });\n var v2 = node2.properties[property] !== void 0 ? node2.properties[property] : \"\";\n if (type !== \"string\") {\n v2 = JSON.stringify(v2);\n }\n input.value = v2;\n input.addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13) {\n inner();\n } else if (e.keyCode != 13) {\n dialog.modified();\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n }\n }\n if (input) input.focus();\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", inner);\n function inner() {\n setValue(input.value);\n }\n function setValue(value) {\n if (info && info.values && info.values.constructor === Object && info.values[value] != void 0)\n value = info.values[value];\n if (typeof node2.properties[property] == \"number\") {\n value = Number(value);\n }\n if (type == \"array\" || type == \"object\") {\n value = JSON.parse(value);\n }\n node2.properties[property] = value;\n if (node2.graph) {\n node2.graph._version++;\n }\n if (node2.onPropertyChanged) {\n node2.onPropertyChanged(property, value);\n }\n if (options.onclose)\n options.onclose();\n dialog.close();\n node2.setDirtyCanvas(true, true);\n }\n return dialog;\n };\n LGraphCanvas.prototype.createDialog = function(html, options) {\n var def_options = { checkForInput: false, closeOnLeave: true, closeOnLeave_checkModified: true };\n options = Object.assign(def_options, options || {});\n var dialog = document.createElement(\"div\");\n dialog.className = \"graphdialog\";\n dialog.innerHTML = html;\n dialog.is_modified = false;\n var rect = this.canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (options.position) {\n offsetx += options.position[0];\n offsety += options.position[1];\n } else if (options.event) {\n offsetx += options.event.clientX;\n offsety += options.event.clientY;\n } else {\n offsetx += this.canvas.width * 0.5;\n offsety += this.canvas.height * 0.5;\n }\n dialog.style.left = offsetx + \"px\";\n dialog.style.top = offsety + \"px\";\n this.canvas.parentNode.appendChild(dialog);\n if (options.checkForInput) {\n var aI = [];\n var focused = false;\n if (aI = dialog.querySelectorAll(\"input\")) {\n aI.forEach(function(iX) {\n iX.addEventListener(\"keydown\", function(e) {\n dialog.modified();\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode != 13) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n if (!focused) iX.focus();\n });\n }\n }\n dialog.modified = function() {\n dialog.is_modified = true;\n };\n dialog.close = function() {\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var dialogCloseTimer = null;\n var prevent_timeout = false;\n dialog.addEventListener(\"mouseleave\", function(e) {\n if (prevent_timeout)\n return;\n if (options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n dialog.addEventListener(\"mouseenter\", function(e) {\n if (options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n var selInDia = dialog.querySelectorAll(\"select\");\n if (selInDia) {\n selInDia.forEach(function(selIn) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n });\n }\n return dialog;\n };\n LGraphCanvas.prototype.createPanel = function(title, options) {\n options = options || {};\n var ref_window2 = options.window || window;\n var root = document.createElement(\"div\");\n root.className = \"litegraph dialog\";\n root.innerHTML = \"
\";\n root.header = root.querySelector(\".dialog-header\");\n if (options.width)\n root.style.width = options.width + (options.width.constructor === Number ? \"px\" : \"\");\n if (options.height)\n root.style.height = options.height + (options.height.constructor === Number ? \"px\" : \"\");\n if (options.closable) {\n var close = document.createElement(\"span\");\n close.innerHTML = \"✕\";\n close.classList.add(\"close\");\n close.addEventListener(\"click\", function() {\n root.close();\n });\n root.header.appendChild(close);\n }\n root.title_element = root.querySelector(\".dialog-title\");\n root.title_element.innerText = title;\n root.content = root.querySelector(\".dialog-content\");\n root.alt_content = root.querySelector(\".dialog-alt-content\");\n root.footer = root.querySelector(\".dialog-footer\");\n root.close = function() {\n if (root.onClose && typeof root.onClose == \"function\") {\n root.onClose();\n }\n if (root.parentNode)\n root.parentNode.removeChild(root);\n if (this.parentNode) {\n this.parentNode.removeChild(this);\n }\n };\n root.toggleAltContent = function(force) {\n if (typeof force != \"undefined\") {\n var vTo = force ? \"block\" : \"none\";\n var vAlt = force ? \"none\" : \"block\";\n } else {\n var vTo = root.alt_content.style.display != \"block\" ? \"block\" : \"none\";\n var vAlt = root.alt_content.style.display != \"block\" ? \"none\" : \"block\";\n }\n root.alt_content.style.display = vTo;\n root.content.style.display = vAlt;\n };\n root.toggleFooterVisibility = function(force) {\n if (typeof force != \"undefined\") {\n var vTo = force ? \"block\" : \"none\";\n } else {\n var vTo = root.footer.style.display != \"block\" ? \"block\" : \"none\";\n }\n root.footer.style.display = vTo;\n };\n root.clear = function() {\n this.content.innerHTML = \"\";\n };\n root.addHTML = function(code, classname, on_footer) {\n var elem = document.createElement(\"div\");\n if (classname)\n elem.className = classname;\n elem.innerHTML = code;\n if (on_footer)\n root.footer.appendChild(elem);\n else\n root.content.appendChild(elem);\n return elem;\n };\n root.addButton = function(name, callback, options2) {\n var elem = document.createElement(\"button\");\n elem.innerText = name;\n elem.options = options2;\n elem.classList.add(\"btn\");\n elem.addEventListener(\"click\", callback);\n root.footer.appendChild(elem);\n return elem;\n };\n root.addSeparator = function() {\n var elem = document.createElement(\"div\");\n elem.className = \"separator\";\n root.content.appendChild(elem);\n };\n root.addWidget = function(type, name, value, options2, callback) {\n options2 = options2 || {};\n var str_value = String(value);\n type = type.toLowerCase();\n if (type == \"number\")\n str_value = value.toFixed(3);\n var elem = document.createElement(\"div\");\n elem.className = \"property\";\n elem.innerHTML = \"\";\n elem.querySelector(\".property_name\").innerText = options2.label || name;\n var value_element = elem.querySelector(\".property_value\");\n value_element.innerText = str_value;\n elem.dataset[\"property\"] = name;\n elem.dataset[\"type\"] = options2.type || type;\n elem.options = options2;\n elem.value = value;\n if (type == \"code\")\n elem.addEventListener(\"click\", function(e) {\n root.inner_showCodePad(this.dataset[\"property\"]);\n });\n else if (type == \"boolean\") {\n elem.classList.add(\"boolean\");\n if (value)\n elem.classList.add(\"bool-on\");\n elem.addEventListener(\"click\", function() {\n var propname = this.dataset[\"property\"];\n this.value = !this.value;\n this.classList.toggle(\"bool-on\");\n this.querySelector(\".property_value\").innerText = this.value ? \"true\" : \"false\";\n innerChange(propname, this.value);\n });\n } else if (type == \"string\" || type == \"number\") {\n value_element.setAttribute(\"contenteditable\", true);\n value_element.addEventListener(\"keydown\", function(e) {\n if (e.code == \"Enter\" && (type != \"string\" || !e.shiftKey)) {\n e.preventDefault();\n this.blur();\n }\n });\n value_element.addEventListener(\"blur\", function() {\n var v2 = this.innerText;\n var propname = this.parentNode.dataset[\"property\"];\n var proptype = this.parentNode.dataset[\"type\"];\n if (proptype == \"number\")\n v2 = Number(v2);\n innerChange(propname, v2);\n });\n } else if (type == \"enum\" || type == \"combo\") {\n var str_value = LGraphCanvas.getPropertyPrintableValue(value, options2.values);\n value_element.innerText = str_value;\n value_element.addEventListener(\"click\", function(event2) {\n var values2 = options2.values || [];\n var propname = this.parentNode.dataset[\"property\"];\n var elem_that = this;\n new LiteGraph.ContextMenu(\n values2,\n {\n event: event2,\n className: \"dark\",\n callback: inner_clicked\n },\n ref_window2\n );\n function inner_clicked(v2, option, event3) {\n elem_that.innerText = v2;\n innerChange(propname, v2);\n return false;\n }\n });\n }\n root.content.appendChild(elem);\n function innerChange(name2, value2) {\n if (options2.callback)\n options2.callback(name2, value2, options2);\n if (callback)\n callback(name2, value2, options2);\n }\n return elem;\n };\n if (root.onOpen && typeof root.onOpen == \"function\") root.onOpen();\n return root;\n };\n LGraphCanvas.getPropertyPrintableValue = function(value, values2) {\n if (!values2)\n return String(value);\n if (values2.constructor === Array) {\n return String(value);\n }\n if (values2.constructor === Object) {\n var desc_value = \"\";\n for (var k in values2) {\n if (values2[k] != value)\n continue;\n desc_value = k;\n break;\n }\n return String(value) + \" (\" + desc_value + \")\";\n }\n };\n LGraphCanvas.prototype.closePanels = function() {\n var panel2 = document.querySelector(\"#node-panel\");\n if (panel2)\n panel2.close();\n var panel2 = document.querySelector(\"#option-panel\");\n if (panel2)\n panel2.close();\n };\n LGraphCanvas.prototype.showShowGraphOptionsPanel = function(refOpts, obEv, refMenu, refMenu2) {\n if (this.constructor && this.constructor.name == \"HTMLDivElement\") {\n if (!obEv || !obEv.event || !obEv.event.target || !obEv.event.target.lgraphcanvas) {\n console.warn(\"Canvas not found\");\n return;\n }\n var graphcanvas = obEv.event.target.lgraphcanvas;\n } else {\n var graphcanvas = this;\n }\n graphcanvas.closePanels();\n var ref_window2 = graphcanvas.getCanvasWindow();\n panel = graphcanvas.createPanel(\"Options\", {\n closable: true,\n window: ref_window2,\n onOpen: function() {\n graphcanvas.OPTIONPANEL_IS_OPEN = true;\n },\n onClose: function() {\n graphcanvas.OPTIONPANEL_IS_OPEN = false;\n graphcanvas.options_panel = null;\n }\n });\n graphcanvas.options_panel = panel;\n panel.id = \"option-panel\";\n panel.classList.add(\"settings\");\n function inner_refresh() {\n panel.content.innerHTML = \"\";\n var fUpdate = function(name, value, options) {\n switch (name) {\n default:\n if (options && options.key) {\n name = options.key;\n }\n if (options.values) {\n value = Object.values(options.values).indexOf(value);\n }\n graphcanvas[name] = value;\n break;\n }\n };\n var aProps = LiteGraph.availableCanvasOptions;\n aProps.sort();\n for (var pI in aProps) {\n var pX = aProps[pI];\n panel.addWidget(\"boolean\", pX, graphcanvas[pX], { key: pX, on: \"True\", off: \"False\" }, fUpdate);\n }\n [graphcanvas.links_render_mode];\n panel.addWidget(\"combo\", \"Render mode\", LiteGraph.LINK_RENDER_MODES[graphcanvas.links_render_mode], { key: \"links_render_mode\", values: LiteGraph.LINK_RENDER_MODES }, fUpdate);\n panel.addSeparator();\n panel.footer.innerHTML = \"\";\n }\n inner_refresh();\n graphcanvas.canvas.parentNode.appendChild(panel);\n };\n LGraphCanvas.prototype.showShowNodePanel = function(node2) {\n this.SELECTED_NODE = node2;\n this.closePanels();\n var ref_window2 = this.getCanvasWindow();\n var graphcanvas = this;\n var panel2 = this.createPanel(node2.title || \"\", {\n closable: true,\n window: ref_window2,\n onOpen: function() {\n graphcanvas.NODEPANEL_IS_OPEN = true;\n },\n onClose: function() {\n graphcanvas.NODEPANEL_IS_OPEN = false;\n graphcanvas.node_panel = null;\n }\n });\n graphcanvas.node_panel = panel2;\n panel2.id = \"node-panel\";\n panel2.node = node2;\n panel2.classList.add(\"settings\");\n function inner_refresh() {\n panel2.content.innerHTML = \"\";\n panel2.addHTML(\"\" + node2.type + \"\" + (node2.constructor.desc || \"\") + \"\");\n panel2.addHTML(\"

Properties

\");\n var fUpdate = function(name, value2) {\n graphcanvas.graph.beforeChange(node2);\n switch (name) {\n case \"Title\":\n node2.title = value2;\n break;\n case \"Mode\":\n var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value2);\n if (kV >= 0 && LiteGraph.NODE_MODES[kV]) {\n node2.changeMode(kV);\n } else {\n console.warn(\"unexpected mode: \" + value2);\n }\n break;\n case \"Color\":\n if (LGraphCanvas.node_colors[value2]) {\n node2.color = LGraphCanvas.node_colors[value2].color;\n node2.bgcolor = LGraphCanvas.node_colors[value2].bgcolor;\n } else {\n console.warn(\"unexpected color: \" + value2);\n }\n break;\n default:\n node2.setProperty(name, value2);\n break;\n }\n graphcanvas.graph.afterChange();\n graphcanvas.dirty_canvas = true;\n };\n panel2.addWidget(\"string\", \"Title\", node2.title, {}, fUpdate);\n panel2.addWidget(\"combo\", \"Mode\", LiteGraph.NODE_MODES[node2.mode], { values: LiteGraph.NODE_MODES }, fUpdate);\n var nodeCol = \"\";\n if (node2.color !== void 0) {\n nodeCol = Object.keys(LGraphCanvas.node_colors).filter(function(nK) {\n return LGraphCanvas.node_colors[nK].color == node2.color;\n });\n }\n panel2.addWidget(\"combo\", \"Color\", nodeCol, { values: Object.keys(LGraphCanvas.node_colors) }, fUpdate);\n for (var pName in node2.properties) {\n var value = node2.properties[pName];\n var info = node2.getPropertyInfo(pName);\n info.type || \"string\";\n if (node2.onAddPropertyToPanel && node2.onAddPropertyToPanel(pName, panel2))\n continue;\n panel2.addWidget(info.widget || info.type, pName, value, info, fUpdate);\n }\n panel2.addSeparator();\n if (node2.onShowCustomPanelInfo)\n node2.onShowCustomPanelInfo(panel2);\n panel2.footer.innerHTML = \"\";\n panel2.addButton(\"Delete\", function() {\n if (node2.block_delete)\n return;\n node2.graph.remove(node2);\n panel2.close();\n }).classList.add(\"delete\");\n }\n panel2.inner_showCodePad = function(propname) {\n panel2.classList.remove(\"settings\");\n panel2.classList.add(\"centered\");\n panel2.alt_content.innerHTML = \"\";\n var textarea = panel2.alt_content.querySelector(\"textarea\");\n var fDoneWith = function() {\n panel2.toggleAltContent(false);\n panel2.toggleFooterVisibility(true);\n textarea.parentNode.removeChild(textarea);\n panel2.classList.add(\"settings\");\n panel2.classList.remove(\"centered\");\n inner_refresh();\n };\n textarea.value = node2.properties[propname];\n textarea.addEventListener(\"keydown\", function(e) {\n if (e.code == \"Enter\" && e.ctrlKey) {\n node2.setProperty(propname, textarea.value);\n fDoneWith();\n }\n });\n panel2.toggleAltContent(true);\n panel2.toggleFooterVisibility(false);\n textarea.style.height = \"calc(100% - 40px)\";\n var assign = panel2.addButton(\"Assign\", function() {\n node2.setProperty(propname, textarea.value);\n fDoneWith();\n });\n panel2.alt_content.appendChild(assign);\n var button = panel2.addButton(\"Close\", fDoneWith);\n button.style.float = \"right\";\n panel2.alt_content.appendChild(button);\n };\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n };\n LGraphCanvas.prototype.showSubgraphPropertiesDialog = function(node2) {\n console.log(\"showing subgraph properties dialog\");\n var old_panel = this.canvas.parentNode.querySelector(\".subgraph_dialog\");\n if (old_panel)\n old_panel.close();\n var panel2 = this.createPanel(\"Subgraph Inputs\", { closable: true, width: 500 });\n panel2.node = node2;\n panel2.classList.add(\"subgraph_dialog\");\n function inner_refresh() {\n panel2.clear();\n if (node2.inputs)\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n var input = node2.inputs[i2];\n if (input.not_subgraph_input)\n continue;\n var html2 = \" \";\n var elem2 = panel2.addHTML(html2, \"subgraph_property\");\n elem2.dataset[\"name\"] = input.name;\n elem2.dataset[\"slot\"] = i2;\n elem2.querySelector(\".name\").innerText = input.name;\n elem2.querySelector(\".type\").innerText = input.type;\n elem2.querySelector(\"button\").addEventListener(\"click\", function(e) {\n node2.removeInput(Number(this.parentNode.dataset[\"slot\"]));\n inner_refresh();\n });\n }\n }\n var html = \" + NameType\";\n var elem = panel2.addHTML(html, \"subgraph_property extra\", true);\n elem.querySelector(\"button\").addEventListener(\"click\", function(e) {\n var elem2 = this.parentNode;\n var name = elem2.querySelector(\".name\").value;\n var type = elem2.querySelector(\".type\").value;\n if (!name || node2.findInputSlot(name) != -1)\n return;\n node2.addInput(name, type);\n elem2.querySelector(\".name\").value = \"\";\n elem2.querySelector(\".type\").value = \"\";\n inner_refresh();\n });\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n return panel2;\n };\n LGraphCanvas.prototype.showSubgraphPropertiesDialogRight = function(node2) {\n var old_panel = this.canvas.parentNode.querySelector(\".subgraph_dialog\");\n if (old_panel)\n old_panel.close();\n var panel2 = this.createPanel(\"Subgraph Outputs\", { closable: true, width: 500 });\n panel2.node = node2;\n panel2.classList.add(\"subgraph_dialog\");\n function inner_refresh() {\n panel2.clear();\n if (node2.outputs)\n for (var i2 = 0; i2 < node2.outputs.length; ++i2) {\n var input = node2.outputs[i2];\n if (input.not_subgraph_output)\n continue;\n var html2 = \" \";\n var elem2 = panel2.addHTML(html2, \"subgraph_property\");\n elem2.dataset[\"name\"] = input.name;\n elem2.dataset[\"slot\"] = i2;\n elem2.querySelector(\".name\").innerText = input.name;\n elem2.querySelector(\".type\").innerText = input.type;\n elem2.querySelector(\"button\").addEventListener(\"click\", function(e) {\n node2.removeOutput(Number(this.parentNode.dataset[\"slot\"]));\n inner_refresh();\n });\n }\n }\n var html = \" + NameType\";\n var elem = panel2.addHTML(html, \"subgraph_property extra\", true);\n elem.querySelector(\".name\").addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 13) {\n addOutput.apply(this);\n }\n });\n elem.querySelector(\"button\").addEventListener(\"click\", function(e) {\n addOutput.apply(this);\n });\n function addOutput() {\n var elem2 = this.parentNode;\n var name = elem2.querySelector(\".name\").value;\n var type = elem2.querySelector(\".type\").value;\n if (!name || node2.findOutputSlot(name) != -1)\n return;\n node2.addOutput(name, type);\n elem2.querySelector(\".name\").value = \"\";\n elem2.querySelector(\".type\").value = \"\";\n inner_refresh();\n }\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n return panel2;\n };\n LGraphCanvas.prototype.checkPanels = function() {\n if (!this.canvas)\n return;\n var panels = this.canvas.parentNode.querySelectorAll(\".litegraph.dialog\");\n for (var i2 = 0; i2 < panels.length; ++i2) {\n var panel2 = panels[i2];\n if (!panel2.node)\n continue;\n if (!panel2.node.graph || panel2.graph != this.graph)\n panel2.close();\n }\n };\n LGraphCanvas.onMenuNodeCollapse = function(value, options, e, menu, node2) {\n node2.graph.beforeChange(\n /*?*/\n );\n var fApplyMultiNode = function(node3) {\n node3.collapse();\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.graph.afterChange(\n /*?*/\n );\n };\n LGraphCanvas.onMenuNodePin = function(value, options, e, menu, node2) {\n node2.pin();\n };\n LGraphCanvas.onMenuNodeMode = function(value, options, e, menu, node2) {\n new LiteGraph.ContextMenu(\n LiteGraph.NODE_MODES,\n { event: e, callback: inner_clicked, parentMenu: menu, node: node2 }\n );\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n var kV = Object.values(LiteGraph.NODE_MODES).indexOf(v2);\n var fApplyMultiNode = function(node3) {\n if (kV >= 0 && LiteGraph.NODE_MODES[kV])\n node3.changeMode(kV);\n else {\n console.warn(\"unexpected mode: \" + v2);\n node3.changeMode(LiteGraph.ALWAYS);\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n }\n return false;\n };\n LGraphCanvas.onMenuNodeColors = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node for color\";\n }\n var values2 = [];\n values2.push({\n value: null,\n content: \"No color\"\n });\n for (var i2 in LGraphCanvas.node_colors) {\n var color = LGraphCanvas.node_colors[i2];\n var value = {\n value: i2,\n content: \"\" + i2 + \"\"\n };\n values2.push(value);\n }\n new LiteGraph.ContextMenu(values2, {\n event: e,\n callback: inner_clicked,\n parentMenu: menu,\n node: node2\n });\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n var color2 = v2.value ? LGraphCanvas.node_colors[v2.value] : null;\n var fApplyColor = function(node3) {\n if (color2) {\n if (node3.constructor === LiteGraph.LGraphGroup) {\n node3.color = color2.groupcolor;\n } else {\n node3.color = color2.color;\n node3.bgcolor = color2.bgcolor;\n }\n } else {\n delete node3.color;\n delete node3.bgcolor;\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyColor(node2);\n } else {\n for (var i3 in graphcanvas.selected_nodes) {\n fApplyColor(graphcanvas.selected_nodes[i3]);\n }\n }\n node2.setDirtyCanvas(true, true);\n }\n return false;\n };\n LGraphCanvas.onMenuNodeShapes = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node passed\";\n }\n new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, {\n event: e,\n callback: inner_clicked,\n parentMenu: menu,\n node: node2\n });\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n node2.graph.beforeChange(\n /*?*/\n );\n var fApplyMultiNode = function(node3) {\n node3.shape = v2;\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.graph.afterChange(\n /*?*/\n );\n node2.setDirtyCanvas(true);\n }\n return false;\n };\n LGraphCanvas.onMenuNodeRemove = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node passed\";\n }\n var graph = node2.graph;\n graph.beforeChange();\n var fApplyMultiNode = function(node3) {\n if (node3.removable === false) {\n return;\n }\n graph.remove(node3);\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n graph.afterChange();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.onMenuNodeToSubgraph = function(value, options, e, menu, node2) {\n var graph = node2.graph;\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas)\n return;\n var nodes_list = Object.values(graphcanvas.selected_nodes || {});\n if (!nodes_list.length)\n nodes_list = [node2];\n var subgraph_node = LiteGraph.createNode(\"graph/subgraph\");\n subgraph_node.pos = node2.pos.concat();\n graph.add(subgraph_node);\n subgraph_node.buildFromNodes(nodes_list);\n graphcanvas.deselectAllNodes();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.onMenuNodeClone = function(value, options, e, menu, node2) {\n node2.graph.beforeChange();\n var newSelected = {};\n var fApplyMultiNode = function(node3) {\n if (node3.clonable === false) {\n return;\n }\n var newnode = node3.clone();\n if (!newnode) {\n return;\n }\n newnode.pos = [node3.pos[0] + 5, node3.pos[1] + 5];\n node3.graph.add(newnode);\n newSelected[newnode.id] = newnode;\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n if (Object.keys(newSelected).length) {\n graphcanvas.selectNodes(newSelected);\n }\n node2.graph.afterChange();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.node_colors = {\n red: { color: \"#322\", bgcolor: \"#533\", groupcolor: \"#A88\" },\n brown: { color: \"#332922\", bgcolor: \"#593930\", groupcolor: \"#b06634\" },\n green: { color: \"#232\", bgcolor: \"#353\", groupcolor: \"#8A8\" },\n blue: { color: \"#223\", bgcolor: \"#335\", groupcolor: \"#88A\" },\n pale_blue: {\n color: \"#2a363b\",\n bgcolor: \"#3f5159\",\n groupcolor: \"#3f789e\"\n },\n cyan: { color: \"#233\", bgcolor: \"#355\", groupcolor: \"#8AA\" },\n purple: { color: \"#323\", bgcolor: \"#535\", groupcolor: \"#a1309b\" },\n yellow: { color: \"#432\", bgcolor: \"#653\", groupcolor: \"#b58b2a\" },\n black: { color: \"#222\", bgcolor: \"#000\", groupcolor: \"#444\" }\n };\n LGraphCanvas.prototype.getCanvasMenuOptions = function() {\n var options = null;\n if (this.getMenuOptions) {\n options = this.getMenuOptions();\n } else {\n options = [\n {\n content: \"Add Node\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuAdd\n },\n { content: \"Add Group\", callback: LGraphCanvas.onGroupAdd }\n //{ content: \"Arrange\", callback: that.graph.arrange },\n //{content:\"Collapse All\", callback: LGraphCanvas.onMenuCollapseAll }\n ];\n if (Object.keys(this.selected_nodes).length > 1) {\n options.push({\n content: \"Align\",\n has_submenu: true,\n callback: LGraphCanvas.onGroupAlign\n });\n }\n if (this._graph_stack && this._graph_stack.length > 0) {\n options.push(null, {\n content: \"Close subgraph\",\n callback: this.closeSubgraph.bind(this)\n });\n }\n }\n if (this.getExtraMenuOptions) {\n var extra = this.getExtraMenuOptions(this, options);\n if (extra) {\n options = options.concat(extra);\n }\n }\n return options;\n };\n LGraphCanvas.prototype.getNodeMenuOptions = function(node2) {\n var _a;\n var options = null;\n if (node2.getMenuOptions) {\n options = node2.getMenuOptions(this);\n } else {\n options = [\n {\n content: \"Inputs\",\n has_submenu: true,\n disabled: true,\n callback: LGraphCanvas.showMenuNodeOptionalInputs\n },\n {\n content: \"Outputs\",\n has_submenu: true,\n disabled: true,\n callback: LGraphCanvas.showMenuNodeOptionalOutputs\n },\n null,\n {\n content: \"Properties\",\n has_submenu: true,\n callback: LGraphCanvas.onShowMenuNodeProperties\n },\n {\n content: \"Properties Panel\",\n callback: function(item, options2, e, menu, node3) {\n LGraphCanvas.active_canvas.showShowNodePanel(node3);\n }\n },\n null,\n {\n content: \"Title\",\n callback: LGraphCanvas.onShowPropertyEditor\n },\n {\n content: \"Mode\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeMode\n }\n ];\n if (node2.resizable !== false) {\n options.push({\n content: \"Resize\",\n callback: LGraphCanvas.onMenuResizeNode\n });\n }\n options.push(\n {\n content: \"Collapse\",\n callback: LGraphCanvas.onMenuNodeCollapse\n },\n {\n content: ((_a = node2.flags) == null ? void 0 : _a.pinned) ? \"Unpin\" : \"Pin\",\n callback: LGraphCanvas.onMenuNodePin\n },\n {\n content: \"Colors\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeColors\n },\n {\n content: \"Shapes\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeShapes\n },\n null\n );\n }\n if (node2.onGetInputs) {\n var inputs = node2.onGetInputs();\n if (inputs && inputs.length) {\n options[0].disabled = false;\n }\n }\n if (node2.onGetOutputs) {\n var outputs = node2.onGetOutputs();\n if (outputs && outputs.length) {\n options[1].disabled = false;\n }\n }\n if (node2.getExtraMenuOptions) {\n var extra = node2.getExtraMenuOptions(this, options);\n if (extra) {\n extra.push(null);\n options = extra.concat(options);\n }\n }\n if (node2.clonable !== false) {\n options.push({\n content: \"Clone\",\n callback: LGraphCanvas.onMenuNodeClone\n });\n }\n if (Object.keys(this.selected_nodes).length > 1) {\n options.push({\n content: \"Align Selected To\",\n has_submenu: true,\n callback: LGraphCanvas.onNodeAlign\n });\n }\n options.push(null, {\n content: \"Remove\",\n disabled: !(node2.removable !== false && !node2.block_delete),\n callback: LGraphCanvas.onMenuNodeRemove\n });\n if (node2.graph && node2.graph.onGetNodeMenuOptions) {\n node2.graph.onGetNodeMenuOptions(options, node2);\n }\n return options;\n };\n LGraphCanvas.prototype.getGroupMenuOptions = function(node2) {\n var o = [\n { content: \"Title\", callback: LGraphCanvas.onShowPropertyEditor },\n {\n content: \"Color\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeColors\n },\n {\n content: \"Font size\",\n property: \"font_size\",\n type: \"Number\",\n callback: LGraphCanvas.onShowPropertyEditor\n },\n null,\n { content: \"Remove\", callback: LGraphCanvas.onMenuNodeRemove }\n ];\n return o;\n };\n LGraphCanvas.prototype.processContextMenu = function(node2, event2) {\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var menu_info = null;\n var options = {\n event: event2,\n callback: inner_option_clicked,\n extra: node2\n };\n if (node2)\n options.title = node2.type;\n var slot = null;\n if (node2) {\n slot = node2.getSlotInPosition(event2.canvasX, event2.canvasY);\n LGraphCanvas.active_node = node2;\n }\n if (slot) {\n menu_info = [];\n if (node2.getSlotMenuOptions) {\n menu_info = node2.getSlotMenuOptions(slot);\n } else {\n if (slot && slot.output && slot.output.links && slot.output.links.length) {\n menu_info.push({ content: \"Disconnect Links\", slot });\n }\n var _slot = slot.input || slot.output;\n if (_slot.removable) {\n menu_info.push(\n _slot.locked ? \"Cannot remove\" : { content: \"Remove Slot\", slot }\n );\n }\n if (!_slot.nameLocked) {\n menu_info.push({ content: \"Rename Slot\", slot });\n }\n }\n options.title = (slot.input ? slot.input.type : slot.output.type) || \"*\";\n if (slot.input && slot.input.type == LiteGraph.ACTION) {\n options.title = \"Action\";\n }\n if (slot.output && slot.output.type == LiteGraph.EVENT) {\n options.title = \"Event\";\n }\n } else {\n if (node2) {\n menu_info = this.getNodeMenuOptions(node2);\n } else {\n menu_info = this.getCanvasMenuOptions();\n var group = this.graph.getGroupOnPos(\n event2.canvasX,\n event2.canvasY\n );\n if (group) {\n menu_info.push(null, {\n content: \"Edit Group\",\n has_submenu: true,\n submenu: {\n title: \"Group\",\n extra: group,\n options: this.getGroupMenuOptions(group)\n }\n });\n }\n }\n }\n if (!menu_info) {\n return;\n }\n new LiteGraph.ContextMenu(menu_info, options, ref_window2);\n function inner_option_clicked(v2, options2, e) {\n if (!v2) {\n return;\n }\n if (v2.content == \"Remove Slot\") {\n var info = v2.slot;\n node2.graph.beforeChange();\n if (info.input) {\n node2.removeInput(info.slot);\n } else if (info.output) {\n node2.removeOutput(info.slot);\n }\n node2.graph.afterChange();\n return;\n } else if (v2.content == \"Disconnect Links\") {\n var info = v2.slot;\n node2.graph.beforeChange();\n if (info.output) {\n node2.disconnectOutput(info.slot);\n } else if (info.input) {\n node2.disconnectInput(info.slot);\n }\n node2.graph.afterChange();\n return;\n } else if (v2.content == \"Rename Slot\") {\n var info = v2.slot;\n var slot_info = info.input ? node2.getInputInfo(info.slot) : node2.getOutputInfo(info.slot);\n var dialog = that2.createDialog(\n \"Name\",\n options2\n );\n var input = dialog.querySelector(\"input\");\n if (input && slot_info) {\n input.value = slot_info.label || \"\";\n }\n var inner = function() {\n node2.graph.beforeChange();\n if (input.value) {\n if (slot_info) {\n slot_info.label = input.value;\n }\n that2.setDirty(true);\n }\n dialog.close();\n node2.graph.afterChange();\n };\n dialog.querySelector(\"button\").addEventListener(\"click\", inner);\n input.addEventListener(\"keydown\", function(e2) {\n dialog.is_modified = true;\n if (e2.keyCode == 27) {\n dialog.close();\n } else if (e2.keyCode == 13) {\n inner();\n } else if (e2.keyCode != 13 && e2.target.localName != \"textarea\") {\n return;\n }\n e2.preventDefault();\n e2.stopPropagation();\n });\n input.focus();\n }\n }\n };\n if (typeof window != \"undefined\" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) {\n window.CanvasRenderingContext2D.prototype.roundRect = function(x2, y2, w2, h, radius, radius_low) {\n var top_left_radius = 0;\n var top_right_radius = 0;\n var bottom_left_radius = 0;\n var bottom_right_radius = 0;\n if (radius === 0) {\n this.rect(x2, y2, w2, h);\n return;\n }\n if (radius_low === void 0)\n radius_low = radius;\n if (radius != null && radius.constructor === Array) {\n if (radius.length == 1)\n top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0];\n else if (radius.length == 2) {\n top_left_radius = bottom_right_radius = radius[0];\n top_right_radius = bottom_left_radius = radius[1];\n } else if (radius.length == 4) {\n top_left_radius = radius[0];\n top_right_radius = radius[1];\n bottom_left_radius = radius[2];\n bottom_right_radius = radius[3];\n } else\n return;\n } else {\n top_left_radius = radius || 0;\n top_right_radius = radius || 0;\n bottom_left_radius = radius_low || 0;\n bottom_right_radius = radius_low || 0;\n }\n this.moveTo(x2 + top_left_radius, y2);\n this.lineTo(x2 + w2 - top_right_radius, y2);\n this.quadraticCurveTo(x2 + w2, y2, x2 + w2, y2 + top_right_radius);\n this.lineTo(x2 + w2, y2 + h - bottom_right_radius);\n this.quadraticCurveTo(\n x2 + w2,\n y2 + h,\n x2 + w2 - bottom_right_radius,\n y2 + h\n );\n this.lineTo(x2 + bottom_right_radius, y2 + h);\n this.quadraticCurveTo(x2, y2 + h, x2, y2 + h - bottom_left_radius);\n this.lineTo(x2, y2 + bottom_left_radius);\n this.quadraticCurveTo(x2, y2, x2 + top_left_radius, y2);\n };\n }\n function compareObjects(a, b) {\n for (var i2 in a) {\n if (a[i2] != b[i2]) {\n return false;\n }\n }\n return true;\n }\n LiteGraph.compareObjects = compareObjects;\n function distance(a, b) {\n return Math.sqrt(\n (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])\n );\n }\n LiteGraph.distance = distance;\n function colorToString(c) {\n return \"rgba(\" + Math.round(c[0] * 255).toFixed() + \",\" + Math.round(c[1] * 255).toFixed() + \",\" + Math.round(c[2] * 255).toFixed() + \",\" + (c.length == 4 ? c[3].toFixed(2) : \"1.0\") + \")\";\n }\n LiteGraph.colorToString = colorToString;\n function isInsideRectangle(x2, y2, left, top, width2, height) {\n if (left < x2 && left + width2 > x2 && top < y2 && top + height > y2) {\n return true;\n }\n return false;\n }\n LiteGraph.isInsideRectangle = isInsideRectangle;\n function growBounding(bounding, x2, y2) {\n if (x2 < bounding[0]) {\n bounding[0] = x2;\n } else if (x2 > bounding[2]) {\n bounding[2] = x2;\n }\n if (y2 < bounding[1]) {\n bounding[1] = y2;\n } else if (y2 > bounding[3]) {\n bounding[3] = y2;\n }\n }\n LiteGraph.growBounding = growBounding;\n function isInsideBounding(p, bb) {\n if (p[0] < bb[0][0] || p[1] < bb[0][1] || p[0] > bb[1][0] || p[1] > bb[1][1]) {\n return false;\n }\n return true;\n }\n LiteGraph.isInsideBounding = isInsideBounding;\n function overlapBounding(a, b) {\n var A_end_x = a[0] + a[2];\n var A_end_y = a[1] + a[3];\n var B_end_x = b[0] + b[2];\n var B_end_y = b[1] + b[3];\n if (a[0] > B_end_x || a[1] > B_end_y || A_end_x < b[0] || A_end_y < b[1]) {\n return false;\n }\n return true;\n }\n LiteGraph.overlapBounding = overlapBounding;\n function hex2num(hex) {\n if (hex.charAt(0) == \"#\") {\n hex = hex.slice(1);\n }\n hex = hex.toUpperCase();\n var hex_alphabets = \"0123456789ABCDEF\";\n var value = new Array(3);\n var k = 0;\n var int1, int2;\n for (var i2 = 0; i2 < 6; i2 += 2) {\n int1 = hex_alphabets.indexOf(hex.charAt(i2));\n int2 = hex_alphabets.indexOf(hex.charAt(i2 + 1));\n value[k] = int1 * 16 + int2;\n k++;\n }\n return value;\n }\n LiteGraph.hex2num = hex2num;\n function num2hex(triplet) {\n var hex_alphabets = \"0123456789ABCDEF\";\n var hex = \"#\";\n var int1, int2;\n for (var i2 = 0; i2 < 3; i2++) {\n int1 = triplet[i2] / 16;\n int2 = triplet[i2] % 16;\n hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);\n }\n return hex;\n }\n LiteGraph.num2hex = num2hex;\n function ContextMenu(values2, options) {\n options = options || {};\n this.options = options;\n var that2 = this;\n if (options.parentMenu) {\n if (options.parentMenu.constructor !== this.constructor) {\n console.error(\n \"parentMenu must be of class ContextMenu, ignoring it\"\n );\n options.parentMenu = null;\n } else {\n this.parentMenu = options.parentMenu;\n this.parentMenu.lock = true;\n this.parentMenu.current_submenu = this;\n }\n }\n var eventClass = null;\n if (options.event)\n eventClass = options.event.constructor.name;\n if (eventClass !== \"MouseEvent\" && eventClass !== \"CustomEvent\" && eventClass !== \"PointerEvent\") {\n console.error(\n \"Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (\" + eventClass + \")\"\n );\n options.event = null;\n }\n var root = document.createElement(\"div\");\n root.className = \"litegraph litecontextmenu litemenubar-panel\";\n if (options.className) {\n root.className += \" \" + options.className;\n }\n root.style.minWidth = 100;\n root.style.minHeight = 100;\n root.style.pointerEvents = \"none\";\n setTimeout(function() {\n root.style.pointerEvents = \"auto\";\n }, 100);\n LiteGraph.pointerListenerAdd(\n root,\n \"up\",\n function(e) {\n e.preventDefault();\n return true;\n },\n true\n );\n root.addEventListener(\n \"contextmenu\",\n function(e) {\n if (e.button != 2) {\n return false;\n }\n e.preventDefault();\n return false;\n },\n true\n );\n LiteGraph.pointerListenerAdd(\n root,\n \"down\",\n function(e) {\n if (e.button == 2) {\n that2.close();\n e.preventDefault();\n return true;\n }\n },\n true\n );\n function on_mouse_wheel(e) {\n var pos2 = parseInt(root.style.top);\n root.style.top = (pos2 + e.deltaY * options.scroll_speed).toFixed() + \"px\";\n e.preventDefault();\n return true;\n }\n if (!options.scroll_speed) {\n options.scroll_speed = 0.1;\n }\n root.addEventListener(\"wheel\", on_mouse_wheel, true);\n root.addEventListener(\"mousewheel\", on_mouse_wheel, true);\n this.root = root;\n if (options.title) {\n var element = document.createElement(\"div\");\n element.className = \"litemenu-title\";\n element.innerHTML = options.title;\n root.appendChild(element);\n }\n for (var i2 = 0; i2 < values2.length; i2++) {\n var name = values2.constructor == Array ? values2[i2] : i2;\n if (name != null && name.constructor !== String) {\n name = name.content === void 0 ? String(name) : name.content;\n }\n var value = values2[i2];\n this.addItem(name, value, options);\n }\n LiteGraph.pointerListenerAdd(root, \"enter\", function(e) {\n if (root.closing_timer) {\n clearTimeout(root.closing_timer);\n }\n });\n var root_document = document;\n if (options.event) {\n root_document = options.event.target.ownerDocument;\n }\n if (!root_document) {\n root_document = document;\n }\n if (root_document.fullscreenElement)\n root_document.fullscreenElement.appendChild(root);\n else\n root_document.body.appendChild(root);\n var left = options.left || 0;\n var top = options.top || 0;\n if (options.event) {\n left = options.event.clientX - 10;\n top = options.event.clientY - 10;\n if (options.title) {\n top -= 20;\n }\n if (options.parentMenu) {\n var rect = options.parentMenu.root.getBoundingClientRect();\n left = rect.left + rect.width;\n }\n var body_rect = document.body.getBoundingClientRect();\n var root_rect = root.getBoundingClientRect();\n if (body_rect.height == 0)\n console.error(\"document.body height is 0. That is dangerous, set html,body { height: 100%; }\");\n if (body_rect.width && left > body_rect.width - root_rect.width - 10) {\n left = body_rect.width - root_rect.width - 10;\n }\n if (body_rect.height && top > body_rect.height - root_rect.height - 10) {\n top = body_rect.height - root_rect.height - 10;\n }\n }\n root.style.left = left + \"px\";\n root.style.top = top + \"px\";\n if (options.scale) {\n root.style.transform = \"scale(\" + options.scale + \")\";\n }\n }\n ContextMenu.prototype.addItem = function(name, value, options) {\n var that2 = this;\n options = options || {};\n var element = document.createElement(\"div\");\n element.className = \"litemenu-entry submenu\";\n var disabled = false;\n if (value === null) {\n element.classList.add(\"separator\");\n } else {\n element.innerHTML = value && value.title ? value.title : name;\n element.value = value;\n element.setAttribute(\"role\", \"menuitem\");\n if (value) {\n if (value.disabled) {\n disabled = true;\n element.classList.add(\"disabled\");\n element.setAttribute(\"aria-disabled\", \"true\");\n }\n if (value.submenu || value.has_submenu) {\n element.classList.add(\"has_submenu\");\n element.setAttribute(\"aria-haspopup\", \"true\");\n element.setAttribute(\"aria-expanded\", \"false\");\n }\n }\n if (typeof value == \"function\") {\n element.dataset[\"value\"] = name;\n element.onclick_callback = value;\n } else {\n element.dataset[\"value\"] = value;\n }\n if (value.className) {\n element.className += \" \" + value.className;\n }\n }\n this.root.appendChild(element);\n if (!disabled) {\n element.addEventListener(\"click\", inner_onclick);\n }\n if (!disabled && options.autoopen) {\n LiteGraph.pointerListenerAdd(element, \"enter\", inner_over);\n }\n function setAriaExpanded() {\n const entries = that2.root.querySelectorAll(\"div.litemenu-entry.has_submenu\");\n if (entries) {\n for (let i2 = 0; i2 < entries.length; i2++) {\n entries[i2].setAttribute(\"aria-expanded\", \"false\");\n }\n }\n element.setAttribute(\"aria-expanded\", \"true\");\n }\n function inner_over(e) {\n var value2 = this.value;\n if (!value2 || !value2.has_submenu) {\n return;\n }\n inner_onclick.call(this, e);\n setAriaExpanded();\n }\n function inner_onclick(e) {\n var value2 = this.value;\n var close_parent = true;\n if (that2.current_submenu) {\n that2.current_submenu.close(e);\n }\n if ((value2 == null ? void 0 : value2.has_submenu) || (value2 == null ? void 0 : value2.submenu)) {\n setAriaExpanded();\n }\n if (options.callback) {\n var r = options.callback.call(\n this,\n value2,\n options,\n e,\n that2,\n options.node\n );\n if (r === true) {\n close_parent = false;\n }\n }\n if (value2) {\n if (value2.callback && !options.ignore_item_callbacks && value2.disabled !== true) {\n var r = value2.callback.call(\n this,\n value2,\n options,\n e,\n that2,\n options.extra\n );\n if (r === true) {\n close_parent = false;\n }\n }\n if (value2.submenu) {\n if (!value2.submenu.options) {\n throw \"ContextMenu submenu needs options\";\n }\n new that2.constructor(value2.submenu.options, {\n callback: value2.submenu.callback,\n event: e,\n parentMenu: that2,\n ignore_item_callbacks: value2.submenu.ignore_item_callbacks,\n title: value2.submenu.title,\n extra: value2.submenu.extra,\n autoopen: options.autoopen\n });\n close_parent = false;\n }\n }\n if (close_parent && !that2.lock) {\n that2.close();\n }\n }\n return element;\n };\n ContextMenu.prototype.close = function(e, ignore_parent_menu) {\n if (this.root.parentNode) {\n this.root.parentNode.removeChild(this.root);\n }\n if (this.parentMenu && !ignore_parent_menu) {\n this.parentMenu.lock = false;\n this.parentMenu.current_submenu = null;\n if (e === void 0) {\n this.parentMenu.close();\n } else if (e && !ContextMenu.isCursorOverElement(e, this.parentMenu.root)) {\n ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method + \"leave\", e);\n }\n }\n if (this.current_submenu) {\n this.current_submenu.close(e, true);\n }\n if (this.root.closing_timer) {\n clearTimeout(this.root.closing_timer);\n }\n };\n ContextMenu.trigger = function(element, event_name, params, origin) {\n var evt = document.createEvent(\"CustomEvent\");\n evt.initCustomEvent(event_name, true, true, params);\n evt.srcElement = origin;\n if (element.dispatchEvent) {\n element.dispatchEvent(evt);\n } else if (element.__events) {\n element.__events.dispatchEvent(evt);\n }\n return evt;\n };\n ContextMenu.prototype.getTopMenu = function() {\n if (this.options.parentMenu) {\n return this.options.parentMenu.getTopMenu();\n }\n return this;\n };\n ContextMenu.prototype.getFirstEvent = function() {\n if (this.options.parentMenu) {\n return this.options.parentMenu.getFirstEvent();\n }\n return this.options.event;\n };\n ContextMenu.isCursorOverElement = function(event2, element) {\n var left = event2.clientX;\n var top = event2.clientY;\n var rect = element.getBoundingClientRect();\n if (!rect) {\n return false;\n }\n if (top > rect.top && top < rect.top + rect.height && left > rect.left && left < rect.left + rect.width) {\n return true;\n }\n return false;\n };\n LiteGraph.ContextMenu = ContextMenu;\n LiteGraph.closeAllContextMenus = function(ref_window2) {\n ref_window2 = ref_window2 || window;\n var elements = ref_window2.document.querySelectorAll(\".litecontextmenu\");\n if (!elements.length) {\n return;\n }\n var result = [];\n for (var i2 = 0; i2 < elements.length; i2++) {\n result.push(elements[i2]);\n }\n for (var i2 = 0; i2 < result.length; i2++) {\n if (result[i2].close) {\n result[i2].close();\n } else if (result[i2].parentNode) {\n result[i2].parentNode.removeChild(result[i2]);\n }\n }\n };\n LiteGraph.extendClass = function(target, origin) {\n for (var i2 in origin) {\n if (target.hasOwnProperty(i2)) {\n continue;\n }\n target[i2] = origin[i2];\n }\n if (origin.prototype) {\n for (var i2 in origin.prototype) {\n if (!origin.prototype.hasOwnProperty(i2)) {\n continue;\n }\n if (target.prototype.hasOwnProperty(i2)) {\n continue;\n }\n if (origin.prototype.__lookupGetter__(i2)) {\n target.prototype.__defineGetter__(\n i2,\n origin.prototype.__lookupGetter__(i2)\n );\n } else {\n target.prototype[i2] = origin.prototype[i2];\n }\n if (origin.prototype.__lookupSetter__(i2)) {\n target.prototype.__defineSetter__(\n i2,\n origin.prototype.__lookupSetter__(i2)\n );\n }\n }\n }\n };\n function CurveEditor(points) {\n this.points = points;\n this.selected = -1;\n this.nearest = -1;\n this.size = null;\n this.must_update = true;\n this.margin = 5;\n }\n CurveEditor.sampleCurve = function(f, points) {\n if (!points)\n return;\n for (var i2 = 0; i2 < points.length - 1; ++i2) {\n var p = points[i2];\n var pn = points[i2 + 1];\n if (pn[0] < f)\n continue;\n var r = pn[0] - p[0];\n if (Math.abs(r) < 1e-5)\n return p[1];\n var local_f = (f - p[0]) / r;\n return p[1] * (1 - local_f) + pn[1] * local_f;\n }\n return 0;\n };\n CurveEditor.prototype.draw = function(ctx, size, graphcanvas, background_color, line_color, inactive) {\n var points = this.points;\n if (!points)\n return;\n this.size = size;\n var w2 = size[0] - this.margin * 2;\n var h = size[1] - this.margin * 2;\n line_color = line_color || \"#666\";\n ctx.save();\n ctx.translate(this.margin, this.margin);\n if (background_color) {\n ctx.fillStyle = \"#111\";\n ctx.fillRect(0, 0, w2, h);\n ctx.fillStyle = \"#222\";\n ctx.fillRect(w2 * 0.5, 0, 1, h);\n ctx.strokeStyle = \"#333\";\n ctx.strokeRect(0, 0, w2, h);\n }\n ctx.strokeStyle = line_color;\n if (inactive)\n ctx.globalAlpha = 0.5;\n ctx.beginPath();\n for (var i2 = 0; i2 < points.length; ++i2) {\n var p = points[i2];\n ctx.lineTo(p[0] * w2, (1 - p[1]) * h);\n }\n ctx.stroke();\n ctx.globalAlpha = 1;\n if (!inactive)\n for (var i2 = 0; i2 < points.length; ++i2) {\n var p = points[i2];\n ctx.fillStyle = this.selected == i2 ? \"#FFF\" : this.nearest == i2 ? \"#DDD\" : \"#AAA\";\n ctx.beginPath();\n ctx.arc(p[0] * w2, (1 - p[1]) * h, 2, 0, Math.PI * 2);\n ctx.fill();\n }\n ctx.restore();\n };\n CurveEditor.prototype.onMouseDown = function(localpos, graphcanvas) {\n var points = this.points;\n if (!points)\n return;\n if (localpos[1] < 0)\n return;\n var w2 = this.size[0] - this.margin * 2;\n var h = this.size[1] - this.margin * 2;\n var x2 = localpos[0] - this.margin;\n var y2 = localpos[1] - this.margin;\n var pos2 = [x2, y2];\n var max_dist = 30 / graphcanvas.ds.scale;\n this.selected = this.getCloserPoint(pos2, max_dist);\n if (this.selected == -1) {\n var point = [x2 / w2, 1 - y2 / h];\n points.push(point);\n points.sort(function(a, b) {\n return a[0] - b[0];\n });\n this.selected = points.indexOf(point);\n this.must_update = true;\n }\n if (this.selected != -1)\n return true;\n };\n CurveEditor.prototype.onMouseMove = function(localpos, graphcanvas) {\n var points = this.points;\n if (!points)\n return;\n var s = this.selected;\n if (s < 0)\n return;\n var x2 = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2);\n var y2 = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2);\n var curvepos = [localpos[0] - this.margin, localpos[1] - this.margin];\n var max_dist = 30 / graphcanvas.ds.scale;\n this._nearest = this.getCloserPoint(curvepos, max_dist);\n var point = points[s];\n if (point) {\n var is_edge_point = s == 0 || s == points.length - 1;\n if (!is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10)) {\n points.splice(s, 1);\n this.selected = -1;\n return;\n }\n if (!is_edge_point)\n point[0] = clamp(x2, 0, 1);\n else\n point[0] = s == 0 ? 0 : 1;\n point[1] = 1 - clamp(y2, 0, 1);\n points.sort(function(a, b) {\n return a[0] - b[0];\n });\n this.selected = points.indexOf(point);\n this.must_update = true;\n }\n };\n CurveEditor.prototype.onMouseUp = function(localpos, graphcanvas) {\n this.selected = -1;\n return false;\n };\n CurveEditor.prototype.getCloserPoint = function(pos2, max_dist) {\n var points = this.points;\n if (!points)\n return -1;\n max_dist = max_dist || 30;\n var w2 = this.size[0] - this.margin * 2;\n var h = this.size[1] - this.margin * 2;\n var num = points.length;\n var p2 = [0, 0];\n var min_dist = 1e6;\n var closest = -1;\n for (var i2 = 0; i2 < num; ++i2) {\n var p = points[i2];\n p2[0] = p[0] * w2;\n p2[1] = (1 - p[1]) * h;\n if (p2[0] < pos2[0])\n ;\n var dist = vec2.distance(pos2, p2);\n if (dist > min_dist || dist > max_dist)\n continue;\n closest = i2;\n min_dist = dist;\n }\n return closest;\n };\n LiteGraph.CurveEditor = CurveEditor;\n LiteGraph.getParameterNames = function(func) {\n return (func + \"\").replace(/[/][/].*$/gm, \"\").replace(/\\s+/g, \"\").replace(/[/][*][^/*]*[*][/]/g, \"\").split(\"){\", 1)[0].replace(/^[^(]*[(]/, \"\").replace(/=[^,]+/g, \"\").split(\",\").filter(Boolean);\n };\n LiteGraph.pointerListenerAdd = function(oDOM, sEvIn, fCall, capture = false) {\n if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall !== \"function\") {\n return;\n }\n var sMethod = LiteGraph.pointerevents_method;\n var sEvent = sEvIn;\n if (sMethod == \"pointer\" && !window.PointerEvent) {\n console.warn(\"sMethod=='pointer' && !window.PointerEvent\");\n console.log(\"Converting pointer[\" + sEvent + \"] : down move up cancel enter TO touchstart touchmove touchend, etc ..\");\n switch (sEvent) {\n case \"down\": {\n sMethod = \"touch\";\n sEvent = \"start\";\n break;\n }\n case \"move\": {\n sMethod = \"touch\";\n break;\n }\n case \"up\": {\n sMethod = \"touch\";\n sEvent = \"end\";\n break;\n }\n case \"cancel\": {\n sMethod = \"touch\";\n break;\n }\n case \"enter\": {\n console.log(\"debug: Should I send a move event?\");\n break;\n }\n default: {\n console.warn(\"PointerEvent not available in this browser ? The event \" + sEvent + \" would not be called\");\n }\n }\n }\n switch (sEvent) {\n case \"down\":\n case \"up\":\n case \"move\":\n case \"over\":\n case \"out\":\n case \"enter\": {\n oDOM.addEventListener(sMethod + sEvent, fCall, capture);\n }\n case \"leave\":\n case \"cancel\":\n case \"gotpointercapture\":\n case \"lostpointercapture\": {\n if (sMethod != \"mouse\") {\n return oDOM.addEventListener(sMethod + sEvent, fCall, capture);\n }\n }\n default:\n return oDOM.addEventListener(sEvent, fCall, capture);\n }\n };\n LiteGraph.pointerListenerRemove = function(oDOM, sEvent, fCall, capture = false) {\n if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall !== \"function\") {\n return;\n }\n switch (sEvent) {\n case \"down\":\n case \"up\":\n case \"move\":\n case \"over\":\n case \"out\":\n case \"enter\": {\n if (LiteGraph.pointerevents_method == \"pointer\" || LiteGraph.pointerevents_method == \"mouse\") {\n oDOM.removeEventListener(LiteGraph.pointerevents_method + sEvent, fCall, capture);\n }\n }\n case \"leave\":\n case \"cancel\":\n case \"gotpointercapture\":\n case \"lostpointercapture\": {\n if (LiteGraph.pointerevents_method == \"pointer\") {\n return oDOM.removeEventListener(LiteGraph.pointerevents_method + sEvent, fCall, capture);\n }\n }\n default:\n return oDOM.removeEventListener(sEvent, fCall, capture);\n }\n };\n function clamp(v2, a, b) {\n return a > v2 ? a : b < v2 ? b : v2;\n }\n globalThis.clamp = clamp;\n if (typeof window != \"undefined\" && !window[\"requestAnimationFrame\"]) {\n window.requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {\n window.setTimeout(callback, 1e3 / 60);\n };\n }\n})(globalExport);\nconst LiteGraph = globalExport.LiteGraph;\nconst LGraph = globalExport.LGraph;\nconst LLink = globalExport.LLink;\nconst LGraphNode = globalExport.LGraphNode;\nconst LGraphGroup = globalExport.LGraphGroup;\nconst DragAndScale = globalExport.DragAndScale;\nconst LGraphCanvas = globalExport.LGraphCanvas;\nconst ContextMenu = globalExport.ContextMenu;\nexport {\n ContextMenu,\n DragAndScale,\n LGraph,\n LGraphCanvas,\n LGraphGroup,\n LGraphNode,\n LLink,\n LiteGraph\n};\n//# sourceMappingURL=litegraph.es.js.map\n","import { app, ANIM_PREVIEW_WIDGET } from './app'\r\nimport { LGraphCanvas, LGraphNode, LiteGraph } from '@comfyorg/litegraph'\r\nimport type { Vector4 } from '@comfyorg/litegraph'\r\n\r\nconst SIZE = Symbol()\r\n\r\ninterface Rect {\r\n height: number\r\n width: number\r\n x: number\r\n y: number\r\n}\r\n\r\nexport interface DOMWidget {\r\n type: string\r\n name: string\r\n computedHeight?: number\r\n element?: T\r\n options: any\r\n value?: any\r\n y?: number\r\n callback?: (value: any) => void\r\n draw?: (\r\n ctx: CanvasRenderingContext2D,\r\n node: LGraphNode,\r\n widgetWidth: number,\r\n y: number,\r\n widgetHeight: number\r\n ) => void\r\n onRemove?: () => void\r\n}\r\n\r\nfunction intersect(a: Rect, b: Rect): Vector4 | null {\r\n const x = Math.max(a.x, b.x)\r\n const num1 = Math.min(a.x + a.width, b.x + b.width)\r\n const y = Math.max(a.y, b.y)\r\n const num2 = Math.min(a.y + a.height, b.y + b.height)\r\n if (num1 >= x && num2 >= y) return [x, y, num1 - x, num2 - y]\r\n else return null\r\n}\r\n\r\nfunction getClipPath(node: LGraphNode, element: HTMLElement): string {\r\n const selectedNode: LGraphNode = Object.values(\r\n app.canvas.selected_nodes\r\n )[0] as LGraphNode\r\n if (selectedNode && selectedNode !== node) {\r\n const elRect = element.getBoundingClientRect()\r\n const MARGIN = 7\r\n const scale = app.canvas.ds.scale\r\n\r\n const bounding = selectedNode.getBounding()\r\n const intersection = intersect(\r\n {\r\n x: elRect.x / scale,\r\n y: elRect.y / scale,\r\n width: elRect.width / scale,\r\n height: elRect.height / scale\r\n },\r\n {\r\n x: selectedNode.pos[0] + app.canvas.ds.offset[0] - MARGIN,\r\n y:\r\n selectedNode.pos[1] +\r\n app.canvas.ds.offset[1] -\r\n LiteGraph.NODE_TITLE_HEIGHT -\r\n MARGIN,\r\n width: bounding[2] + MARGIN + MARGIN,\r\n height: bounding[3] + MARGIN + MARGIN\r\n }\r\n )\r\n\r\n if (!intersection) {\r\n return ''\r\n }\r\n\r\n const widgetRect = element.getBoundingClientRect()\r\n const clipX = elRect.left + intersection[0] - widgetRect.x / scale + 'px'\r\n const clipY = elRect.top + intersection[1] - widgetRect.y / scale + 'px'\r\n const clipWidth = intersection[2] + 'px'\r\n const clipHeight = intersection[3] + 'px'\r\n const path = `polygon(0% 0%, 0% 100%, ${clipX} 100%, ${clipX} ${clipY}, calc(${clipX} + ${clipWidth}) ${clipY}, calc(${clipX} + ${clipWidth}) calc(${clipY} + ${clipHeight}), ${clipX} calc(${clipY} + ${clipHeight}), ${clipX} 100%, 100% 100%, 100% 0%)`\r\n return path\r\n }\r\n return ''\r\n}\r\n\r\nfunction computeSize(size: [number, number]): void {\r\n if (this.widgets?.[0]?.last_y == null) return\r\n\r\n let y = this.widgets[0].last_y\r\n let freeSpace = size[1] - y\r\n\r\n let widgetHeight = 0\r\n let dom = []\r\n for (const w of this.widgets) {\r\n if (w.type === 'converted-widget') {\r\n // Ignore\r\n delete w.computedHeight\r\n } else if (w.computeSize) {\r\n widgetHeight += w.computeSize()[1] + 4\r\n } else if (w.element) {\r\n // Extract DOM widget size info\r\n const styles = getComputedStyle(w.element)\r\n let minHeight =\r\n w.options.getMinHeight?.() ??\r\n parseInt(styles.getPropertyValue('--comfy-widget-min-height'))\r\n let maxHeight =\r\n w.options.getMaxHeight?.() ??\r\n parseInt(styles.getPropertyValue('--comfy-widget-max-height'))\r\n\r\n let prefHeight =\r\n w.options.getHeight?.() ??\r\n styles.getPropertyValue('--comfy-widget-height')\r\n if (prefHeight.endsWith?.('%')) {\r\n prefHeight =\r\n size[1] *\r\n (parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100)\r\n } else {\r\n prefHeight = parseInt(prefHeight)\r\n if (isNaN(minHeight)) {\r\n minHeight = prefHeight\r\n }\r\n }\r\n if (isNaN(minHeight)) {\r\n minHeight = 50\r\n }\r\n if (!isNaN(maxHeight)) {\r\n if (!isNaN(prefHeight)) {\r\n prefHeight = Math.min(prefHeight, maxHeight)\r\n } else {\r\n prefHeight = maxHeight\r\n }\r\n }\r\n dom.push({\r\n minHeight,\r\n prefHeight,\r\n w\r\n })\r\n } else {\r\n widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n }\r\n\r\n freeSpace -= widgetHeight\r\n\r\n // Calculate sizes with all widgets at their min height\r\n const prefGrow = [] // Nodes that want to grow to their prefd size\r\n const canGrow = [] // Nodes that can grow to auto size\r\n let growBy = 0\r\n for (const d of dom) {\r\n freeSpace -= d.minHeight\r\n if (isNaN(d.prefHeight)) {\r\n canGrow.push(d)\r\n d.w.computedHeight = d.minHeight\r\n } else {\r\n const diff = d.prefHeight - d.minHeight\r\n if (diff > 0) {\r\n prefGrow.push(d)\r\n growBy += diff\r\n d.diff = diff\r\n } else {\r\n d.w.computedHeight = d.minHeight\r\n }\r\n }\r\n }\r\n\r\n if (this.imgs && !this.widgets.find((w) => w.name === ANIM_PREVIEW_WIDGET)) {\r\n // Allocate space for image\r\n freeSpace -= 220\r\n }\r\n\r\n this.freeWidgetSpace = freeSpace\r\n\r\n if (freeSpace < 0) {\r\n // Not enough space for all widgets so we need to grow\r\n size[1] -= freeSpace\r\n this.graph.setDirtyCanvas(true)\r\n } else {\r\n // Share the space between each\r\n const growDiff = freeSpace - growBy\r\n if (growDiff > 0) {\r\n // All pref sizes can be fulfilled\r\n freeSpace = growDiff\r\n for (const d of prefGrow) {\r\n d.w.computedHeight = d.prefHeight\r\n }\r\n } else {\r\n // We need to grow evenly\r\n const shared = -growDiff / prefGrow.length\r\n for (const d of prefGrow) {\r\n d.w.computedHeight = d.prefHeight - shared\r\n }\r\n freeSpace = 0\r\n }\r\n\r\n if (freeSpace > 0 && canGrow.length) {\r\n // Grow any that are auto height\r\n const shared = freeSpace / canGrow.length\r\n for (const d of canGrow) {\r\n d.w.computedHeight += shared\r\n }\r\n }\r\n }\r\n\r\n // Position each of the widgets\r\n for (const w of this.widgets) {\r\n w.y = y\r\n if (w.computedHeight) {\r\n y += w.computedHeight\r\n } else if (w.computeSize) {\r\n y += w.computeSize()[1] + 4\r\n } else {\r\n y += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n }\r\n}\r\n\r\n// Override the compute visible nodes function to allow us to hide/show DOM elements when the node goes offscreen\r\nconst elementWidgets = new Set()\r\n//@ts-ignore\r\nconst computeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes\r\n//@ts-ignore\r\nLGraphCanvas.prototype.computeVisibleNodes = function (): LGraphNode[] {\r\n const visibleNodes = computeVisibleNodes.apply(this, arguments)\r\n // @ts-expect-error\r\n for (const node of app.graph._nodes) {\r\n if (elementWidgets.has(node)) {\r\n const hidden = visibleNodes.indexOf(node) === -1\r\n for (const w of node.widgets) {\r\n if (w.element) {\r\n w.element.dataset.isInVisibleNodes = hidden ? 'false' : 'true'\r\n const shouldOtherwiseHide = w.element.dataset.shouldHide === 'true'\r\n const isCollapsed = w.element.dataset.collapsed === 'true'\r\n const wasHidden = w.element.hidden\r\n const actualHidden = hidden || shouldOtherwiseHide || isCollapsed\r\n w.element.hidden = actualHidden\r\n w.element.style.display = actualHidden ? 'none' : null\r\n if (actualHidden && !wasHidden) {\r\n w.options.onHide?.(w)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return visibleNodes\r\n}\r\n\r\nlet enableDomClipping = true\r\n\r\nexport function addDomClippingSetting(): void {\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.DOMClippingEnabled',\r\n category: ['Comfy', 'Node', 'DOMClippingEnabled'],\r\n name: 'Enable DOM element clipping (enabling may reduce performance)',\r\n type: 'boolean',\r\n defaultValue: enableDomClipping,\r\n onChange(value) {\r\n enableDomClipping = !!value\r\n }\r\n })\r\n}\r\n\r\n//@ts-ignore\r\nLGraphNode.prototype.addDOMWidget = function (\r\n name: string,\r\n type: string,\r\n element: HTMLElement,\r\n options: Record\r\n): DOMWidget {\r\n options = { hideOnZoom: true, selectOn: ['focus', 'click'], ...options }\r\n\r\n if (!element.parentElement) {\r\n app.canvasContainer.append(element)\r\n }\r\n element.hidden = true\r\n element.style.display = 'none'\r\n\r\n let mouseDownHandler\r\n if (element.blur) {\r\n mouseDownHandler = (event) => {\r\n if (!element.contains(event.target)) {\r\n element.blur()\r\n }\r\n }\r\n document.addEventListener('mousedown', mouseDownHandler)\r\n }\r\n\r\n const { nodeData } = this.constructor\r\n const tooltip = (nodeData?.input.required?.[name] ??\r\n nodeData?.input.optional?.[name])?.[1]?.tooltip\r\n if (tooltip && !element.title) {\r\n element.title = tooltip\r\n }\r\n\r\n const widget: DOMWidget = {\r\n type,\r\n name,\r\n get value() {\r\n return options.getValue?.() ?? undefined\r\n },\r\n set value(v) {\r\n options.setValue?.(v)\r\n widget.callback?.(widget.value)\r\n },\r\n draw: function (\r\n ctx: CanvasRenderingContext2D,\r\n node: LGraphNode,\r\n widgetWidth: number,\r\n y: number,\r\n widgetHeight: number\r\n ) {\r\n if (widget.computedHeight == null) {\r\n computeSize.call(node, node.size)\r\n }\r\n\r\n const hidden =\r\n (!!options.hideOnZoom && app.canvas.ds.scale < 0.5) ||\r\n widget.computedHeight <= 0 ||\r\n widget.type === 'converted-widget' ||\r\n widget.type === 'hidden'\r\n element.dataset.shouldHide = hidden ? 'true' : 'false'\r\n const isInVisibleNodes = element.dataset.isInVisibleNodes === 'true'\r\n const isCollapsed = element.dataset.collapsed === 'true'\r\n const actualHidden = hidden || !isInVisibleNodes || isCollapsed\r\n const wasHidden = element.hidden\r\n element.hidden = actualHidden\r\n element.style.display = actualHidden ? 'none' : null\r\n if (actualHidden && !wasHidden) {\r\n widget.options.onHide?.(widget)\r\n }\r\n if (actualHidden) {\r\n return\r\n }\r\n\r\n const margin = 10\r\n const elRect = ctx.canvas.getBoundingClientRect()\r\n const transform = new DOMMatrix()\r\n .scaleSelf(\r\n elRect.width / ctx.canvas.width,\r\n elRect.height / ctx.canvas.height\r\n )\r\n .multiplySelf(ctx.getTransform())\r\n .translateSelf(margin, margin + y)\r\n\r\n const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)\r\n\r\n Object.assign(element.style, {\r\n transformOrigin: '0 0',\r\n transform: scale,\r\n left: `${transform.a + transform.e}px`,\r\n top: `${transform.d + transform.f}px`,\r\n width: `${widgetWidth - margin * 2}px`,\r\n height: `${(widget.computedHeight ?? 50) - margin * 2}px`,\r\n position: 'absolute',\r\n // @ts-expect-error\r\n zIndex: app.graph._nodes.indexOf(node)\r\n })\r\n\r\n if (enableDomClipping) {\r\n element.style.clipPath = getClipPath(node, element)\r\n element.style.willChange = 'clip-path'\r\n }\r\n\r\n this.options.onDraw?.(widget)\r\n },\r\n element,\r\n options,\r\n onRemove() {\r\n if (mouseDownHandler) {\r\n document.removeEventListener('mousedown', mouseDownHandler)\r\n }\r\n element.remove()\r\n }\r\n }\r\n\r\n for (const evt of options.selectOn) {\r\n element.addEventListener(evt, () => {\r\n app.canvas.selectNode(this)\r\n app.canvas.bringToFront(this)\r\n })\r\n }\r\n\r\n this.addCustomWidget(widget)\r\n elementWidgets.add(this)\r\n\r\n const collapse = this.collapse\r\n this.collapse = function () {\r\n collapse.apply(this, arguments)\r\n if (this.flags?.collapsed) {\r\n element.hidden = true\r\n element.style.display = 'none'\r\n }\r\n element.dataset.collapsed = this.flags?.collapsed ? 'true' : 'false'\r\n }\r\n\r\n const onRemoved = this.onRemoved\r\n this.onRemoved = function () {\r\n element.remove()\r\n elementWidgets.delete(this)\r\n onRemoved?.apply(this, arguments)\r\n }\r\n\r\n if (!this[SIZE]) {\r\n this[SIZE] = true\r\n const onResize = this.onResize\r\n this.onResize = function (size) {\r\n options.beforeResize?.call(widget, this)\r\n computeSize.call(this, size)\r\n onResize?.apply(this, arguments)\r\n options.afterResize?.call(widget, this)\r\n }\r\n }\r\n\r\n return widget\r\n}\r\n","import { api } from './api'\r\nimport './domWidget'\r\nimport type { ComfyApp } from './app'\r\nimport type { IWidget, LGraphNode } from '@comfyorg/litegraph'\r\nimport { ComfyNodeDef } from '@/types/apiTypes'\r\n\r\nexport type ComfyWidgetConstructor = (\r\n node: LGraphNode,\r\n inputName: string,\r\n inputData: ComfyNodeDef,\r\n app?: ComfyApp,\r\n widgetName?: string\r\n) => { widget: IWidget; minWidth?: number; minHeight?: number }\r\n\r\nlet controlValueRunBefore = false\r\nexport function updateControlWidgetLabel(widget) {\r\n let replacement = 'after'\r\n let find = 'before'\r\n if (controlValueRunBefore) {\r\n ;[find, replacement] = [replacement, find]\r\n }\r\n widget.label = (widget.label ?? widget.name).replace(find, replacement)\r\n}\r\n\r\nconst IS_CONTROL_WIDGET = Symbol()\r\nconst HAS_EXECUTED = Symbol()\r\n\r\nfunction getNumberDefaults(\r\n inputData: ComfyNodeDef,\r\n defaultStep,\r\n precision,\r\n enable_rounding\r\n) {\r\n let defaultVal = inputData[1]['default']\r\n let { min, max, step, round } = inputData[1]\r\n\r\n if (defaultVal == undefined) defaultVal = 0\r\n if (min == undefined) min = 0\r\n if (max == undefined) max = 2048\r\n if (step == undefined) step = defaultStep\r\n // precision is the number of decimal places to show.\r\n // by default, display the the smallest number of decimal places such that changes of size step are visible.\r\n if (precision == undefined) {\r\n precision = Math.max(-Math.floor(Math.log10(step)), 0)\r\n }\r\n\r\n if (enable_rounding && (round == undefined || round === true)) {\r\n // by default, round the value to those decimal places shown.\r\n round = Math.round(1000000 * Math.pow(0.1, precision)) / 1000000\r\n }\r\n\r\n return {\r\n val: defaultVal,\r\n config: { min, max, step: 10.0 * step, round, precision }\r\n }\r\n}\r\n\r\nexport function addValueControlWidget(\r\n node,\r\n targetWidget,\r\n defaultValue = 'randomize',\r\n values,\r\n widgetName,\r\n inputData: ComfyNodeDef\r\n) {\r\n let name = inputData[1]?.control_after_generate\r\n if (typeof name !== 'string') {\r\n name = widgetName\r\n }\r\n const widgets = addValueControlWidgets(\r\n node,\r\n targetWidget,\r\n defaultValue,\r\n {\r\n addFilterList: false,\r\n controlAfterGenerateName: name\r\n },\r\n inputData\r\n )\r\n return widgets[0]\r\n}\r\n\r\nexport function addValueControlWidgets(\r\n node,\r\n targetWidget,\r\n defaultValue = 'randomize',\r\n options,\r\n inputData: ComfyNodeDef\r\n) {\r\n if (!defaultValue) defaultValue = 'randomize'\r\n if (!options) options = {}\r\n\r\n const getName = (defaultName, optionName) => {\r\n let name = defaultName\r\n if (options[optionName]) {\r\n name = options[optionName]\r\n } else if (typeof inputData?.[1]?.[defaultName] === 'string') {\r\n name = inputData?.[1]?.[defaultName]\r\n } else if (inputData?.[1]?.control_prefix) {\r\n name = inputData?.[1]?.control_prefix + ' ' + name\r\n }\r\n return name\r\n }\r\n\r\n const widgets = []\r\n const valueControl = node.addWidget(\r\n 'combo',\r\n getName('control_after_generate', 'controlAfterGenerateName'),\r\n defaultValue,\r\n function () {},\r\n {\r\n values: ['fixed', 'increment', 'decrement', 'randomize'],\r\n serialize: false // Don't include this in prompt.\r\n }\r\n )\r\n valueControl.tooltip =\r\n 'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'\r\n valueControl[IS_CONTROL_WIDGET] = true\r\n updateControlWidgetLabel(valueControl)\r\n widgets.push(valueControl)\r\n\r\n const isCombo = targetWidget.type === 'combo'\r\n let comboFilter\r\n if (isCombo) {\r\n valueControl.options.values.push('increment-wrap')\r\n }\r\n if (isCombo && options.addFilterList !== false) {\r\n comboFilter = node.addWidget(\r\n 'string',\r\n getName('control_filter_list', 'controlFilterListName'),\r\n '',\r\n function () {},\r\n {\r\n serialize: false // Don't include this in prompt.\r\n }\r\n )\r\n updateControlWidgetLabel(comboFilter)\r\n comboFilter.tooltip =\r\n \"Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'.\"\r\n\r\n widgets.push(comboFilter)\r\n }\r\n\r\n const applyWidgetControl = () => {\r\n var v = valueControl.value\r\n\r\n if (isCombo && v !== 'fixed') {\r\n let values = targetWidget.options.values\r\n const filter = comboFilter?.value\r\n if (filter) {\r\n let check\r\n if (filter.startsWith('/') && filter.endsWith('/')) {\r\n try {\r\n const regex = new RegExp(filter.substring(1, filter.length - 1))\r\n check = (item) => regex.test(item)\r\n } catch (error) {\r\n console.error(\r\n 'Error constructing RegExp filter for node ' + node.id,\r\n filter,\r\n error\r\n )\r\n }\r\n }\r\n if (!check) {\r\n const lower = filter.toLocaleLowerCase()\r\n check = (item) => item.toLocaleLowerCase().includes(lower)\r\n }\r\n values = values.filter((item) => check(item))\r\n if (!values.length && targetWidget.options.values.length) {\r\n console.warn(\r\n 'Filter for node ' + node.id + ' has filtered out all items',\r\n filter\r\n )\r\n }\r\n }\r\n let current_index = values.indexOf(targetWidget.value)\r\n let current_length = values.length\r\n\r\n switch (v) {\r\n case 'increment':\r\n current_index += 1\r\n break\r\n case 'increment-wrap':\r\n current_index += 1\r\n if (current_index >= current_length) {\r\n current_index = 0\r\n }\r\n break\r\n case 'decrement':\r\n current_index -= 1\r\n break\r\n case 'randomize':\r\n current_index = Math.floor(Math.random() * current_length)\r\n break\r\n default:\r\n break\r\n }\r\n current_index = Math.max(0, current_index)\r\n current_index = Math.min(current_length - 1, current_index)\r\n if (current_index >= 0) {\r\n let value = values[current_index]\r\n targetWidget.value = value\r\n targetWidget.callback(value)\r\n }\r\n } else {\r\n //number\r\n let min = targetWidget.options.min\r\n let max = targetWidget.options.max\r\n // limit to something that javascript can handle\r\n max = Math.min(1125899906842624, max)\r\n min = Math.max(-1125899906842624, min)\r\n let range = (max - min) / (targetWidget.options.step / 10)\r\n\r\n //adjust values based on valueControl Behaviour\r\n switch (v) {\r\n case 'fixed':\r\n break\r\n case 'increment':\r\n targetWidget.value += targetWidget.options.step / 10\r\n break\r\n case 'decrement':\r\n targetWidget.value -= targetWidget.options.step / 10\r\n break\r\n case 'randomize':\r\n targetWidget.value =\r\n Math.floor(Math.random() * range) *\r\n (targetWidget.options.step / 10) +\r\n min\r\n break\r\n default:\r\n break\r\n }\r\n /*check if values are over or under their respective\r\n * ranges and set them to min or max.*/\r\n if (targetWidget.value < min) targetWidget.value = min\r\n\r\n if (targetWidget.value > max) targetWidget.value = max\r\n targetWidget.callback(targetWidget.value)\r\n }\r\n }\r\n\r\n valueControl.beforeQueued = () => {\r\n if (controlValueRunBefore) {\r\n // Don't run on first execution\r\n if (valueControl[HAS_EXECUTED]) {\r\n applyWidgetControl()\r\n }\r\n }\r\n valueControl[HAS_EXECUTED] = true\r\n }\r\n\r\n valueControl.afterQueued = () => {\r\n if (!controlValueRunBefore) {\r\n applyWidgetControl()\r\n }\r\n }\r\n\r\n return widgets\r\n}\r\n\r\nfunction seedWidget(node, inputName, inputData: ComfyNodeDef, app, widgetName) {\r\n const seed = createIntWidget(node, inputName, inputData, app, true)\r\n const seedControl = addValueControlWidget(\r\n node,\r\n seed.widget,\r\n 'randomize',\r\n undefined,\r\n widgetName,\r\n inputData\r\n )\r\n\r\n seed.widget.linkedWidgets = [seedControl]\r\n return seed\r\n}\r\n\r\nfunction createIntWidget(\r\n node,\r\n inputName,\r\n inputData: ComfyNodeDef,\r\n app,\r\n isSeedInput: boolean = false\r\n) {\r\n const control = inputData[1]?.control_after_generate\r\n if (!isSeedInput && control) {\r\n return seedWidget(\r\n node,\r\n inputName,\r\n inputData,\r\n app,\r\n typeof control === 'string' ? control : undefined\r\n )\r\n }\r\n\r\n let widgetType = isSlider(inputData[1]['display'], app)\r\n const { val, config } = getNumberDefaults(inputData, 1, 0, true)\r\n Object.assign(config, { precision: 0 })\r\n return {\r\n widget: node.addWidget(\r\n widgetType,\r\n inputName,\r\n val,\r\n function (v) {\r\n const s = this.options.step / 10\r\n let sh = this.options.min % s\r\n if (isNaN(sh)) {\r\n sh = 0\r\n }\r\n this.value = Math.round((v - sh) / s) * s + sh\r\n },\r\n config\r\n )\r\n }\r\n}\r\n\r\nfunction addMultilineWidget(node, name, opts, app) {\r\n const inputEl = document.createElement('textarea')\r\n inputEl.className = 'comfy-multiline-input'\r\n inputEl.value = opts.defaultVal\r\n inputEl.placeholder = opts.placeholder || name\r\n inputEl.spellcheck = opts.spellcheck || false\r\n\r\n const widget = node.addDOMWidget(name, 'customtext', inputEl, {\r\n getValue() {\r\n return inputEl.value\r\n },\r\n setValue(v) {\r\n inputEl.value = v\r\n }\r\n })\r\n widget.inputEl = inputEl\r\n\r\n inputEl.addEventListener('input', () => {\r\n widget.callback?.(widget.value)\r\n })\r\n\r\n return { minWidth: 400, minHeight: 200, widget }\r\n}\r\n\r\nfunction isSlider(display, app) {\r\n if (app.ui.settings.getSettingValue('Comfy.DisableSliders')) {\r\n return 'number'\r\n }\r\n\r\n return display === 'slider' ? 'slider' : 'number'\r\n}\r\n\r\nexport function initWidgets(app) {\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.WidgetControlMode',\r\n category: ['Comfy', 'Node Widget', 'WidgetControlMode'],\r\n name: 'Widget control mode',\r\n tooltip:\r\n 'Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.',\r\n type: 'combo',\r\n defaultValue: 'after',\r\n options: ['before', 'after'],\r\n onChange(value) {\r\n controlValueRunBefore = value === 'before'\r\n for (const n of app.graph._nodes) {\r\n if (!n.widgets) continue\r\n for (const w of n.widgets) {\r\n if (w[IS_CONTROL_WIDGET]) {\r\n updateControlWidgetLabel(w)\r\n if (w.linkedWidgets) {\r\n for (const l of w.linkedWidgets) {\r\n updateControlWidgetLabel(l)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n })\r\n}\r\n\r\nexport const ComfyWidgets: Record = {\r\n 'INT:seed': seedWidget,\r\n 'INT:noise_seed': seedWidget,\r\n FLOAT(node, inputName, inputData: ComfyNodeDef, app) {\r\n let widgetType: 'number' | 'slider' = isSlider(inputData[1]['display'], app)\r\n let precision = app.ui.settings.getSettingValue(\r\n 'Comfy.FloatRoundingPrecision'\r\n )\r\n let disable_rounding = app.ui.settings.getSettingValue(\r\n 'Comfy.DisableFloatRounding'\r\n )\r\n if (precision == 0) precision = undefined\r\n const { val, config } = getNumberDefaults(\r\n inputData,\r\n 0.5,\r\n precision,\r\n !disable_rounding\r\n )\r\n return {\r\n widget: node.addWidget(\r\n widgetType,\r\n inputName,\r\n val,\r\n function (v) {\r\n if (config.round) {\r\n this.value =\r\n Math.round((v + Number.EPSILON) / config.round) * config.round\r\n if (this.value > config.max) this.value = config.max\r\n if (this.value < config.min) this.value = config.min\r\n } else {\r\n this.value = v\r\n }\r\n },\r\n config\r\n )\r\n }\r\n },\r\n INT(node, inputName, inputData: ComfyNodeDef, app) {\r\n return createIntWidget(node, inputName, inputData, app)\r\n },\r\n BOOLEAN(node, inputName, inputData) {\r\n let defaultVal = false\r\n let options = {}\r\n if (inputData[1]) {\r\n if (inputData[1].default) defaultVal = inputData[1].default\r\n if (inputData[1].label_on) options['on'] = inputData[1].label_on\r\n if (inputData[1].label_off) options['off'] = inputData[1].label_off\r\n }\r\n return {\r\n widget: node.addWidget('toggle', inputName, defaultVal, () => {}, options)\r\n }\r\n },\r\n STRING(node, inputName, inputData: ComfyNodeDef, app) {\r\n const defaultVal = inputData[1].default || ''\r\n const multiline = !!inputData[1].multiline\r\n\r\n let res\r\n if (multiline) {\r\n res = addMultilineWidget(\r\n node,\r\n inputName,\r\n { defaultVal, ...inputData[1] },\r\n app\r\n )\r\n } else {\r\n res = {\r\n widget: node.addWidget('text', inputName, defaultVal, () => {}, {})\r\n }\r\n }\r\n\r\n if (inputData[1].dynamicPrompts != undefined)\r\n res.widget.dynamicPrompts = inputData[1].dynamicPrompts\r\n\r\n return res\r\n },\r\n COMBO(node, inputName, inputData: ComfyNodeDef) {\r\n const type = inputData[0]\r\n let defaultValue = type[0]\r\n if (inputData[1] && inputData[1].default) {\r\n defaultValue = inputData[1].default\r\n }\r\n const res = {\r\n widget: node.addWidget('combo', inputName, defaultValue, () => {}, {\r\n values: type\r\n })\r\n }\r\n if (inputData[1]?.control_after_generate) {\r\n // TODO make combo handle a widget node type?\r\n res.widget.linkedWidgets = addValueControlWidgets(\r\n node,\r\n res.widget,\r\n undefined,\r\n undefined,\r\n inputData\r\n )\r\n }\r\n return res\r\n },\r\n IMAGEUPLOAD(\r\n node: LGraphNode,\r\n inputName: string,\r\n inputData: ComfyNodeDef,\r\n app\r\n ) {\r\n // TODO make image upload handle a custom node type?\r\n const imageWidget = node.widgets.find(\r\n (w) => w.name === (inputData[1]?.widget ?? 'image')\r\n )\r\n let uploadWidget\r\n\r\n function showImage(name) {\r\n const img = new Image()\r\n img.onload = () => {\r\n // @ts-expect-error\r\n node.imgs = [img]\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n let folder_separator = name.lastIndexOf('/')\r\n let subfolder = ''\r\n if (folder_separator > -1) {\r\n subfolder = name.substring(0, folder_separator)\r\n name = name.substring(folder_separator + 1)\r\n }\r\n img.src = api.apiURL(\r\n `/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`\r\n )\r\n // @ts-expect-error\r\n node.setSizeForImage?.()\r\n }\r\n\r\n var default_value = imageWidget.value\r\n Object.defineProperty(imageWidget, 'value', {\r\n set: function (value) {\r\n this._real_value = value\r\n },\r\n\r\n get: function () {\r\n if (!this._real_value) {\r\n return default_value\r\n }\r\n\r\n let value = this._real_value\r\n if (value.filename) {\r\n let real_value = value\r\n value = ''\r\n if (real_value.subfolder) {\r\n value = real_value.subfolder + '/'\r\n }\r\n\r\n value += real_value.filename\r\n\r\n if (real_value.type && real_value.type !== 'input')\r\n value += ` [${real_value.type}]`\r\n }\r\n return value\r\n }\r\n })\r\n\r\n // Add our own callback to the combo widget to render an image when it changes\r\n // TODO: Explain this?\r\n // @ts-expect-error\r\n const cb = node.callback\r\n imageWidget.callback = function () {\r\n showImage(imageWidget.value)\r\n if (cb) {\r\n return cb.apply(this, arguments)\r\n }\r\n }\r\n\r\n // On load if we have a value then render the image\r\n // The value isnt set immediately so we need to wait a moment\r\n // No change callbacks seem to be fired on initial setting of the value\r\n requestAnimationFrame(() => {\r\n if (imageWidget.value) {\r\n showImage(imageWidget.value)\r\n }\r\n })\r\n\r\n async function uploadFile(file, updateNode, pasted = false) {\r\n try {\r\n // Wrap file in formdata so it includes filename\r\n const body = new FormData()\r\n body.append('image', file)\r\n if (pasted) body.append('subfolder', 'pasted')\r\n const resp = await api.fetchApi('/upload/image', {\r\n method: 'POST',\r\n body\r\n })\r\n\r\n if (resp.status === 200) {\r\n const data = await resp.json()\r\n // Add the file to the dropdown list and update the widget value\r\n let path = data.name\r\n if (data.subfolder) path = data.subfolder + '/' + path\r\n\r\n if (!imageWidget.options.values.includes(path)) {\r\n imageWidget.options.values.push(path)\r\n }\r\n\r\n if (updateNode) {\r\n showImage(path)\r\n imageWidget.value = path\r\n }\r\n } else {\r\n alert(resp.status + ' - ' + resp.statusText)\r\n }\r\n } catch (error) {\r\n alert(error)\r\n }\r\n }\r\n\r\n const fileInput = document.createElement('input')\r\n Object.assign(fileInput, {\r\n type: 'file',\r\n accept: 'image/jpeg,image/png,image/webp',\r\n style: 'display: none',\r\n onchange: async () => {\r\n if (fileInput.files.length) {\r\n await uploadFile(fileInput.files[0], true)\r\n }\r\n }\r\n })\r\n document.body.append(fileInput)\r\n\r\n // Create the button widget for selecting the files\r\n uploadWidget = node.addWidget('button', inputName, 'image', () => {\r\n fileInput.click()\r\n })\r\n uploadWidget.label = 'choose file to upload'\r\n uploadWidget.serialize = false\r\n\r\n // Add handler to check if an image is being dragged over our node\r\n // @ts-expect-error\r\n node.onDragOver = function (e) {\r\n if (e.dataTransfer && e.dataTransfer.items) {\r\n const image = [...e.dataTransfer.items].find((f) => f.kind === 'file')\r\n return !!image\r\n }\r\n\r\n return false\r\n }\r\n\r\n // On drop upload files\r\n // @ts-expect-error\r\n node.onDragDrop = function (e) {\r\n console.log('onDragDrop called')\r\n let handled = false\r\n for (const file of e.dataTransfer.files) {\r\n if (file.type.startsWith('image/')) {\r\n uploadFile(file, !handled) // Dont await these, any order is fine, only update on first one\r\n handled = true\r\n }\r\n }\r\n\r\n return handled\r\n }\r\n\r\n // @ts-expect-error\r\n node.pasteFile = function (file) {\r\n if (file.type.startsWith('image/')) {\r\n const is_pasted =\r\n file.name === 'image.png' && file.lastModified - Date.now() < 2000\r\n uploadFile(file, true, is_pasted)\r\n return true\r\n }\r\n return false\r\n }\r\n\r\n return { widget: uploadWidget }\r\n }\r\n}\r\n","import type { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\r\n\r\nexport const defaultGraph: ComfyWorkflowJSON = {\r\n last_node_id: 9,\r\n last_link_id: 9,\r\n nodes: [\r\n {\r\n id: 7,\r\n type: 'CLIPTextEncode',\r\n pos: [413, 389],\r\n size: [425.27801513671875, 180.6060791015625],\r\n flags: {},\r\n order: 3,\r\n mode: 0,\r\n inputs: [{ name: 'clip', type: 'CLIP', link: 5 }],\r\n outputs: [\r\n {\r\n name: 'CONDITIONING',\r\n type: 'CONDITIONING',\r\n links: [6],\r\n slot_index: 0\r\n }\r\n ],\r\n properties: {},\r\n widgets_values: ['text, watermark']\r\n },\r\n {\r\n id: 6,\r\n type: 'CLIPTextEncode',\r\n pos: [415, 186],\r\n size: [422.84503173828125, 164.31304931640625],\r\n flags: {},\r\n order: 2,\r\n mode: 0,\r\n inputs: [{ name: 'clip', type: 'CLIP', link: 3 }],\r\n outputs: [\r\n {\r\n name: 'CONDITIONING',\r\n type: 'CONDITIONING',\r\n links: [4],\r\n slot_index: 0\r\n }\r\n ],\r\n properties: {},\r\n widgets_values: [\r\n 'beautiful scenery nature glass bottle landscape, , purple galaxy bottle,'\r\n ]\r\n },\r\n {\r\n id: 5,\r\n type: 'EmptyLatentImage',\r\n pos: [473, 609],\r\n size: [315, 106],\r\n flags: {},\r\n order: 1,\r\n mode: 0,\r\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [2], slot_index: 0 }],\r\n properties: {},\r\n widgets_values: [512, 512, 1]\r\n },\r\n {\r\n id: 3,\r\n type: 'KSampler',\r\n pos: [863, 186],\r\n size: [315, 262],\r\n flags: {},\r\n order: 4,\r\n mode: 0,\r\n inputs: [\r\n { name: 'model', type: 'MODEL', link: 1 },\r\n { name: 'positive', type: 'CONDITIONING', link: 4 },\r\n { name: 'negative', type: 'CONDITIONING', link: 6 },\r\n { name: 'latent_image', type: 'LATENT', link: 2 }\r\n ],\r\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [7], slot_index: 0 }],\r\n properties: {},\r\n widgets_values: [156680208700286, true, 20, 8, 'euler', 'normal', 1]\r\n },\r\n {\r\n id: 8,\r\n type: 'VAEDecode',\r\n pos: [1209, 188],\r\n size: [210, 46],\r\n flags: {},\r\n order: 5,\r\n mode: 0,\r\n inputs: [\r\n { name: 'samples', type: 'LATENT', link: 7 },\r\n { name: 'vae', type: 'VAE', link: 8 }\r\n ],\r\n outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [9], slot_index: 0 }],\r\n properties: {}\r\n },\r\n {\r\n id: 9,\r\n type: 'SaveImage',\r\n pos: [1451, 189],\r\n size: [210, 26],\r\n flags: {},\r\n order: 6,\r\n mode: 0,\r\n inputs: [{ name: 'images', type: 'IMAGE', link: 9 }],\r\n properties: {}\r\n },\r\n {\r\n id: 4,\r\n type: 'CheckpointLoaderSimple',\r\n pos: [26, 474],\r\n size: [315, 98],\r\n flags: {},\r\n order: 0,\r\n mode: 0,\r\n outputs: [\r\n { name: 'MODEL', type: 'MODEL', links: [1], slot_index: 0 },\r\n { name: 'CLIP', type: 'CLIP', links: [3, 5], slot_index: 1 },\r\n { name: 'VAE', type: 'VAE', links: [8], slot_index: 2 }\r\n ],\r\n properties: {},\r\n widgets_values: ['v1-5-pruned-emaonly.ckpt']\r\n }\r\n ],\r\n links: [\r\n [1, 4, 0, 3, 0, 'MODEL'],\r\n [2, 5, 0, 3, 3, 'LATENT'],\r\n [3, 4, 1, 6, 0, 'CLIP'],\r\n [4, 6, 0, 3, 1, 'CONDITIONING'],\r\n [5, 4, 1, 7, 0, 'CLIP'],\r\n [6, 7, 0, 3, 2, 'CONDITIONING'],\r\n [7, 3, 0, 8, 0, 'LATENT'],\r\n [8, 4, 2, 8, 1, 'VAE'],\r\n [9, 8, 0, 9, 0, 'IMAGE']\r\n ],\r\n groups: [],\r\n config: {},\r\n extra: {},\r\n version: 0.4,\r\n models: [\r\n {\r\n name: 'v1-5-pruned-emaonly.ckpt',\r\n url: 'https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt',\r\n hash: 'cc6cb27103417325ff94f52b7a5d2dde45a7515b25c255d8e396c90014281516',\r\n hash_type: 'SHA256',\r\n directory: 'checkpoints'\r\n }\r\n ]\r\n}\r\n","export function getFromPngBuffer(buffer: ArrayBuffer) {\r\n // Get the PNG data as a Uint8Array\r\n const pngData = new Uint8Array(buffer)\r\n const dataView = new DataView(pngData.buffer)\r\n\r\n // Check that the PNG signature is present\r\n if (dataView.getUint32(0) !== 0x89504e47) {\r\n console.error('Not a valid PNG file')\r\n return\r\n }\r\n\r\n // Start searching for chunks after the PNG signature\r\n let offset = 8\r\n let txt_chunks: Record = {}\r\n // Loop through the chunks in the PNG file\r\n while (offset < pngData.length) {\r\n // Get the length of the chunk\r\n const length = dataView.getUint32(offset)\r\n // Get the chunk type\r\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\r\n if (type === 'tEXt' || type == 'comf' || type === 'iTXt') {\r\n // Get the keyword\r\n let keyword_end = offset + 8\r\n while (pngData[keyword_end] !== 0) {\r\n keyword_end++\r\n }\r\n const keyword = String.fromCharCode(\r\n ...pngData.slice(offset + 8, keyword_end)\r\n )\r\n // Get the text\r\n const contentArraySegment = pngData.slice(\r\n keyword_end + 1,\r\n offset + 8 + length\r\n )\r\n const contentJson = new TextDecoder('utf-8').decode(contentArraySegment)\r\n txt_chunks[keyword] = contentJson\r\n }\r\n\r\n offset += 12 + length\r\n }\r\n return txt_chunks\r\n}\r\n\r\nexport function getFromPngFile(file: File) {\r\n return new Promise>((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n r(getFromPngBuffer(event.target.result as ArrayBuffer))\r\n }\r\n\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n","export function getFromFlacBuffer(buffer: ArrayBuffer): Record {\r\n const dataView = new DataView(buffer)\r\n\r\n // Verify the FLAC signature\r\n const signature = String.fromCharCode(...new Uint8Array(buffer, 0, 4))\r\n if (signature !== 'fLaC') {\r\n console.error('Not a valid FLAC file')\r\n return\r\n }\r\n\r\n // Parse metadata blocks\r\n let offset = 4\r\n let vorbisComment = null\r\n while (offset < dataView.byteLength) {\r\n const isLastBlock = dataView.getUint8(offset) & 0x80\r\n const blockType = dataView.getUint8(offset) & 0x7f\r\n const blockSize = dataView.getUint32(offset, false) & 0xffffff\r\n offset += 4\r\n\r\n if (blockType === 4) {\r\n // Vorbis Comment block type\r\n vorbisComment = parseVorbisComment(\r\n new DataView(buffer, offset, blockSize)\r\n )\r\n }\r\n\r\n offset += blockSize\r\n if (isLastBlock) break\r\n }\r\n\r\n return vorbisComment\r\n}\r\n\r\nexport function getFromFlacFile(file: File): Promise> {\r\n return new Promise((r) => {\r\n const reader = new FileReader()\r\n reader.onload = function (event) {\r\n const arrayBuffer = event.target.result as ArrayBuffer\r\n r(getFromFlacBuffer(arrayBuffer))\r\n }\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n\r\n// Function to parse the Vorbis Comment block\r\nfunction parseVorbisComment(dataView: DataView): Record {\r\n let offset = 0\r\n const vendorLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const vendorString = getString(dataView, offset, vendorLength)\r\n offset += vendorLength\r\n\r\n const userCommentListLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const comments = {}\r\n for (let i = 0; i < userCommentListLength; i++) {\r\n const commentLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const comment = getString(dataView, offset, commentLength)\r\n offset += commentLength\r\n\r\n const ind = comment.indexOf('=')\r\n const key = comment.substring(0, ind)\r\n\r\n comments[key] = comment.substring(ind + 1)\r\n }\r\n\r\n return comments\r\n}\r\n\r\nfunction getString(dataView: DataView, offset: number, length: number): string {\r\n let string = ''\r\n for (let i = 0; i < length; i++) {\r\n string += String.fromCharCode(dataView.getUint8(offset + i))\r\n }\r\n return string\r\n}\r\n","import { LiteGraph } from '@comfyorg/litegraph'\r\nimport { api } from './api'\r\nimport { getFromPngFile } from './metadata/png'\r\nimport { getFromFlacFile } from './metadata/flac'\r\n\r\n// Original functions left in for backwards compatibility\r\nexport function getPngMetadata(file: File): Promise> {\r\n return getFromPngFile(file)\r\n}\r\n\r\nexport function getFlacMetadata(file: File): Promise> {\r\n return getFromFlacFile(file)\r\n}\r\n\r\nfunction parseExifData(exifData) {\r\n // Check for the correct TIFF header (0x4949 for little-endian or 0x4D4D for big-endian)\r\n const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === 'II'\r\n\r\n // Function to read 16-bit and 32-bit integers from binary data\r\n function readInt(offset, isLittleEndian, length) {\r\n let arr = exifData.slice(offset, offset + length)\r\n if (length === 2) {\r\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(\r\n 0,\r\n isLittleEndian\r\n )\r\n } else if (length === 4) {\r\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(\r\n 0,\r\n isLittleEndian\r\n )\r\n }\r\n }\r\n\r\n // Read the offset to the first IFD (Image File Directory)\r\n const ifdOffset = readInt(4, isLittleEndian, 4)\r\n\r\n function parseIFD(offset) {\r\n const numEntries = readInt(offset, isLittleEndian, 2)\r\n const result = {}\r\n\r\n for (let i = 0; i < numEntries; i++) {\r\n const entryOffset = offset + 2 + i * 12\r\n const tag = readInt(entryOffset, isLittleEndian, 2)\r\n const type = readInt(entryOffset + 2, isLittleEndian, 2)\r\n const numValues = readInt(entryOffset + 4, isLittleEndian, 4)\r\n const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4)\r\n\r\n // Read the value(s) based on the data type\r\n let value\r\n if (type === 2) {\r\n // ASCII string\r\n value = String.fromCharCode(\r\n ...exifData.slice(valueOffset, valueOffset + numValues - 1)\r\n )\r\n }\r\n\r\n result[tag] = value\r\n }\r\n\r\n return result\r\n }\r\n\r\n // Parse the first IFD\r\n const ifdData = parseIFD(ifdOffset)\r\n return ifdData\r\n}\r\n\r\nfunction splitValues(input) {\r\n var output = {}\r\n for (var key in input) {\r\n var value = input[key]\r\n var splitValues = value.split(':', 2)\r\n output[splitValues[0]] = splitValues[1]\r\n }\r\n return output\r\n}\r\n\r\nexport function getWebpMetadata(file) {\r\n return new Promise>((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n const webp = new Uint8Array(event.target.result as ArrayBuffer)\r\n const dataView = new DataView(webp.buffer)\r\n\r\n // Check that the WEBP signature is present\r\n if (\r\n dataView.getUint32(0) !== 0x52494646 ||\r\n dataView.getUint32(8) !== 0x57454250\r\n ) {\r\n console.error('Not a valid WEBP file')\r\n r({})\r\n return\r\n }\r\n\r\n // Start searching for chunks after the WEBP signature\r\n let offset = 12\r\n let txt_chunks = {}\r\n // Loop through the chunks in the WEBP file\r\n while (offset < webp.length) {\r\n const chunk_length = dataView.getUint32(offset + 4, true)\r\n const chunk_type = String.fromCharCode(\r\n ...webp.slice(offset, offset + 4)\r\n )\r\n if (chunk_type === 'EXIF') {\r\n if (\r\n String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) ==\r\n 'Exif\\0\\0'\r\n ) {\r\n offset += 6\r\n }\r\n let data = parseExifData(\r\n webp.slice(offset + 8, offset + 8 + chunk_length)\r\n )\r\n for (var key in data) {\r\n var value = data[key] as string\r\n let index = value.indexOf(':')\r\n txt_chunks[value.slice(0, index)] = value.slice(index + 1)\r\n }\r\n break\r\n }\r\n\r\n offset += 8 + chunk_length\r\n }\r\n\r\n r(txt_chunks)\r\n }\r\n\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n\r\nexport function getLatentMetadata(file) {\r\n return new Promise((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n const safetensorsData = new Uint8Array(event.target.result as ArrayBuffer)\r\n const dataView = new DataView(safetensorsData.buffer)\r\n let header_size = dataView.getUint32(0, true)\r\n let offset = 8\r\n let header = JSON.parse(\r\n new TextDecoder().decode(\r\n safetensorsData.slice(offset, offset + header_size)\r\n )\r\n )\r\n r(header.__metadata__)\r\n }\r\n\r\n var slice = file.slice(0, 1024 * 1024 * 4)\r\n reader.readAsArrayBuffer(slice)\r\n })\r\n}\r\n\r\nexport async function importA1111(graph, parameters) {\r\n const p = parameters.lastIndexOf('\\nSteps:')\r\n if (p > -1) {\r\n const embeddings = await api.getEmbeddings()\r\n const opts = parameters\r\n .substr(p)\r\n .split('\\n')[1]\r\n .match(\r\n new RegExp('\\\\s*([^:]+:\\\\s*([^\"\\\\{].*?|\".*?\"|\\\\{.*?\\\\}))\\\\s*(,|$)', 'g')\r\n )\r\n .reduce((p, n) => {\r\n const s = n.split(':')\r\n if (s[1].endsWith(',')) {\r\n s[1] = s[1].substr(0, s[1].length - 1)\r\n }\r\n p[s[0].trim().toLowerCase()] = s[1].trim()\r\n return p\r\n }, {})\r\n const p2 = parameters.lastIndexOf('\\nNegative prompt:', p)\r\n if (p2 > -1) {\r\n let positive = parameters.substr(0, p2).trim()\r\n let negative = parameters.substring(p2 + 18, p).trim()\r\n\r\n const ckptNode = LiteGraph.createNode('CheckpointLoaderSimple')\r\n const clipSkipNode = LiteGraph.createNode('CLIPSetLastLayer')\r\n const positiveNode = LiteGraph.createNode('CLIPTextEncode')\r\n const negativeNode = LiteGraph.createNode('CLIPTextEncode')\r\n const samplerNode = LiteGraph.createNode('KSampler')\r\n const imageNode = LiteGraph.createNode('EmptyLatentImage')\r\n const vaeNode = LiteGraph.createNode('VAEDecode')\r\n const vaeLoaderNode = LiteGraph.createNode('VAELoader')\r\n const saveNode = LiteGraph.createNode('SaveImage')\r\n let hrSamplerNode = null\r\n let hrSteps = null\r\n\r\n const ceil64 = (v) => Math.ceil(v / 64) * 64\r\n\r\n const getWidget = (node, name) => {\r\n return node.widgets.find((w) => w.name === name)\r\n }\r\n\r\n const setWidgetValue = (node, name, value, isOptionPrefix?) => {\r\n const w = getWidget(node, name)\r\n if (isOptionPrefix) {\r\n const o = w.options.values.find((w) => w.startsWith(value))\r\n if (o) {\r\n w.value = o\r\n } else {\r\n console.warn(`Unknown value '${value}' for widget '${name}'`, node)\r\n w.value = value\r\n }\r\n } else {\r\n w.value = value\r\n }\r\n }\r\n\r\n const createLoraNodes = (clipNode, text, prevClip, prevModel) => {\r\n const loras = []\r\n text = text.replace(/]+)>/g, function (m, c) {\r\n const s = c.split(':')\r\n const weight = parseFloat(s[1])\r\n if (isNaN(weight)) {\r\n console.warn('Invalid LORA', m)\r\n } else {\r\n loras.push({ name: s[0], weight })\r\n }\r\n return ''\r\n })\r\n\r\n for (const l of loras) {\r\n const loraNode = LiteGraph.createNode('LoraLoader')\r\n graph.add(loraNode)\r\n setWidgetValue(loraNode, 'lora_name', l.name, true)\r\n setWidgetValue(loraNode, 'strength_model', l.weight)\r\n setWidgetValue(loraNode, 'strength_clip', l.weight)\r\n prevModel.node.connect(prevModel.index, loraNode, 0)\r\n prevClip.node.connect(prevClip.index, loraNode, 1)\r\n prevModel = { node: loraNode, index: 0 }\r\n prevClip = { node: loraNode, index: 1 }\r\n }\r\n\r\n prevClip.node.connect(1, clipNode, 0)\r\n prevModel.node.connect(0, samplerNode, 0)\r\n if (hrSamplerNode) {\r\n prevModel.node.connect(0, hrSamplerNode, 0)\r\n }\r\n\r\n return { text, prevModel, prevClip }\r\n }\r\n\r\n const replaceEmbeddings = (text) => {\r\n if (!embeddings.length) return text\r\n return text.replaceAll(\r\n new RegExp(\r\n '\\\\b(' +\r\n embeddings\r\n .map((e) => e.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\r\n .join('\\\\b|\\\\b') +\r\n ')\\\\b',\r\n 'ig'\r\n ),\r\n 'embedding:$1'\r\n )\r\n }\r\n\r\n const popOpt = (name) => {\r\n const v = opts[name]\r\n delete opts[name]\r\n return v\r\n }\r\n\r\n graph.clear()\r\n graph.add(ckptNode)\r\n graph.add(clipSkipNode)\r\n graph.add(positiveNode)\r\n graph.add(negativeNode)\r\n graph.add(samplerNode)\r\n graph.add(imageNode)\r\n graph.add(vaeNode)\r\n graph.add(vaeLoaderNode)\r\n graph.add(saveNode)\r\n\r\n ckptNode.connect(1, clipSkipNode, 0)\r\n clipSkipNode.connect(0, positiveNode, 0)\r\n clipSkipNode.connect(0, negativeNode, 0)\r\n ckptNode.connect(0, samplerNode, 0)\r\n positiveNode.connect(0, samplerNode, 1)\r\n negativeNode.connect(0, samplerNode, 2)\r\n imageNode.connect(0, samplerNode, 3)\r\n vaeNode.connect(0, saveNode, 0)\r\n samplerNode.connect(0, vaeNode, 0)\r\n vaeLoaderNode.connect(0, vaeNode, 1)\r\n\r\n const handlers = {\r\n model(v) {\r\n setWidgetValue(ckptNode, 'ckpt_name', v, true)\r\n },\r\n vae(v) {\r\n setWidgetValue(vaeLoaderNode, 'vae_name', v, true)\r\n },\r\n 'cfg scale'(v) {\r\n setWidgetValue(samplerNode, 'cfg', +v)\r\n },\r\n 'clip skip'(v) {\r\n setWidgetValue(clipSkipNode, 'stop_at_clip_layer', -v)\r\n },\r\n sampler(v) {\r\n let name = v.toLowerCase().replace('++', 'pp').replaceAll(' ', '_')\r\n if (name.includes('karras')) {\r\n name = name.replace('karras', '').replace(/_+$/, '')\r\n setWidgetValue(samplerNode, 'scheduler', 'karras')\r\n } else {\r\n setWidgetValue(samplerNode, 'scheduler', 'normal')\r\n }\r\n const w = getWidget(samplerNode, 'sampler_name')\r\n const o = w.options.values.find(\r\n (w) => w === name || w === 'sample_' + name\r\n )\r\n if (o) {\r\n setWidgetValue(samplerNode, 'sampler_name', o)\r\n }\r\n },\r\n size(v) {\r\n const wxh = v.split('x')\r\n const w = ceil64(+wxh[0])\r\n const h = ceil64(+wxh[1])\r\n const hrUp = popOpt('hires upscale')\r\n const hrSz = popOpt('hires resize')\r\n hrSteps = popOpt('hires steps')\r\n let hrMethod = popOpt('hires upscaler')\r\n\r\n setWidgetValue(imageNode, 'width', w)\r\n setWidgetValue(imageNode, 'height', h)\r\n\r\n if (hrUp || hrSz) {\r\n let uw, uh\r\n if (hrUp) {\r\n uw = w * hrUp\r\n uh = h * hrUp\r\n } else {\r\n const s = hrSz.split('x')\r\n uw = +s[0]\r\n uh = +s[1]\r\n }\r\n\r\n let upscaleNode\r\n let latentNode\r\n\r\n if (hrMethod.startsWith('Latent')) {\r\n latentNode = upscaleNode = LiteGraph.createNode('LatentUpscale')\r\n graph.add(upscaleNode)\r\n samplerNode.connect(0, upscaleNode, 0)\r\n\r\n switch (hrMethod) {\r\n case 'Latent (nearest-exact)':\r\n hrMethod = 'nearest-exact'\r\n break\r\n }\r\n setWidgetValue(upscaleNode, 'upscale_method', hrMethod, true)\r\n } else {\r\n const decode = LiteGraph.createNode('VAEDecodeTiled')\r\n graph.add(decode)\r\n samplerNode.connect(0, decode, 0)\r\n vaeLoaderNode.connect(0, decode, 1)\r\n\r\n const upscaleLoaderNode =\r\n LiteGraph.createNode('UpscaleModelLoader')\r\n graph.add(upscaleLoaderNode)\r\n setWidgetValue(upscaleLoaderNode, 'model_name', hrMethod, true)\r\n\r\n const modelUpscaleNode = LiteGraph.createNode(\r\n 'ImageUpscaleWithModel'\r\n )\r\n graph.add(modelUpscaleNode)\r\n decode.connect(0, modelUpscaleNode, 1)\r\n upscaleLoaderNode.connect(0, modelUpscaleNode, 0)\r\n\r\n upscaleNode = LiteGraph.createNode('ImageScale')\r\n graph.add(upscaleNode)\r\n modelUpscaleNode.connect(0, upscaleNode, 0)\r\n\r\n const vaeEncodeNode = (latentNode =\r\n LiteGraph.createNode('VAEEncodeTiled'))\r\n graph.add(vaeEncodeNode)\r\n upscaleNode.connect(0, vaeEncodeNode, 0)\r\n vaeLoaderNode.connect(0, vaeEncodeNode, 1)\r\n }\r\n\r\n setWidgetValue(upscaleNode, 'width', ceil64(uw))\r\n setWidgetValue(upscaleNode, 'height', ceil64(uh))\r\n\r\n hrSamplerNode = LiteGraph.createNode('KSampler')\r\n graph.add(hrSamplerNode)\r\n ckptNode.connect(0, hrSamplerNode, 0)\r\n positiveNode.connect(0, hrSamplerNode, 1)\r\n negativeNode.connect(0, hrSamplerNode, 2)\r\n latentNode.connect(0, hrSamplerNode, 3)\r\n hrSamplerNode.connect(0, vaeNode, 0)\r\n }\r\n },\r\n steps(v) {\r\n setWidgetValue(samplerNode, 'steps', +v)\r\n },\r\n seed(v) {\r\n setWidgetValue(samplerNode, 'seed', +v)\r\n }\r\n }\r\n\r\n for (const opt in opts) {\r\n if (opt in handlers) {\r\n handlers[opt](popOpt(opt))\r\n }\r\n }\r\n\r\n if (hrSamplerNode) {\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'steps',\r\n hrSteps ? +hrSteps : getWidget(samplerNode, 'steps').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'cfg',\r\n getWidget(samplerNode, 'cfg').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'scheduler',\r\n getWidget(samplerNode, 'scheduler').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'sampler_name',\r\n getWidget(samplerNode, 'sampler_name').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'denoise',\r\n +(popOpt('denoising strength') || '1')\r\n )\r\n }\r\n\r\n let n = createLoraNodes(\r\n positiveNode,\r\n positive,\r\n { node: clipSkipNode, index: 0 },\r\n { node: ckptNode, index: 0 }\r\n )\r\n positive = n.text\r\n n = createLoraNodes(negativeNode, negative, n.prevClip, n.prevModel)\r\n negative = n.text\r\n\r\n setWidgetValue(positiveNode, 'text', replaceEmbeddings(positive))\r\n setWidgetValue(negativeNode, 'text', replaceEmbeddings(negative))\r\n\r\n graph.arrange()\r\n\r\n for (const opt of [\r\n 'model hash',\r\n 'ensd',\r\n 'version',\r\n 'vae hash',\r\n 'ti hashes',\r\n 'lora hashes',\r\n 'hashes'\r\n ]) {\r\n delete opts[opt]\r\n }\r\n\r\n console.warn('Unhandled parameters:', opts)\r\n }\r\n }\r\n}\r\n","import { app } from '../app'\r\nimport { $el } from '../ui'\r\n\r\nexport function calculateImageGrid(imgs, dw, dh) {\r\n let best = 0\r\n let w = imgs[0].naturalWidth\r\n let h = imgs[0].naturalHeight\r\n const numImages = imgs.length\r\n\r\n let cellWidth, cellHeight, cols, rows, shiftX\r\n // compact style\r\n for (let c = 1; c <= numImages; c++) {\r\n const r = Math.ceil(numImages / c)\r\n const cW = dw / c\r\n const cH = dh / r\r\n const scaleX = cW / w\r\n const scaleY = cH / h\r\n\r\n const scale = Math.min(scaleX, scaleY, 1)\r\n const imageW = w * scale\r\n const imageH = h * scale\r\n const area = imageW * imageH * numImages\r\n\r\n if (area > best) {\r\n best = area\r\n cellWidth = imageW\r\n cellHeight = imageH\r\n cols = c\r\n rows = r\r\n shiftX = c * ((cW - imageW) / 2)\r\n }\r\n }\r\n\r\n return { cellWidth, cellHeight, cols, rows, shiftX }\r\n}\r\n\r\nexport function createImageHost(node) {\r\n const el = $el('div.comfy-img-preview')\r\n let currentImgs\r\n let first = true\r\n\r\n function updateSize() {\r\n let w = null\r\n let h = null\r\n\r\n if (currentImgs) {\r\n let elH = el.clientHeight\r\n if (first) {\r\n first = false\r\n // On first run, if we are small then grow a bit\r\n if (elH < 190) {\r\n elH = 190\r\n }\r\n el.style.setProperty('--comfy-widget-min-height', elH.toString())\r\n } else {\r\n el.style.setProperty('--comfy-widget-min-height', null)\r\n }\r\n\r\n const nw = node.size[0]\r\n ;({ cellWidth: w, cellHeight: h } = calculateImageGrid(\r\n currentImgs,\r\n nw - 20,\r\n elH\r\n ))\r\n w += 'px'\r\n h += 'px'\r\n\r\n el.style.setProperty('--comfy-img-preview-width', w)\r\n el.style.setProperty('--comfy-img-preview-height', h)\r\n }\r\n }\r\n return {\r\n el,\r\n updateImages(imgs) {\r\n if (imgs !== currentImgs) {\r\n if (currentImgs == null) {\r\n requestAnimationFrame(() => {\r\n updateSize()\r\n })\r\n }\r\n el.replaceChildren(...imgs)\r\n currentImgs = imgs\r\n node.onResize(node.size)\r\n node.graph.setDirtyCanvas(true, true)\r\n }\r\n },\r\n getHeight() {\r\n updateSize()\r\n },\r\n onDraw() {\r\n // Element from point uses a hittest find elements so we need to toggle pointer events\r\n el.style.pointerEvents = 'all'\r\n const over = document.elementFromPoint(\r\n app.canvas.mouse[0],\r\n app.canvas.mouse[1]\r\n )\r\n el.style.pointerEvents = 'none'\r\n\r\n if (!over) return\r\n // Set the overIndex so Open Image etc work\r\n const idx = currentImgs.indexOf(over)\r\n node.overIndex = idx\r\n }\r\n }\r\n}\r\n","/*\r\n Original implementation:\r\n https://github.com/TahaSh/drag-to-reorder\r\n MIT License\r\n\r\n Copyright (c) 2023 Taha Shashtari\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included in all\r\n copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n SOFTWARE.\r\n*/\r\n\r\nimport { $el } from '../ui'\r\n\r\n$el('style', {\r\n parent: document.head,\r\n textContent: `\r\n .draggable-item {\r\n position: relative;\r\n will-change: transform;\r\n user-select: none;\r\n }\r\n .draggable-item.is-idle {\r\n transition: 0.25s ease transform;\r\n }\r\n .draggable-item.is-draggable {\r\n z-index: 10;\r\n }\r\n `\r\n})\r\n\r\nexport class DraggableList extends EventTarget {\r\n listContainer\r\n draggableItem\r\n pointerStartX\r\n pointerStartY\r\n scrollYMax\r\n itemsGap = 0\r\n items = []\r\n itemSelector\r\n handleClass = 'drag-handle'\r\n off = []\r\n offDrag = []\r\n\r\n constructor(element, itemSelector) {\r\n super()\r\n this.listContainer = element\r\n this.itemSelector = itemSelector\r\n\r\n if (!this.listContainer) return\r\n\r\n this.off.push(this.on(this.listContainer, 'mousedown', this.dragStart))\r\n this.off.push(this.on(this.listContainer, 'touchstart', this.dragStart))\r\n this.off.push(this.on(document, 'mouseup', this.dragEnd))\r\n this.off.push(this.on(document, 'touchend', this.dragEnd))\r\n }\r\n\r\n getAllItems() {\r\n if (!this.items?.length) {\r\n this.items = Array.from(\r\n this.listContainer.querySelectorAll(this.itemSelector)\r\n )\r\n this.items.forEach((element) => {\r\n element.classList.add('is-idle')\r\n })\r\n }\r\n return this.items\r\n }\r\n\r\n getIdleItems() {\r\n return this.getAllItems().filter((item) =>\r\n item.classList.contains('is-idle')\r\n )\r\n }\r\n\r\n isItemAbove(item) {\r\n return item.hasAttribute('data-is-above')\r\n }\r\n\r\n isItemToggled(item) {\r\n return item.hasAttribute('data-is-toggled')\r\n }\r\n\r\n on(source, event, listener, options?) {\r\n listener = listener.bind(this)\r\n source.addEventListener(event, listener, options)\r\n return () => source.removeEventListener(event, listener)\r\n }\r\n\r\n dragStart(e) {\r\n if (e.target.classList.contains(this.handleClass)) {\r\n this.draggableItem = e.target.closest(this.itemSelector)\r\n }\r\n\r\n if (!this.draggableItem) return\r\n\r\n this.pointerStartX = e.clientX || e.touches[0].clientX\r\n this.pointerStartY = e.clientY || e.touches[0].clientY\r\n this.scrollYMax =\r\n this.listContainer.scrollHeight - this.listContainer.clientHeight\r\n\r\n this.setItemsGap()\r\n this.initDraggableItem()\r\n this.initItemsState()\r\n\r\n this.offDrag.push(this.on(document, 'mousemove', this.drag))\r\n this.offDrag.push(\r\n this.on(document, 'touchmove', this.drag, { passive: false })\r\n )\r\n\r\n this.dispatchEvent(\r\n new CustomEvent('dragstart', {\r\n detail: {\r\n element: this.draggableItem,\r\n position: this.getAllItems().indexOf(this.draggableItem)\r\n }\r\n })\r\n )\r\n }\r\n\r\n setItemsGap() {\r\n if (this.getIdleItems().length <= 1) {\r\n this.itemsGap = 0\r\n return\r\n }\r\n\r\n const item1 = this.getIdleItems()[0]\r\n const item2 = this.getIdleItems()[1]\r\n\r\n const item1Rect = item1.getBoundingClientRect()\r\n const item2Rect = item2.getBoundingClientRect()\r\n\r\n this.itemsGap = Math.abs(item1Rect.bottom - item2Rect.top)\r\n }\r\n\r\n initItemsState() {\r\n this.getIdleItems().forEach((item, i) => {\r\n if (this.getAllItems().indexOf(this.draggableItem) > i) {\r\n item.dataset.isAbove = ''\r\n }\r\n })\r\n }\r\n\r\n initDraggableItem() {\r\n this.draggableItem.classList.remove('is-idle')\r\n this.draggableItem.classList.add('is-draggable')\r\n }\r\n\r\n drag(e) {\r\n if (!this.draggableItem) return\r\n\r\n e.preventDefault()\r\n\r\n const clientX = e.clientX || e.touches[0].clientX\r\n const clientY = e.clientY || e.touches[0].clientY\r\n\r\n const listRect = this.listContainer.getBoundingClientRect()\r\n\r\n if (clientY > listRect.bottom) {\r\n if (this.listContainer.scrollTop < this.scrollYMax) {\r\n this.listContainer.scrollBy(0, 10)\r\n this.pointerStartY -= 10\r\n }\r\n } else if (clientY < listRect.top && this.listContainer.scrollTop > 0) {\r\n this.pointerStartY += 10\r\n this.listContainer.scrollBy(0, -10)\r\n }\r\n\r\n const pointerOffsetX = clientX - this.pointerStartX\r\n const pointerOffsetY = clientY - this.pointerStartY\r\n\r\n this.updateIdleItemsStateAndPosition()\r\n this.draggableItem.style.transform = `translate(${pointerOffsetX}px, ${pointerOffsetY}px)`\r\n }\r\n\r\n updateIdleItemsStateAndPosition() {\r\n const draggableItemRect = this.draggableItem.getBoundingClientRect()\r\n const draggableItemY = draggableItemRect.top + draggableItemRect.height / 2\r\n\r\n // Update state\r\n this.getIdleItems().forEach((item) => {\r\n const itemRect = item.getBoundingClientRect()\r\n const itemY = itemRect.top + itemRect.height / 2\r\n if (this.isItemAbove(item)) {\r\n if (draggableItemY <= itemY) {\r\n item.dataset.isToggled = ''\r\n } else {\r\n delete item.dataset.isToggled\r\n }\r\n } else {\r\n if (draggableItemY >= itemY) {\r\n item.dataset.isToggled = ''\r\n } else {\r\n delete item.dataset.isToggled\r\n }\r\n }\r\n })\r\n\r\n // Update position\r\n this.getIdleItems().forEach((item) => {\r\n if (this.isItemToggled(item)) {\r\n const direction = this.isItemAbove(item) ? 1 : -1\r\n item.style.transform = `translateY(${direction * (draggableItemRect.height + this.itemsGap)}px)`\r\n } else {\r\n item.style.transform = ''\r\n }\r\n })\r\n }\r\n\r\n dragEnd() {\r\n if (!this.draggableItem) return\r\n\r\n this.applyNewItemsOrder()\r\n this.cleanup()\r\n }\r\n\r\n applyNewItemsOrder() {\r\n const reorderedItems = []\r\n\r\n let oldPosition = -1\r\n this.getAllItems().forEach((item, index) => {\r\n if (item === this.draggableItem) {\r\n oldPosition = index\r\n return\r\n }\r\n if (!this.isItemToggled(item)) {\r\n reorderedItems[index] = item\r\n return\r\n }\r\n const newIndex = this.isItemAbove(item) ? index + 1 : index - 1\r\n reorderedItems[newIndex] = item\r\n })\r\n\r\n for (let index = 0; index < this.getAllItems().length; index++) {\r\n const item = reorderedItems[index]\r\n if (typeof item === 'undefined') {\r\n reorderedItems[index] = this.draggableItem\r\n }\r\n }\r\n\r\n reorderedItems.forEach((item) => {\r\n this.listContainer.appendChild(item)\r\n })\r\n\r\n this.items = reorderedItems\r\n\r\n this.dispatchEvent(\r\n new CustomEvent('dragend', {\r\n detail: {\r\n element: this.draggableItem,\r\n oldPosition,\r\n newPosition: reorderedItems.indexOf(this.draggableItem)\r\n }\r\n })\r\n )\r\n }\r\n\r\n cleanup() {\r\n this.itemsGap = 0\r\n this.items = []\r\n this.unsetDraggableItem()\r\n this.unsetItemState()\r\n\r\n this.offDrag.forEach((f) => f())\r\n this.offDrag = []\r\n }\r\n\r\n unsetDraggableItem() {\r\n this.draggableItem.style = null\r\n this.draggableItem.classList.remove('is-draggable')\r\n this.draggableItem.classList.add('is-idle')\r\n this.draggableItem = null\r\n }\r\n\r\n unsetItemState() {\r\n this.getIdleItems().forEach((item, i) => {\r\n delete item.dataset.isAbove\r\n delete item.dataset.isToggled\r\n item.style.transform = ''\r\n })\r\n }\r\n\r\n dispose() {\r\n this.off.forEach((f) => f())\r\n }\r\n}\r\n","import { api } from './api'\r\nimport type { ComfyApp } from './app'\r\nimport { $el } from './ui'\r\n\r\n// Simple date formatter\r\nconst parts = {\r\n d: (d) => d.getDate(),\r\n M: (d) => d.getMonth() + 1,\r\n h: (d) => d.getHours(),\r\n m: (d) => d.getMinutes(),\r\n s: (d) => d.getSeconds()\r\n}\r\nconst format =\r\n Object.keys(parts)\r\n .map((k) => k + k + '?')\r\n .join('|') + '|yyy?y?'\r\n\r\nfunction formatDate(text: string, date: Date) {\r\n return text.replace(new RegExp(format, 'g'), (text: string): string => {\r\n if (text === 'yy') return (date.getFullYear() + '').substring(2)\r\n if (text === 'yyyy') return date.getFullYear().toString()\r\n if (text[0] in parts) {\r\n const p = parts[text[0]](date)\r\n return (p + '').padStart(text.length, '0')\r\n }\r\n return text\r\n })\r\n}\r\n\r\nexport function clone(obj) {\r\n try {\r\n if (typeof structuredClone !== 'undefined') {\r\n return structuredClone(obj)\r\n }\r\n } catch (error) {\r\n // structuredClone is stricter than using JSON.parse/stringify so fallback to that\r\n }\r\n\r\n return JSON.parse(JSON.stringify(obj))\r\n}\r\n\r\nexport function applyTextReplacements(app: ComfyApp, value: string): string {\r\n return value.replace(/%([^%]+)%/g, function (match, text) {\r\n const split = text.split('.')\r\n if (split.length !== 2) {\r\n // Special handling for dates\r\n if (split[0].startsWith('date:')) {\r\n return formatDate(split[0].substring(5), new Date())\r\n }\r\n\r\n if (text !== 'width' && text !== 'height') {\r\n // Dont warn on standard replacements\r\n console.warn('Invalid replacement pattern', text)\r\n }\r\n return match\r\n }\r\n\r\n // Find node with matching S&R property name\r\n // @ts-expect-error\r\n let nodes = app.graph._nodes.filter(\r\n (n) => n.properties?.['Node name for S&R'] === split[0]\r\n )\r\n // If we cant, see if there is a node with that title\r\n if (!nodes.length) {\r\n // @ts-expect-error\r\n nodes = app.graph._nodes.filter((n) => n.title === split[0])\r\n }\r\n if (!nodes.length) {\r\n console.warn('Unable to find node', split[0])\r\n return match\r\n }\r\n\r\n if (nodes.length > 1) {\r\n console.warn('Multiple nodes matched', split[0], 'using first match')\r\n }\r\n\r\n const node = nodes[0]\r\n\r\n const widget = node.widgets?.find((w) => w.name === split[1])\r\n if (!widget) {\r\n console.warn('Unable to find widget', split[1], 'on node', split[0], node)\r\n return match\r\n }\r\n\r\n return ((widget.value ?? '') + '').replaceAll(/\\/|\\\\/g, '_')\r\n })\r\n}\r\n\r\nexport async function addStylesheet(\r\n urlOrFile: string,\r\n relativeTo?: string\r\n): Promise {\r\n return new Promise((res, rej) => {\r\n let url\r\n if (urlOrFile.endsWith('.js')) {\r\n url = urlOrFile.substr(0, urlOrFile.length - 2) + 'css'\r\n } else {\r\n url = new URL(\r\n urlOrFile,\r\n relativeTo ?? `${window.location.protocol}//${window.location.host}`\r\n ).toString()\r\n }\r\n $el('link', {\r\n parent: document.head,\r\n rel: 'stylesheet',\r\n type: 'text/css',\r\n href: url,\r\n onload: res,\r\n onerror: rej\r\n })\r\n })\r\n}\r\n\r\n/**\r\n * @param { string } filename\r\n * @param { Blob } blob\r\n */\r\nexport function downloadBlob(filename, blob) {\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n}\r\n\r\nexport function prop(\r\n target: object,\r\n name: string,\r\n defaultValue: T,\r\n onChanged?: (\r\n currentValue: T,\r\n previousValue: T,\r\n target: object,\r\n name: string\r\n ) => void\r\n): T {\r\n let currentValue\r\n Object.defineProperty(target, name, {\r\n get() {\r\n return currentValue\r\n },\r\n set(newValue) {\r\n const prevValue = currentValue\r\n currentValue = newValue\r\n onChanged?.(currentValue, prevValue, target, name)\r\n }\r\n })\r\n return defaultValue\r\n}\r\n\r\nexport function getStorageValue(id) {\r\n const clientId = api.clientId ?? api.initialClientId\r\n return (\r\n (clientId && sessionStorage.getItem(`${id}:${clientId}`)) ??\r\n localStorage.getItem(id)\r\n )\r\n}\r\n\r\nexport function setStorageValue(id, value) {\r\n const clientId = api.clientId ?? api.initialClientId\r\n if (clientId) {\r\n sessionStorage.setItem(`${id}:${clientId}`, value)\r\n }\r\n localStorage.setItem(id, value)\r\n}\r\n","type RGB = { r: number; g: number; b: number }\r\ntype HSL = { h: number; s: number; l: number }\r\n\r\nfunction rgbToHsl({ r, g, b }: RGB): HSL {\r\n r /= 255\r\n g /= 255\r\n b /= 255\r\n const max = Math.max(r, g, b),\r\n min = Math.min(r, g, b)\r\n let h: number, s: number\r\n const l: number = (max + min) / 2\r\n\r\n if (max === min) {\r\n h = s = 0 // achromatic\r\n } else {\r\n const d = max - min\r\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\r\n switch (max) {\r\n case r:\r\n h = (g - b) / d + (g < b ? 6 : 0)\r\n break\r\n case g:\r\n h = (b - r) / d + 2\r\n break\r\n case b:\r\n h = (r - g) / d + 4\r\n break\r\n }\r\n h /= 6\r\n }\r\n\r\n return { h, s, l }\r\n}\r\n\r\nfunction hslToRgb({ h, s, l }: HSL): RGB {\r\n let r: number, g: number, b: number\r\n\r\n if (s === 0) {\r\n r = g = b = l // achromatic\r\n } else {\r\n const hue2rgb = (p: number, q: number, t: number) => {\r\n if (t < 0) t += 1\r\n if (t > 1) t -= 1\r\n if (t < 1 / 6) return p + (q - p) * 6 * t\r\n if (t < 1 / 2) return q\r\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6\r\n return p\r\n }\r\n\r\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s\r\n const p = 2 * l - q\r\n r = hue2rgb(p, q, h + 1 / 3)\r\n g = hue2rgb(p, q, h)\r\n b = hue2rgb(p, q, h - 1 / 3)\r\n }\r\n\r\n return {\r\n r: Math.round(r * 255),\r\n g: Math.round(g * 255),\r\n b: Math.round(b * 255)\r\n }\r\n}\r\n\r\nfunction hexToRgb(hex: string): RGB {\r\n let r = 0,\r\n g = 0,\r\n b = 0\r\n // 3 digits\r\n if (hex.length == 4) {\r\n r = parseInt(hex[1] + hex[1], 16)\r\n g = parseInt(hex[2] + hex[2], 16)\r\n b = parseInt(hex[3] + hex[3], 16)\r\n }\r\n // 6 digits\r\n else if (hex.length == 7) {\r\n r = parseInt(hex.slice(1, 3), 16)\r\n g = parseInt(hex.slice(3, 5), 16)\r\n b = parseInt(hex.slice(5, 7), 16)\r\n }\r\n return { r, g, b }\r\n}\r\n\r\nfunction rgbToHex({ r, g, b }: RGB): string {\r\n return (\r\n '#' +\r\n [r, g, b]\r\n .map((x) => {\r\n const hex = x.toString(16)\r\n return hex.length === 1 ? '0' + hex : hex\r\n })\r\n .join('')\r\n )\r\n}\r\n\r\nexport function lightenColor(hex: string, amount: number): string {\r\n let rgb = hexToRgb(hex)\r\n const hsl = rgbToHsl(rgb)\r\n hsl.l = Math.min(1, hsl.l + amount)\r\n rgb = hslToRgb(hsl)\r\n return rgbToHex(rgb)\r\n}\r\n","export type ClassList = string | string[] | Record\r\n\r\nexport function applyClasses(\r\n element: HTMLElement,\r\n classList: ClassList,\r\n ...requiredClasses: string[]\r\n) {\r\n classList ??= ''\r\n\r\n let str: string\r\n if (typeof classList === 'string') {\r\n str = classList\r\n } else if (classList instanceof Array) {\r\n str = classList.join(' ')\r\n } else {\r\n str = Object.entries(classList).reduce((p, c) => {\r\n if (c[1]) {\r\n p += (p.length ? ' ' : '') + c[0]\r\n }\r\n return p\r\n }, '')\r\n }\r\n element.className = str\r\n if (requiredClasses) {\r\n element.classList.add(...requiredClasses)\r\n }\r\n}\r\n\r\nexport function toggleElement(\r\n element: HTMLElement,\r\n {\r\n onHide,\r\n onShow\r\n }: {\r\n onHide?: (el: HTMLElement) => void\r\n onShow?: (el: HTMLElement, value) => void\r\n } = {}\r\n) {\r\n let placeholder: HTMLElement | Comment\r\n let hidden: boolean\r\n return (value) => {\r\n if (value) {\r\n if (hidden) {\r\n hidden = false\r\n placeholder.replaceWith(element)\r\n }\r\n onShow?.(element, value)\r\n } else {\r\n if (!placeholder) {\r\n placeholder = document.createComment('')\r\n }\r\n hidden = true\r\n element.replaceWith(placeholder)\r\n onHide?.(element)\r\n }\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { applyClasses, ClassList, toggleElement } from '../utils'\r\nimport { prop } from '../../utils'\r\nimport type { ComfyPopup } from './popup'\r\nimport type { ComfyComponent } from '.'\r\nimport type { ComfyApp } from '@/scripts/app'\r\nimport { Settings } from '@/types/apiTypes'\r\n\r\ntype ComfyButtonProps = {\r\n icon?: string\r\n overIcon?: string\r\n iconSize?: number\r\n content?: string | HTMLElement\r\n tooltip?: string\r\n enabled?: boolean\r\n action?: (e: Event, btn: ComfyButton) => void\r\n classList?: ClassList\r\n visibilitySetting?: { id: keyof Settings; showValue: boolean }\r\n app?: ComfyApp\r\n}\r\n\r\nexport class ComfyButton implements ComfyComponent {\r\n #over = 0\r\n #popupOpen = false\r\n isOver = false\r\n iconElement = $el('i.mdi')\r\n contentElement = $el('span')\r\n popup: ComfyPopup\r\n element: HTMLElement\r\n overIcon: string\r\n iconSize: number\r\n content: string | HTMLElement\r\n icon: string\r\n tooltip: string\r\n classList: ClassList\r\n hidden: boolean\r\n enabled: boolean\r\n action: (e: Event, btn: ComfyButton) => void\r\n\r\n constructor({\r\n icon,\r\n overIcon,\r\n iconSize,\r\n content,\r\n tooltip,\r\n action,\r\n classList = 'comfyui-button',\r\n visibilitySetting,\r\n app,\r\n enabled = true\r\n }: ComfyButtonProps) {\r\n this.element = $el(\r\n 'button',\r\n {\r\n onmouseenter: () => {\r\n this.isOver = true\r\n if (this.overIcon) {\r\n this.updateIcon()\r\n }\r\n },\r\n onmouseleave: () => {\r\n this.isOver = false\r\n if (this.overIcon) {\r\n this.updateIcon()\r\n }\r\n }\r\n },\r\n [this.iconElement, this.contentElement]\r\n )\r\n\r\n this.icon = prop(\r\n this,\r\n 'icon',\r\n icon,\r\n toggleElement(this.iconElement, { onShow: this.updateIcon })\r\n )\r\n this.overIcon = prop(this, 'overIcon', overIcon, () => {\r\n if (this.isOver) {\r\n this.updateIcon()\r\n }\r\n })\r\n this.iconSize = prop(this, 'iconSize', iconSize, this.updateIcon)\r\n this.content = prop(\r\n this,\r\n 'content',\r\n content,\r\n toggleElement(this.contentElement, {\r\n onShow: (el, v) => {\r\n if (typeof v === 'string') {\r\n el.textContent = v\r\n } else {\r\n el.replaceChildren(v)\r\n }\r\n }\r\n })\r\n )\r\n\r\n this.tooltip = prop(this, 'tooltip', tooltip, (v) => {\r\n if (v) {\r\n this.element.title = v\r\n } else {\r\n this.element.removeAttribute('title')\r\n }\r\n })\r\n this.classList = prop(this, 'classList', classList, this.updateClasses)\r\n this.hidden = prop(this, 'hidden', false, this.updateClasses)\r\n this.enabled = prop(this, 'enabled', enabled, () => {\r\n this.updateClasses()\r\n ;(this.element as HTMLButtonElement).disabled = !this.enabled\r\n })\r\n this.action = prop(this, 'action', action)\r\n this.element.addEventListener('click', (e) => {\r\n if (this.popup) {\r\n // we are either a touch device or triggered by click not hover\r\n if (!this.#over) {\r\n this.popup.toggle()\r\n }\r\n }\r\n this.action?.(e, this)\r\n })\r\n\r\n if (visibilitySetting?.id) {\r\n const settingUpdated = () => {\r\n this.hidden =\r\n app.ui.settings.getSettingValue(visibilitySetting.id) !==\r\n visibilitySetting.showValue\r\n }\r\n app.ui.settings.addEventListener(\r\n visibilitySetting.id + '.change',\r\n settingUpdated\r\n )\r\n settingUpdated()\r\n }\r\n }\r\n\r\n updateIcon = () =>\r\n (this.iconElement.className = `mdi mdi-${(this.isOver && this.overIcon) || this.icon}${this.iconSize ? ' mdi-' + this.iconSize + 'px' : ''}`)\r\n updateClasses = () => {\r\n const internalClasses = []\r\n if (this.hidden) {\r\n internalClasses.push('hidden')\r\n }\r\n if (!this.enabled) {\r\n internalClasses.push('disabled')\r\n }\r\n if (this.popup) {\r\n if (this.#popupOpen) {\r\n internalClasses.push('popup-open')\r\n } else {\r\n internalClasses.push('popup-closed')\r\n }\r\n }\r\n applyClasses(this.element, this.classList, ...internalClasses)\r\n }\r\n\r\n withPopup(popup: ComfyPopup, mode: 'click' | 'hover' = 'click') {\r\n this.popup = popup\r\n\r\n if (mode === 'hover') {\r\n for (const el of [this.element, this.popup.element]) {\r\n el.addEventListener('mouseenter', () => {\r\n this.popup.open = !!++this.#over\r\n })\r\n el.addEventListener('mouseleave', () => {\r\n this.popup.open = !!--this.#over\r\n })\r\n }\r\n }\r\n\r\n popup.addEventListener('change', () => {\r\n this.#popupOpen = popup.open\r\n this.updateClasses()\r\n })\r\n\r\n return this\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { ComfyButton } from './button'\r\nimport { prop } from '../../utils'\r\n\r\nexport class ComfyButtonGroup {\r\n element = $el('div.comfyui-button-group')\r\n buttons: (HTMLElement | ComfyButton)[]\r\n\r\n constructor(...buttons: (HTMLElement | ComfyButton)[]) {\r\n this.buttons = prop(this, 'buttons', buttons, () => this.update())\r\n }\r\n\r\n insert(button: ComfyButton, index: number) {\r\n this.buttons.splice(index, 0, button)\r\n this.update()\r\n }\r\n\r\n append(button: ComfyButton) {\r\n this.buttons.push(button)\r\n this.update()\r\n }\r\n\r\n remove(indexOrButton: ComfyButton | number) {\r\n if (typeof indexOrButton !== 'number') {\r\n indexOrButton = this.buttons.indexOf(indexOrButton)\r\n }\r\n if (indexOrButton > -1) {\r\n const r = this.buttons.splice(indexOrButton, 1)\r\n this.update()\r\n return r\r\n }\r\n }\r\n\r\n update() {\r\n this.element.replaceChildren(...this.buttons.map((b) => b['element'] ?? b))\r\n }\r\n}\r\n","import { prop } from '../../utils'\r\nimport { $el } from '../../ui'\r\nimport { applyClasses, ClassList } from '../utils'\r\n\r\nexport class ComfyPopup extends EventTarget {\r\n element = $el('div.comfyui-popup')\r\n open: boolean\r\n children: HTMLElement[]\r\n target: HTMLElement\r\n ignoreTarget: boolean\r\n container: HTMLElement\r\n position: string\r\n closeOnEscape: boolean\r\n horizontal: string\r\n classList: ClassList\r\n\r\n constructor(\r\n {\r\n target,\r\n container = document.body,\r\n classList = '',\r\n ignoreTarget = true,\r\n closeOnEscape = true,\r\n position = 'absolute',\r\n horizontal = 'left'\r\n }: {\r\n target: HTMLElement\r\n container?: HTMLElement\r\n classList?: ClassList\r\n ignoreTarget?: boolean\r\n closeOnEscape?: boolean\r\n position?: 'absolute' | 'relative'\r\n horizontal?: 'left' | 'right'\r\n },\r\n ...children: HTMLElement[]\r\n ) {\r\n super()\r\n this.target = target\r\n this.ignoreTarget = ignoreTarget\r\n this.container = container\r\n this.position = position\r\n this.closeOnEscape = closeOnEscape\r\n this.horizontal = horizontal\r\n\r\n container.append(this.element)\r\n\r\n this.children = prop(this, 'children', children, () => {\r\n this.element.replaceChildren(...this.children)\r\n this.update()\r\n })\r\n this.classList = prop(this, 'classList', classList, () =>\r\n applyClasses(this.element, this.classList, 'comfyui-popup', horizontal)\r\n )\r\n this.open = prop(this, 'open', false, (v, o) => {\r\n if (v === o) return\r\n if (v) {\r\n this.#show()\r\n } else {\r\n this.#hide()\r\n }\r\n })\r\n }\r\n\r\n toggle() {\r\n this.open = !this.open\r\n }\r\n\r\n #hide() {\r\n this.element.classList.remove('open')\r\n window.removeEventListener('resize', this.update)\r\n window.removeEventListener('click', this.#clickHandler, { capture: true })\r\n window.removeEventListener('keydown', this.#escHandler, { capture: true })\r\n\r\n this.dispatchEvent(new CustomEvent('close'))\r\n this.dispatchEvent(new CustomEvent('change'))\r\n }\r\n\r\n #show() {\r\n this.element.classList.add('open')\r\n this.update()\r\n\r\n window.addEventListener('resize', this.update)\r\n window.addEventListener('click', this.#clickHandler, { capture: true })\r\n if (this.closeOnEscape) {\r\n window.addEventListener('keydown', this.#escHandler, { capture: true })\r\n }\r\n\r\n this.dispatchEvent(new CustomEvent('open'))\r\n this.dispatchEvent(new CustomEvent('change'))\r\n }\r\n\r\n #escHandler = (e) => {\r\n if (e.key === 'Escape') {\r\n this.open = false\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n }\r\n }\r\n\r\n #clickHandler = (e) => {\r\n /** @type {any} */\r\n const target = e.target\r\n if (\r\n !this.element.contains(target) &&\r\n this.ignoreTarget &&\r\n !this.target.contains(target)\r\n ) {\r\n this.open = false\r\n }\r\n }\r\n\r\n update = () => {\r\n const rect = this.target.getBoundingClientRect()\r\n this.element.style.setProperty('--bottom', 'unset')\r\n if (this.position === 'absolute') {\r\n if (this.horizontal === 'left') {\r\n this.element.style.setProperty('--left', rect.left + 'px')\r\n } else {\r\n this.element.style.setProperty(\r\n '--left',\r\n rect.right - this.element.clientWidth + 'px'\r\n )\r\n }\r\n this.element.style.setProperty('--top', rect.bottom + 'px')\r\n this.element.style.setProperty('--limit', rect.bottom + 'px')\r\n } else {\r\n this.element.style.setProperty('--left', 0 + 'px')\r\n this.element.style.setProperty('--top', rect.height + 'px')\r\n this.element.style.setProperty('--limit', rect.height + 'px')\r\n }\r\n\r\n const thisRect = this.element.getBoundingClientRect()\r\n if (thisRect.height < 30) {\r\n // Move up instead\r\n this.element.style.setProperty('--top', 'unset')\r\n this.element.style.setProperty('--bottom', rect.height + 5 + 'px')\r\n this.element.style.setProperty('--limit', rect.height + 5 + 'px')\r\n }\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { ComfyButton } from './button'\r\nimport { prop } from '../../utils'\r\nimport { ComfyPopup } from './popup'\r\n\r\nexport class ComfySplitButton {\r\n arrow: ComfyButton\r\n element: HTMLElement\r\n popup: ComfyPopup\r\n items: Array\r\n\r\n constructor(\r\n {\r\n primary,\r\n mode,\r\n horizontal = 'left',\r\n position = 'relative'\r\n }: {\r\n primary: ComfyButton\r\n mode?: 'hover' | 'click'\r\n horizontal?: 'left' | 'right'\r\n position?: 'relative' | 'absolute'\r\n },\r\n ...items: Array\r\n ) {\r\n this.arrow = new ComfyButton({\r\n icon: 'chevron-down'\r\n })\r\n this.element = $el(\r\n 'div.comfyui-split-button' + (mode === 'hover' ? '.hover' : ''),\r\n [\r\n $el('div.comfyui-split-primary', primary.element),\r\n $el('div.comfyui-split-arrow', this.arrow.element)\r\n ]\r\n )\r\n this.popup = new ComfyPopup({\r\n target: this.element,\r\n container: position === 'relative' ? this.element : document.body,\r\n classList:\r\n 'comfyui-split-button-popup' + (mode === 'hover' ? ' hover' : ''),\r\n closeOnEscape: mode === 'click',\r\n position,\r\n horizontal\r\n })\r\n\r\n this.arrow.withPopup(this.popup, mode)\r\n\r\n this.items = prop(this, 'items', items, () => this.update())\r\n }\r\n\r\n update() {\r\n this.popup.element.replaceChildren(\r\n ...this.items.map((b) => ('element' in b ? b.element : b))\r\n )\r\n }\r\n}\r\n","import type { ComfyApp } from '@/scripts/app'\r\nimport { $el } from '../../ui'\r\nimport { prop } from '../../utils'\r\n\r\nexport class ComfyQueueOptions extends EventTarget {\r\n element = $el('div.comfyui-queue-options')\r\n app: ComfyApp\r\n batchCountInput: HTMLInputElement\r\n batchCount: number\r\n batchCountRange: HTMLInputElement\r\n autoQueueMode: string\r\n autoQueueEl: HTMLElement\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n this.app = app\r\n\r\n this.batchCountInput = $el('input', {\r\n className: 'comfyui-queue-batch-value',\r\n type: 'number',\r\n min: '1',\r\n value: '1',\r\n oninput: () => (this.batchCount = +this.batchCountInput.value)\r\n })\r\n\r\n this.batchCountRange = $el('input', {\r\n type: 'range',\r\n min: '1',\r\n max: '100',\r\n value: '1',\r\n oninput: () => (this.batchCount = +this.batchCountRange.value)\r\n })\r\n\r\n this.element.append(\r\n $el('div.comfyui-queue-batch', [\r\n $el(\r\n 'label',\r\n {\r\n textContent: 'Batch count: '\r\n },\r\n this.batchCountInput\r\n ),\r\n this.batchCountRange\r\n ])\r\n )\r\n\r\n const createOption = (text, value, checked = false) =>\r\n $el(\r\n 'label',\r\n { textContent: text },\r\n $el('input', {\r\n type: 'radio',\r\n name: 'AutoQueueMode',\r\n checked,\r\n value,\r\n oninput: (e) => (this.autoQueueMode = e.target['value'])\r\n })\r\n )\r\n\r\n this.autoQueueEl = $el('div.comfyui-queue-mode', [\r\n $el('span', 'Auto Queue:'),\r\n createOption('Disabled', '', true),\r\n createOption('Instant', 'instant'),\r\n createOption('On Change', 'change')\r\n ])\r\n\r\n this.element.append(this.autoQueueEl)\r\n\r\n this.batchCount = prop(this, 'batchCount', 1, () => {\r\n this.batchCountInput.value = this.batchCount + ''\r\n this.batchCountRange.value = this.batchCount + ''\r\n })\r\n\r\n this.autoQueueMode = prop(this, 'autoQueueMode', 'Disabled', () => {\r\n this.dispatchEvent(\r\n new CustomEvent('autoQueueMode', {\r\n detail: this.autoQueueMode\r\n })\r\n )\r\n })\r\n }\r\n}\r\n","import { ComfyButton } from '../components/button'\r\nimport { $el } from '../../ui'\r\nimport { api } from '../../api'\r\nimport { ComfySplitButton } from '../components/splitButton'\r\nimport { ComfyQueueOptions } from './queueOptions'\r\nimport { prop } from '../../utils'\r\nimport type { ComfyApp } from '@/scripts/app'\r\nimport { StatusWsMessageStatus } from '@/types/apiTypes'\r\n\r\nexport class ComfyQueueButton {\r\n element = $el('div.comfyui-queue-button')\r\n #internalQueueSize = 0\r\n\r\n queuePrompt = async (e?: MouseEvent) => {\r\n this.#internalQueueSize += this.queueOptions.batchCount\r\n // Hold shift to queue front, event is undefined when auto-queue is enabled\r\n await this.app.queuePrompt(\r\n e?.shiftKey ? -1 : 0,\r\n this.queueOptions.batchCount\r\n )\r\n }\r\n queueOptions: ComfyQueueOptions\r\n app: ComfyApp\r\n autoQueueMode: string\r\n graphHasChanged: boolean\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n\r\n const queue = new ComfyButton({\r\n content: $el('div', [\r\n $el('span', {\r\n textContent: 'Queue'\r\n })\r\n ]),\r\n icon: 'play',\r\n classList: 'comfyui-button',\r\n action: this.queuePrompt\r\n })\r\n\r\n this.queueOptions = new ComfyQueueOptions(app)\r\n\r\n const btn = new ComfySplitButton(\r\n {\r\n primary: queue,\r\n mode: 'click',\r\n position: 'absolute',\r\n horizontal: 'right'\r\n },\r\n this.queueOptions.element\r\n )\r\n btn.element.classList.add('primary')\r\n this.element.append(btn.element)\r\n\r\n this.autoQueueMode = prop(this, 'autoQueueMode', '', () => {\r\n switch (this.autoQueueMode) {\r\n case 'instant':\r\n queue.icon = 'infinity'\r\n break\r\n case 'change':\r\n queue.icon = 'auto-mode'\r\n break\r\n default:\r\n queue.icon = 'play'\r\n break\r\n }\r\n })\r\n\r\n this.queueOptions.addEventListener(\r\n 'autoQueueMode',\r\n (e) => (this.autoQueueMode = e['detail'])\r\n )\r\n\r\n api.addEventListener('graphChanged', () => {\r\n if (this.autoQueueMode === 'change') {\r\n if (this.#internalQueueSize) {\r\n this.graphHasChanged = true\r\n } else {\r\n this.graphHasChanged = false\r\n this.queuePrompt()\r\n }\r\n }\r\n })\r\n\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n this.#internalQueueSize = detail?.exec_info?.queue_remaining\r\n if (this.#internalQueueSize != null) {\r\n if (!this.#internalQueueSize && !app.lastExecutionError) {\r\n if (\r\n this.autoQueueMode === 'instant' ||\r\n (this.autoQueueMode === 'change' && this.graphHasChanged)\r\n ) {\r\n this.graphHasChanged = false\r\n this.queuePrompt()\r\n }\r\n }\r\n }\r\n }\r\n )\r\n }\r\n}\r\n","import './spinner.css'\r\n\r\nexport function createSpinner() {\r\n const div = document.createElement('div')\r\n div.innerHTML = `
`\r\n return div.firstElementChild\r\n}\r\n","import type { ComfyApp } from './app'\r\nimport { api } from './api'\r\nimport { clone } from './utils'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\nimport { ComfyWorkflow } from './workflows'\r\n\r\nexport class ChangeTracker {\r\n static MAX_HISTORY = 50\r\n #app: ComfyApp\r\n undo = []\r\n redo = []\r\n activeState = null\r\n isOurLoad = false\r\n workflow: ComfyWorkflow | null\r\n\r\n ds: { scale: number; offset: [number, number] }\r\n nodeOutputs: any\r\n\r\n get app() {\r\n return this.#app ?? this.workflow.manager.app\r\n }\r\n\r\n constructor(workflow: ComfyWorkflow) {\r\n this.workflow = workflow\r\n }\r\n\r\n #setApp(app) {\r\n this.#app = app\r\n }\r\n\r\n store() {\r\n this.ds = {\r\n scale: this.app.canvas.ds.scale,\r\n offset: [...this.app.canvas.ds.offset]\r\n }\r\n }\r\n\r\n restore() {\r\n if (this.ds) {\r\n this.app.canvas.ds.scale = this.ds.scale\r\n this.app.canvas.ds.offset = this.ds.offset\r\n }\r\n if (this.nodeOutputs) {\r\n this.app.nodeOutputs = this.nodeOutputs\r\n }\r\n }\r\n\r\n checkState() {\r\n if (!this.app.graph) return\r\n\r\n const currentState = this.app.graph.serialize()\r\n if (!this.activeState) {\r\n this.activeState = clone(currentState)\r\n return\r\n }\r\n if (!ChangeTracker.graphEqual(this.activeState, currentState)) {\r\n this.undo.push(this.activeState)\r\n if (this.undo.length > ChangeTracker.MAX_HISTORY) {\r\n this.undo.shift()\r\n }\r\n this.activeState = clone(currentState)\r\n this.redo.length = 0\r\n this.workflow.unsaved = true\r\n api.dispatchEvent(\r\n new CustomEvent('graphChanged', { detail: this.activeState })\r\n )\r\n }\r\n }\r\n\r\n async updateState(source, target) {\r\n const prevState = source.pop()\r\n if (prevState) {\r\n target.push(this.activeState)\r\n this.isOurLoad = true\r\n await this.app.loadGraphData(prevState, false, false, this.workflow)\r\n this.activeState = prevState\r\n }\r\n }\r\n\r\n async undoRedo(e) {\r\n if (e.ctrlKey || e.metaKey) {\r\n if (e.key === 'y') {\r\n this.updateState(this.redo, this.undo)\r\n return true\r\n } else if (e.key === 'z') {\r\n this.updateState(this.undo, this.redo)\r\n return true\r\n }\r\n }\r\n }\r\n\r\n static init(app: ComfyApp) {\r\n const changeTracker = () =>\r\n app.workflowManager.activeWorkflow?.changeTracker ?? globalTracker\r\n globalTracker.#setApp(app)\r\n\r\n const loadGraphData = app.loadGraphData\r\n app.loadGraphData = async function () {\r\n const v = await loadGraphData.apply(this, arguments)\r\n const ct = changeTracker()\r\n if (ct.isOurLoad) {\r\n ct.isOurLoad = false\r\n } else {\r\n ct.checkState()\r\n }\r\n return v\r\n }\r\n\r\n let keyIgnored = false\r\n window.addEventListener(\r\n 'keydown',\r\n (e) => {\r\n const activeEl = document.activeElement\r\n requestAnimationFrame(async () => {\r\n let bindInputEl\r\n // If we are auto queue in change mode then we do want to trigger on inputs\r\n if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === 'instant') {\r\n if (\r\n activeEl?.tagName === 'INPUT' ||\r\n activeEl?.['type'] === 'textarea'\r\n ) {\r\n // Ignore events on inputs, they have their native history\r\n return\r\n }\r\n bindInputEl = activeEl\r\n }\r\n\r\n keyIgnored =\r\n e.key === 'Control' ||\r\n e.key === 'Shift' ||\r\n e.key === 'Alt' ||\r\n e.key === 'Meta'\r\n if (keyIgnored) return\r\n\r\n // Check if this is a ctrl+z ctrl+y\r\n if (await changeTracker().undoRedo(e)) return\r\n\r\n // If our active element is some type of input then handle changes after they're done\r\n if (ChangeTracker.bindInput(app, bindInputEl)) return\r\n changeTracker().checkState()\r\n })\r\n },\r\n true\r\n )\r\n\r\n window.addEventListener('keyup', (e) => {\r\n if (keyIgnored) {\r\n keyIgnored = false\r\n changeTracker().checkState()\r\n }\r\n })\r\n\r\n // Handle clicking DOM elements (e.g. widgets)\r\n window.addEventListener('mouseup', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n // Handle prompt queue event for dynamic widget changes\r\n api.addEventListener('promptQueued', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n api.addEventListener('graphCleared', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n // Handle litegraph clicks\r\n const processMouseUp = LGraphCanvas.prototype.processMouseUp\r\n LGraphCanvas.prototype.processMouseUp = function (e) {\r\n const v = processMouseUp.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n const processMouseDown = LGraphCanvas.prototype.processMouseDown\r\n LGraphCanvas.prototype.processMouseDown = function (e) {\r\n const v = processMouseDown.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n\r\n // Handle litegraph context menu for COMBO widgets\r\n const close = LiteGraph.ContextMenu.prototype.close\r\n LiteGraph.ContextMenu.prototype.close = function (e) {\r\n const v = close.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n\r\n // Detects nodes being added via the node search dialog\r\n const onNodeAdded = LiteGraph.LGraph.prototype.onNodeAdded\r\n LiteGraph.LGraph.prototype.onNodeAdded = function () {\r\n const v = onNodeAdded?.apply(this, arguments)\r\n if (!app?.configuringGraph) {\r\n const ct = changeTracker()\r\n if (!ct.isOurLoad) {\r\n ct.checkState()\r\n }\r\n }\r\n return v\r\n }\r\n\r\n // Store node outputs\r\n api.addEventListener('executed', ({ detail }) => {\r\n const prompt = app.workflowManager.queuedPrompts[detail.prompt_id]\r\n if (!prompt?.workflow) return\r\n const nodeOutputs = (prompt.workflow.changeTracker.nodeOutputs ??= {})\r\n const output = nodeOutputs[detail.node]\r\n if (detail.merge && output) {\r\n for (const k in detail.output ?? {}) {\r\n const v = output[k]\r\n if (v instanceof Array) {\r\n output[k] = v.concat(detail.output[k])\r\n } else {\r\n output[k] = detail.output[k]\r\n }\r\n }\r\n } else {\r\n nodeOutputs[detail.node] = detail.output\r\n }\r\n })\r\n }\r\n\r\n static bindInput(app, activeEl) {\r\n if (\r\n activeEl &&\r\n activeEl.tagName !== 'CANVAS' &&\r\n activeEl.tagName !== 'BODY'\r\n ) {\r\n for (const evt of ['change', 'input', 'blur']) {\r\n if (`on${evt}` in activeEl) {\r\n const listener = () => {\r\n app.workflowManager.activeWorkflow.changeTracker.checkState()\r\n activeEl.removeEventListener(evt, listener)\r\n }\r\n activeEl.addEventListener(evt, listener)\r\n return true\r\n }\r\n }\r\n }\r\n }\r\n\r\n static graphEqual(a, b, path = '') {\r\n if (a === b) return true\r\n\r\n if (typeof a == 'object' && a && typeof b == 'object' && b) {\r\n const keys = Object.getOwnPropertyNames(a)\r\n\r\n if (keys.length != Object.getOwnPropertyNames(b).length) {\r\n return false\r\n }\r\n\r\n for (const key of keys) {\r\n let av = a[key]\r\n let bv = b[key]\r\n if (!path && key === 'nodes') {\r\n // Nodes need to be sorted as the order changes when selecting nodes\r\n av = [...av].sort((a, b) => a.id - b.id)\r\n bv = [...bv].sort((a, b) => a.id - b.id)\r\n } else if (path === 'extra.ds') {\r\n // Ignore view changes\r\n continue\r\n }\r\n if (!ChangeTracker.graphEqual(av, bv, path + (path ? '.' : '') + key)) {\r\n return false\r\n }\r\n }\r\n\r\n return true\r\n }\r\n\r\n return false\r\n }\r\n}\r\n\r\nconst globalTracker = new ChangeTracker({} as ComfyWorkflow)\r\n","import { ComfyDialog } from '../dialog'\r\nimport { $el } from '../../ui'\r\n\r\nexport class ComfyAsyncDialog extends ComfyDialog {\r\n #resolve: (value: any) => void\r\n\r\n constructor(actions?: Array) {\r\n super(\r\n 'dialog.comfy-dialog.comfyui-dialog',\r\n actions?.map((opt) => {\r\n if (typeof opt === 'string') {\r\n opt = { text: opt }\r\n }\r\n return $el('button.comfyui-button', {\r\n type: 'button',\r\n textContent: opt.text,\r\n onclick: () => this.close(opt.value ?? opt.text)\r\n })\r\n })\r\n )\r\n }\r\n\r\n show(html: string | HTMLElement | HTMLElement[]) {\r\n this.element.addEventListener('close', () => {\r\n this.close()\r\n })\r\n\r\n super.show(html)\r\n\r\n return new Promise((resolve) => {\r\n this.#resolve = resolve\r\n })\r\n }\r\n\r\n showModal(html: string | HTMLElement | HTMLElement[]) {\r\n this.element.addEventListener('close', () => {\r\n this.close()\r\n })\r\n\r\n super.show(html)\r\n this.element.showModal()\r\n\r\n return new Promise((resolve) => {\r\n this.#resolve = resolve\r\n })\r\n }\r\n\r\n close(result = null) {\r\n this.#resolve(result)\r\n this.element.close()\r\n super.close()\r\n }\r\n\r\n static async prompt({ title = null, message, actions }) {\r\n const dialog = new ComfyAsyncDialog(actions)\r\n const content = [$el('span', message)]\r\n if (title) {\r\n content.unshift($el('h3', title))\r\n }\r\n const res = await dialog.showModal(content)\r\n dialog.element.remove()\r\n return res\r\n }\r\n}\r\n","import type { ComfyApp } from './app'\r\nimport { api } from './api'\r\nimport { ChangeTracker } from './changeTracker'\r\nimport { ComfyAsyncDialog } from './ui/components/asyncDialog'\r\nimport { getStorageValue, setStorageValue } from './utils'\r\nimport { LGraphCanvas, LGraph } from '@comfyorg/litegraph'\r\n\r\nfunction appendJsonExt(path: string) {\r\n if (!path.toLowerCase().endsWith('.json')) {\r\n path += '.json'\r\n }\r\n return path\r\n}\r\n\r\nexport function trimJsonExt(path: string) {\r\n return path?.replace(/\\.json$/, '')\r\n}\r\n\r\nexport class ComfyWorkflowManager extends EventTarget {\r\n #activePromptId: string | null = null\r\n #unsavedCount = 0\r\n #activeWorkflow: ComfyWorkflow\r\n\r\n workflowLookup: Record = {}\r\n workflows: Array = []\r\n openWorkflows: Array = []\r\n queuedPrompts: Record<\r\n string,\r\n { workflow?: ComfyWorkflow; nodes?: Record }\r\n > = {}\r\n app: ComfyApp\r\n\r\n get activeWorkflow() {\r\n return this.#activeWorkflow ?? this.openWorkflows[0]\r\n }\r\n\r\n get activePromptId() {\r\n return this.#activePromptId\r\n }\r\n\r\n get activePrompt() {\r\n return this.queuedPrompts[this.#activePromptId]\r\n }\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n this.app = app\r\n ChangeTracker.init(app)\r\n\r\n this.#bindExecutionEvents()\r\n }\r\n\r\n #bindExecutionEvents() {\r\n // TODO: on reload, set active prompt based on the latest ws message\r\n\r\n const emit = () =>\r\n this.dispatchEvent(\r\n new CustomEvent('execute', { detail: this.activePrompt })\r\n )\r\n let executing = null\r\n api.addEventListener('execution_start', (e) => {\r\n this.#activePromptId = e.detail.prompt_id\r\n\r\n // This event can fire before the event is stored, so put a placeholder\r\n this.queuedPrompts[this.#activePromptId] ??= { nodes: {} }\r\n emit()\r\n })\r\n api.addEventListener('execution_cached', (e) => {\r\n if (!this.activePrompt) return\r\n for (const n of e.detail.nodes) {\r\n this.activePrompt.nodes[n] = true\r\n }\r\n emit()\r\n })\r\n api.addEventListener('executed', (e) => {\r\n if (!this.activePrompt) return\r\n this.activePrompt.nodes[e.detail.node] = true\r\n emit()\r\n })\r\n api.addEventListener('executing', (e) => {\r\n if (!this.activePrompt) return\r\n\r\n if (executing) {\r\n // Seems sometimes nodes that are cached fire executing but not executed\r\n this.activePrompt.nodes[executing] = true\r\n }\r\n executing = e.detail\r\n if (!executing) {\r\n delete this.queuedPrompts[this.#activePromptId]\r\n this.#activePromptId = null\r\n }\r\n emit()\r\n })\r\n }\r\n\r\n async loadWorkflows() {\r\n try {\r\n let favorites\r\n const resp = await api.getUserData('workflows/.index.json')\r\n let info\r\n if (resp.status === 200) {\r\n info = await resp.json()\r\n favorites = new Set(info?.favorites ?? [])\r\n } else {\r\n favorites = new Set()\r\n }\r\n\r\n const workflows = (await api.listUserData('workflows', true, true)).map(\r\n (w) => {\r\n let workflow = this.workflowLookup[w[0]]\r\n if (!workflow) {\r\n workflow = new ComfyWorkflow(\r\n this,\r\n w[0],\r\n w.slice(1),\r\n favorites.has(w[0])\r\n )\r\n this.workflowLookup[workflow.path] = workflow\r\n }\r\n return workflow\r\n }\r\n )\r\n\r\n this.workflows = workflows\r\n } catch (error) {\r\n alert('Error loading workflows: ' + (error.message ?? error))\r\n this.workflows = []\r\n }\r\n }\r\n\r\n async saveWorkflowMetadata() {\r\n await api.storeUserData('workflows/.index.json', {\r\n favorites: [\r\n ...this.workflows.filter((w) => w.isFavorite).map((w) => w.path)\r\n ]\r\n })\r\n }\r\n\r\n /**\r\n * @param {string | ComfyWorkflow | null} workflow\r\n */\r\n setWorkflow(workflow) {\r\n if (workflow && typeof workflow === 'string') {\r\n // Selected by path, i.e. on reload of last workflow\r\n const found = this.workflows.find((w) => w.path === workflow)\r\n if (found) {\r\n workflow = found\r\n workflow.unsaved =\r\n !workflow ||\r\n getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true'\r\n }\r\n }\r\n\r\n if (!(workflow instanceof ComfyWorkflow)) {\r\n // Still not found, either reloading a deleted workflow or blank\r\n workflow = new ComfyWorkflow(\r\n this,\r\n workflow ||\r\n 'Unsaved Workflow' +\r\n (this.#unsavedCount++ ? ` (${this.#unsavedCount})` : '')\r\n )\r\n }\r\n\r\n const index = this.openWorkflows.indexOf(workflow)\r\n if (index === -1) {\r\n // Opening a new workflow\r\n this.openWorkflows.push(workflow)\r\n }\r\n\r\n this.#activeWorkflow = workflow\r\n\r\n setStorageValue('Comfy.PreviousWorkflow', this.activeWorkflow.path ?? '')\r\n this.dispatchEvent(new CustomEvent('changeWorkflow'))\r\n }\r\n\r\n storePrompt({ nodes, id }) {\r\n this.queuedPrompts[id] ??= {}\r\n this.queuedPrompts[id].nodes = {\r\n ...nodes.reduce((p, n) => {\r\n p[n] = false\r\n return p\r\n }, {}),\r\n ...this.queuedPrompts[id].nodes\r\n }\r\n this.queuedPrompts[id].workflow = this.activeWorkflow\r\n }\r\n\r\n /**\r\n * @param {ComfyWorkflow} workflow\r\n */\r\n async closeWorkflow(workflow, warnIfUnsaved = true) {\r\n if (!workflow.isOpen) {\r\n return true\r\n }\r\n if (workflow.unsaved && warnIfUnsaved) {\r\n const res = await ComfyAsyncDialog.prompt({\r\n title: 'Save Changes?',\r\n message: `Do you want to save changes to \"${workflow.path ?? workflow.name}\" before closing?`,\r\n actions: ['Yes', 'No', 'Cancel']\r\n })\r\n if (res === 'Yes') {\r\n const active = this.activeWorkflow\r\n if (active !== workflow) {\r\n // We need to switch to the workflow to save it\r\n await workflow.load()\r\n }\r\n\r\n if (!(await workflow.save())) {\r\n // Save was canceled, restore the previous workflow\r\n if (active !== workflow) {\r\n await active.load()\r\n }\r\n return\r\n }\r\n } else if (res === 'Cancel') {\r\n return\r\n }\r\n }\r\n workflow.changeTracker = null\r\n this.openWorkflows.splice(this.openWorkflows.indexOf(workflow), 1)\r\n if (this.openWorkflows.length) {\r\n this.#activeWorkflow = this.openWorkflows[0]\r\n await this.#activeWorkflow.load()\r\n } else {\r\n // Load default\r\n await this.app.loadGraphData()\r\n }\r\n }\r\n}\r\n\r\nexport class ComfyWorkflow {\r\n #name\r\n #path\r\n #pathParts\r\n #isFavorite = false\r\n changeTracker: ChangeTracker | null = null\r\n unsaved = false\r\n manager: ComfyWorkflowManager\r\n\r\n get name() {\r\n return this.#name\r\n }\r\n\r\n get path() {\r\n return this.#path\r\n }\r\n\r\n get pathParts() {\r\n return this.#pathParts\r\n }\r\n\r\n get isFavorite() {\r\n return this.#isFavorite\r\n }\r\n\r\n get isOpen() {\r\n return !!this.changeTracker\r\n }\r\n\r\n constructor(\r\n manager: ComfyWorkflowManager,\r\n path: string,\r\n pathParts?: string[],\r\n isFavorite?: boolean\r\n ) {\r\n this.manager = manager\r\n if (pathParts) {\r\n this.#updatePath(path, pathParts)\r\n this.#isFavorite = isFavorite\r\n } else {\r\n this.#name = path\r\n this.unsaved = true\r\n }\r\n }\r\n\r\n #updatePath(path: string, pathParts: string[]) {\r\n this.#path = path\r\n\r\n if (!pathParts) {\r\n if (!path.includes('\\\\')) {\r\n pathParts = path.split('/')\r\n } else {\r\n pathParts = path.split('\\\\')\r\n }\r\n }\r\n\r\n this.#pathParts = pathParts\r\n this.#name = trimJsonExt(pathParts[pathParts.length - 1])\r\n }\r\n\r\n async getWorkflowData() {\r\n const resp = await api.getUserData('workflows/' + this.path)\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error loading workflow file '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n return await resp.json()\r\n }\r\n\r\n load = async () => {\r\n if (this.isOpen) {\r\n await this.manager.app.loadGraphData(\r\n this.changeTracker.activeState,\r\n true,\r\n true,\r\n this\r\n )\r\n } else {\r\n const data = await this.getWorkflowData()\r\n if (!data) return\r\n await this.manager.app.loadGraphData(data, true, true, this)\r\n }\r\n }\r\n\r\n async save(saveAs = false) {\r\n if (!this.path || saveAs) {\r\n return !!(await this.#save(null, false))\r\n } else {\r\n return !!(await this.#save(this.path, true))\r\n }\r\n }\r\n\r\n async favorite(value: boolean) {\r\n try {\r\n if (this.#isFavorite === value) return\r\n this.#isFavorite = value\r\n await this.manager.saveWorkflowMetadata()\r\n this.manager.dispatchEvent(new CustomEvent('favorite', { detail: this }))\r\n } catch (error) {\r\n alert(\r\n 'Error favoriting workflow ' +\r\n this.path +\r\n '\\n' +\r\n (error.message ?? error)\r\n )\r\n }\r\n }\r\n\r\n async rename(path: string) {\r\n path = appendJsonExt(path)\r\n let resp = await api.moveUserData(\r\n 'workflows/' + this.path,\r\n 'workflows/' + path\r\n )\r\n\r\n if (resp.status === 409) {\r\n if (\r\n !confirm(\r\n `Workflow '${path}' already exists, do you want to overwrite it?`\r\n )\r\n )\r\n return resp\r\n resp = await api.moveUserData(\r\n 'workflows/' + this.path,\r\n 'workflows/' + path,\r\n { overwrite: true }\r\n )\r\n }\r\n\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error renaming workflow file '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n\r\n const isFav = this.isFavorite\r\n if (isFav) {\r\n await this.favorite(false)\r\n }\r\n path = (await resp.json()).substring('workflows/'.length)\r\n this.#updatePath(path, null)\r\n if (isFav) {\r\n await this.favorite(true)\r\n }\r\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\r\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\r\n }\r\n\r\n async insert() {\r\n const data = await this.getWorkflowData()\r\n if (!data) return\r\n\r\n const old = localStorage.getItem('litegrapheditor_clipboard')\r\n const graph = new LGraph(data)\r\n const canvas = new LGraphCanvas(null, graph, {\r\n // @ts-expect-error\r\n skip_events: true,\r\n skip_render: true\r\n })\r\n canvas.selectNodes()\r\n canvas.copyToClipboard()\r\n this.manager.app.canvas.pasteFromClipboard()\r\n localStorage.setItem('litegrapheditor_clipboard', old)\r\n }\r\n\r\n async delete() {\r\n // TODO: fix delete of current workflow - should mark workflow as unsaved and when saving use old name by default\r\n\r\n try {\r\n if (this.isFavorite) {\r\n await this.favorite(false)\r\n }\r\n await api.deleteUserData('workflows/' + this.path)\r\n this.unsaved = true\r\n this.#path = null\r\n this.#pathParts = null\r\n this.manager.workflows.splice(this.manager.workflows.indexOf(this), 1)\r\n this.manager.dispatchEvent(new CustomEvent('delete', { detail: this }))\r\n } catch (error) {\r\n alert(`Error deleting workflow: ${error.message || error}`)\r\n }\r\n }\r\n\r\n track() {\r\n if (this.changeTracker) {\r\n this.changeTracker.restore()\r\n } else {\r\n this.changeTracker = new ChangeTracker(this)\r\n }\r\n }\r\n\r\n async #save(path: string | null, overwrite: boolean) {\r\n if (!path) {\r\n path = prompt(\r\n 'Save workflow as:',\r\n trimJsonExt(this.path) ?? this.name ?? 'workflow'\r\n )\r\n if (!path) return\r\n }\r\n\r\n path = appendJsonExt(path)\r\n\r\n const p = await this.manager.app.graphToPrompt()\r\n const json = JSON.stringify(p.workflow, null, 2)\r\n let resp = await api.storeUserData('workflows/' + path, json, {\r\n stringify: false,\r\n throwOnError: false,\r\n overwrite\r\n })\r\n if (resp.status === 409) {\r\n if (\r\n !confirm(\r\n `Workflow '${path}' already exists, do you want to overwrite it?`\r\n )\r\n )\r\n return\r\n resp = await api.storeUserData('workflows/' + path, json, {\r\n stringify: false\r\n })\r\n }\r\n\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error saving workflow '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n\r\n path = (await resp.json()).substring('workflows/'.length)\r\n\r\n if (!this.path) {\r\n // Saved new workflow, patch this instance\r\n this.#updatePath(path, null)\r\n await this.manager.loadWorkflows()\r\n this.unsaved = false\r\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\r\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\r\n } else if (path !== this.path) {\r\n // Saved as, open the new copy\r\n await this.manager.loadWorkflows()\r\n const workflow = this.manager.workflowLookup[path]\r\n await workflow.load()\r\n } else {\r\n // Normal save\r\n this.unsaved = false\r\n this.manager.dispatchEvent(new CustomEvent('save', { detail: this }))\r\n }\r\n\r\n return true\r\n }\r\n}\r\n","import { ComfyButton } from '../components/button'\r\nimport { prop, getStorageValue, setStorageValue } from '../../utils'\r\nimport { $el } from '../../ui'\r\nimport { api } from '../../api'\r\nimport { ComfyPopup } from '../components/popup'\r\nimport { createSpinner } from '../spinner'\r\nimport { ComfyWorkflow, trimJsonExt } from '../../workflows'\r\nimport { ComfyAsyncDialog } from '../components/asyncDialog'\r\nimport type { ComfyApp } from '@/scripts/app'\r\nimport type { ComfyComponent } from '../components'\r\n\r\nexport class ComfyWorkflowsMenu {\r\n #first = true\r\n element = $el('div.comfyui-workflows')\r\n popup: ComfyPopup\r\n app: ComfyApp\r\n buttonProgress: HTMLElement\r\n workflowLabel: HTMLElement\r\n button: ComfyButton\r\n content: ComfyWorkflowsContent\r\n unsaved: boolean\r\n\r\n get open() {\r\n return this.popup.open\r\n }\r\n\r\n set open(open) {\r\n this.popup.open = open\r\n }\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n this.#bindEvents()\r\n\r\n const classList = {\r\n 'comfyui-workflows-button': true,\r\n 'comfyui-button': true,\r\n unsaved: getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true',\r\n running: false\r\n }\r\n this.buttonProgress = $el('div.comfyui-workflows-button-progress')\r\n this.workflowLabel = $el('span.comfyui-workflows-label', '')\r\n this.button = new ComfyButton({\r\n content: $el('div.comfyui-workflows-button-inner', [\r\n $el('i.mdi.mdi-graph'),\r\n this.workflowLabel,\r\n this.buttonProgress\r\n ]),\r\n icon: 'chevron-down',\r\n classList\r\n })\r\n\r\n this.element.append(this.button.element)\r\n\r\n this.popup = new ComfyPopup({\r\n target: this.element,\r\n classList: 'comfyui-workflows-popup'\r\n })\r\n this.content = new ComfyWorkflowsContent(app, this.popup)\r\n this.popup.children = [this.content.element]\r\n this.popup.addEventListener('change', () => {\r\n this.button.icon = 'chevron-' + (this.popup.open ? 'up' : 'down')\r\n })\r\n this.button.withPopup(this.popup)\r\n\r\n this.unsaved = prop(this, 'unsaved', classList.unsaved, (v) => {\r\n classList.unsaved = v\r\n this.button.classList = classList\r\n setStorageValue('Comfy.PreviousWorkflowUnsaved', v)\r\n })\r\n }\r\n\r\n #updateProgress = () => {\r\n const prompt = this.app.workflowManager.activePrompt\r\n let percent = 0\r\n if (this.app.workflowManager.activeWorkflow === prompt?.workflow) {\r\n const total = Object.values(prompt.nodes)\r\n const done = total.filter(Boolean)\r\n percent = (done.length / total.length) * 100\r\n }\r\n this.buttonProgress.style.width = percent + '%'\r\n }\r\n\r\n #updateActive = () => {\r\n const active = this.app.workflowManager.activeWorkflow\r\n this.button.tooltip = active.path\r\n this.workflowLabel.textContent = active.name\r\n this.unsaved = active.unsaved\r\n\r\n if (this.#first) {\r\n this.#first = false\r\n this.content.load()\r\n }\r\n\r\n this.#updateProgress()\r\n }\r\n\r\n #bindEvents() {\r\n this.app.workflowManager.addEventListener(\r\n 'changeWorkflow',\r\n this.#updateActive\r\n )\r\n this.app.workflowManager.addEventListener('rename', this.#updateActive)\r\n this.app.workflowManager.addEventListener('delete', this.#updateActive)\r\n\r\n this.app.workflowManager.addEventListener('save', () => {\r\n this.unsaved = this.app.workflowManager.activeWorkflow.unsaved\r\n })\r\n\r\n this.app.workflowManager.addEventListener('execute', (e) => {\r\n this.#updateProgress()\r\n })\r\n\r\n api.addEventListener('graphChanged', () => {\r\n this.unsaved = true\r\n })\r\n }\r\n\r\n #getMenuOptions(callback) {\r\n const menu = []\r\n const directories = new Map()\r\n for (const workflow of this.app.workflowManager.workflows || []) {\r\n const path = workflow.pathParts\r\n if (!path) continue\r\n let parent = menu\r\n let currentPath = ''\r\n for (let i = 0; i < path.length - 1; i++) {\r\n currentPath += '/' + path[i]\r\n let newParent = directories.get(currentPath)\r\n if (!newParent) {\r\n newParent = {\r\n title: path[i],\r\n has_submenu: true,\r\n submenu: {\r\n options: []\r\n }\r\n }\r\n parent.push(newParent)\r\n newParent = newParent.submenu.options\r\n directories.set(currentPath, newParent)\r\n }\r\n parent = newParent\r\n }\r\n parent.push({\r\n title: trimJsonExt(path[path.length - 1]),\r\n callback: () => callback(workflow)\r\n })\r\n }\r\n return menu\r\n }\r\n\r\n #getFavoriteMenuOptions(callback) {\r\n const menu = []\r\n for (const workflow of this.app.workflowManager.workflows || []) {\r\n if (workflow.isFavorite) {\r\n menu.push({\r\n title: '⭐ ' + workflow.name,\r\n callback: () => callback(workflow)\r\n })\r\n }\r\n }\r\n return menu\r\n }\r\n\r\n registerExtension(app: ComfyApp) {\r\n const self = this\r\n app.registerExtension({\r\n name: 'Comfy.Workflows',\r\n async beforeRegisterNodeDef(nodeType) {\r\n function getImageWidget(node) {\r\n const inputs = {\r\n ...node.constructor?.nodeData?.input?.required,\r\n ...node.constructor?.nodeData?.input?.optional\r\n }\r\n for (const input in inputs) {\r\n if (inputs[input][0] === 'IMAGEUPLOAD') {\r\n const imageWidget = node.widgets.find(\r\n (w) => w.name === (inputs[input]?.[1]?.widget ?? 'image')\r\n )\r\n if (imageWidget) return imageWidget\r\n }\r\n }\r\n }\r\n\r\n function setWidgetImage(node, widget, img) {\r\n const url = new URL(img.src)\r\n const filename = url.searchParams.get('filename')\r\n const subfolder = url.searchParams.get('subfolder')\r\n const type = url.searchParams.get('type')\r\n const imageId = `${subfolder ? subfolder + '/' : ''}${filename} [${type}]`\r\n widget.value = imageId\r\n node.imgs = [img]\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n\r\n async function sendToWorkflow(\r\n img: HTMLImageElement,\r\n workflow: ComfyWorkflow\r\n ) {\r\n const openWorkflow = app.workflowManager.openWorkflows.find(\r\n (w) => w.path === workflow.path\r\n )\r\n if (openWorkflow) {\r\n workflow = openWorkflow\r\n }\r\n\r\n await workflow.load()\r\n let options = []\r\n const nodes = app.graph.computeExecutionOrder(false)\r\n for (const node of nodes) {\r\n const widget = getImageWidget(node)\r\n if (widget == null) continue\r\n\r\n if (node.title?.toLowerCase().includes('input')) {\r\n options = [{ widget, node }]\r\n break\r\n } else {\r\n options.push({ widget, node })\r\n }\r\n }\r\n\r\n if (!options.length) {\r\n alert('No image nodes have been found in this workflow!')\r\n return\r\n } else if (options.length > 1) {\r\n const dialog = new WidgetSelectionDialog(options)\r\n const res = await dialog.show(app)\r\n if (!res) return\r\n options = [res]\r\n }\r\n\r\n setWidgetImage(options[0].node, options[0].widget, img)\r\n }\r\n\r\n const getExtraMenuOptions = nodeType.prototype['getExtraMenuOptions']\r\n nodeType.prototype['getExtraMenuOptions'] = function (\r\n this: { imageIndex?: number; overIndex?: number; imgs: string[] },\r\n _,\r\n options\r\n ) {\r\n const r = getExtraMenuOptions?.apply?.(this, arguments)\r\n const setting = app.ui.settings.getSettingValue(\r\n 'Comfy.UseNewMenu',\r\n false\r\n )\r\n if (setting && setting != 'Disabled') {\r\n const t = this\r\n let img\r\n if (t.imageIndex != null) {\r\n // An image is selected so select that\r\n img = t.imgs?.[t.imageIndex]\r\n } else if (t.overIndex != null) {\r\n // No image is selected but one is hovered\r\n img = t.imgs?.[t.overIndex]\r\n }\r\n\r\n if (img) {\r\n let pos = options.findIndex((o) => o.content === 'Save Image')\r\n if (pos === -1) {\r\n pos = 0\r\n } else {\r\n pos++\r\n }\r\n\r\n options.splice(pos, 0, {\r\n content: 'Send to workflow',\r\n has_submenu: true,\r\n submenu: {\r\n options: [\r\n {\r\n callback: () =>\r\n sendToWorkflow(img, app.workflowManager.activeWorkflow),\r\n title: '[Current workflow]'\r\n },\r\n ...self.#getFavoriteMenuOptions(\r\n sendToWorkflow.bind(null, img)\r\n ),\r\n null,\r\n ...self.#getMenuOptions(sendToWorkflow.bind(null, img))\r\n ]\r\n }\r\n })\r\n }\r\n }\r\n\r\n return r\r\n }\r\n }\r\n })\r\n }\r\n}\r\n\r\nexport class ComfyWorkflowsContent {\r\n element = $el('div.comfyui-workflows-panel')\r\n treeState = {}\r\n treeFiles: Record = {}\r\n openFiles: Map> = new Map()\r\n activeElement: WorkflowElement = null\r\n spinner: Element\r\n openElement: HTMLElement\r\n favoritesElement: HTMLElement\r\n treeElement: HTMLElement\r\n app: ComfyApp\r\n popup: ComfyPopup\r\n actions: HTMLElement\r\n filterText: string | undefined\r\n treeRoot: HTMLElement\r\n\r\n constructor(app: ComfyApp, popup: ComfyPopup) {\r\n this.app = app\r\n this.popup = popup\r\n this.actions = $el('div.comfyui-workflows-actions', [\r\n new ComfyButton({\r\n content: 'Default',\r\n icon: 'file-code',\r\n iconSize: 18,\r\n classList: 'comfyui-button primary',\r\n tooltip: 'Load default workflow',\r\n action: () => {\r\n popup.open = false\r\n app.loadGraphData()\r\n app.resetView()\r\n }\r\n }).element,\r\n new ComfyButton({\r\n content: 'Browse',\r\n icon: 'folder',\r\n iconSize: 18,\r\n tooltip: 'Browse for an image or exported workflow',\r\n action: () => {\r\n popup.open = false\r\n app.ui.loadFile()\r\n }\r\n }).element,\r\n new ComfyButton({\r\n content: 'Blank',\r\n icon: 'plus-thick',\r\n iconSize: 18,\r\n tooltip: 'Create a new blank workflow',\r\n action: () => {\r\n app.workflowManager.setWorkflow(null)\r\n app.clean()\r\n app.graph.clear()\r\n app.workflowManager.activeWorkflow.track()\r\n popup.open = false\r\n }\r\n }).element\r\n ])\r\n\r\n this.spinner = createSpinner()\r\n this.element.replaceChildren(this.actions, this.spinner)\r\n\r\n this.popup.addEventListener('open', () => this.load())\r\n this.popup.addEventListener('close', () =>\r\n this.element.replaceChildren(this.actions, this.spinner)\r\n )\r\n\r\n this.app.workflowManager.addEventListener('favorite', (e) => {\r\n const workflow = e['detail']\r\n const button = this.treeFiles[workflow.path]?.primary\r\n if (!button) return // Can happen when a workflow is renamed\r\n button.icon = this.#getFavoriteIcon(workflow)\r\n button.overIcon = this.#getFavoriteOverIcon(workflow)\r\n this.updateFavorites()\r\n })\r\n\r\n for (const e of ['save', 'open', 'close', 'changeWorkflow']) {\r\n // TODO: dont be lazy and just update the specific element\r\n app.workflowManager.addEventListener(e, () => this.updateOpen())\r\n }\r\n this.app.workflowManager.addEventListener('rename', () => this.load())\r\n this.app.workflowManager.addEventListener('execute', (e) =>\r\n this.#updateActive()\r\n )\r\n }\r\n\r\n async load() {\r\n await this.app.workflowManager.loadWorkflows()\r\n this.updateTree()\r\n this.updateFavorites()\r\n this.updateOpen()\r\n this.element.replaceChildren(\r\n this.actions,\r\n this.openElement,\r\n this.favoritesElement,\r\n this.treeElement\r\n )\r\n }\r\n\r\n updateOpen() {\r\n const current = this.openElement\r\n this.openFiles.clear()\r\n\r\n this.openElement = $el('div.comfyui-workflows-open', [\r\n $el('h3', 'Open'),\r\n ...this.app.workflowManager.openWorkflows.map((w) => {\r\n const wrapper = new WorkflowElement(this, w, {\r\n primary: { element: $el('i.mdi.mdi-18px.mdi-progress-pencil') },\r\n buttons: [\r\n this.#getRenameButton(w),\r\n new ComfyButton({\r\n icon: 'close',\r\n iconSize: 18,\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n tooltip: 'Close workflow',\r\n action: (e) => {\r\n e.stopImmediatePropagation()\r\n this.app.workflowManager.closeWorkflow(w)\r\n }\r\n })\r\n ]\r\n })\r\n if (w.unsaved) {\r\n wrapper.element.classList.add('unsaved')\r\n }\r\n if (w === this.app.workflowManager.activeWorkflow) {\r\n wrapper.element.classList.add('active')\r\n }\r\n\r\n this.openFiles.set(w, wrapper)\r\n return wrapper.element\r\n })\r\n ])\r\n\r\n this.#updateActive()\r\n current?.replaceWith(this.openElement)\r\n }\r\n\r\n updateFavorites() {\r\n const current = this.favoritesElement\r\n const favorites = [\r\n ...this.app.workflowManager.workflows.filter((w) => w.isFavorite)\r\n ]\r\n\r\n this.favoritesElement = $el('div.comfyui-workflows-favorites', [\r\n $el('h3', 'Favorites'),\r\n ...favorites\r\n .map((w) => {\r\n return this.#getWorkflowElement(w).element\r\n })\r\n .filter(Boolean)\r\n ])\r\n\r\n current?.replaceWith(this.favoritesElement)\r\n }\r\n\r\n filterTree() {\r\n if (!this.filterText) {\r\n this.treeRoot.classList.remove('filtered')\r\n // Unfilter whole tree\r\n for (const item of Object.values(this.treeFiles)) {\r\n item.element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(item.element.parentElement)\r\n }\r\n return\r\n }\r\n this.treeRoot.classList.add('filtered')\r\n const searchTerms = this.filterText.toLocaleLowerCase().split(' ')\r\n for (const item of Object.values(this.treeFiles)) {\r\n const parts = item.workflow.pathParts\r\n let termIndex = 0\r\n let valid = false\r\n for (const part of parts) {\r\n let currentIndex = 0\r\n do {\r\n currentIndex = part.indexOf(searchTerms[termIndex], currentIndex)\r\n if (currentIndex > -1) currentIndex += searchTerms[termIndex].length\r\n } while (currentIndex !== -1 && ++termIndex < searchTerms.length)\r\n\r\n if (termIndex >= searchTerms.length) {\r\n valid = true\r\n break\r\n }\r\n }\r\n if (valid) {\r\n item.element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(item.element.parentElement)\r\n } else {\r\n item.element.parentElement.style.display = 'none'\r\n this.hideTreeParents(item.element.parentElement)\r\n }\r\n }\r\n }\r\n\r\n hideTreeParents(element) {\r\n // Hide all parents if no children are visible\r\n if (\r\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\r\n false\r\n ) {\r\n for (let i = 1; i < element.parentElement.children.length; i++) {\r\n const c = element.parentElement.children[i]\r\n if (c.style.display !== 'none') {\r\n return\r\n }\r\n }\r\n element.parentElement.style.display = 'none'\r\n this.hideTreeParents(element.parentElement)\r\n }\r\n }\r\n\r\n showTreeParents(element) {\r\n if (\r\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\r\n false\r\n ) {\r\n element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(element.parentElement)\r\n }\r\n }\r\n\r\n updateTree() {\r\n const current = this.treeElement\r\n const nodes = {}\r\n let typingTimeout\r\n\r\n this.treeFiles = {}\r\n this.treeRoot = $el('ul.comfyui-workflows-tree')\r\n this.treeElement = $el('section', [\r\n $el('header', [\r\n $el('h3', 'Browse'),\r\n $el('div.comfy-ui-workflows-search', [\r\n $el('i.mdi.mdi-18px.mdi-magnify'),\r\n $el('input', {\r\n placeholder: 'Search',\r\n value: this.filterText ?? '',\r\n oninput: (e: InputEvent) => {\r\n this.filterText = e.target['value']?.trim()\r\n clearTimeout(typingTimeout)\r\n typingTimeout = setTimeout(() => this.filterTree(), 250)\r\n }\r\n })\r\n ])\r\n ]),\r\n this.treeRoot\r\n ])\r\n\r\n for (const workflow of this.app.workflowManager.workflows) {\r\n if (!workflow.pathParts) continue\r\n\r\n let currentPath = ''\r\n let currentRoot = this.treeRoot\r\n\r\n for (let i = 0; i < workflow.pathParts.length; i++) {\r\n currentPath += (currentPath ? '\\\\' : '') + workflow.pathParts[i]\r\n const parentNode =\r\n nodes[currentPath] ??\r\n this.#createNode(currentPath, workflow, i, currentRoot)\r\n\r\n nodes[currentPath] = parentNode\r\n currentRoot = parentNode\r\n }\r\n }\r\n\r\n current?.replaceWith(this.treeElement)\r\n this.filterTree()\r\n }\r\n\r\n #expandNode(el, workflow, thisPath, i) {\r\n const expanded = !el.classList.toggle('closed')\r\n if (expanded) {\r\n let c = ''\r\n for (let j = 0; j <= i; j++) {\r\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\r\n this.treeState[c] = true\r\n }\r\n } else {\r\n let c = thisPath\r\n for (let j = i + 1; j < workflow.pathParts.length; j++) {\r\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\r\n delete this.treeState[c]\r\n }\r\n delete this.treeState[thisPath]\r\n }\r\n }\r\n\r\n #updateActive() {\r\n this.#removeActive()\r\n\r\n const active = this.app.workflowManager.activePrompt\r\n if (!active?.workflow) return\r\n\r\n const open = this.openFiles.get(active.workflow)\r\n if (!open) return\r\n\r\n this.activeElement = open\r\n\r\n const total = Object.values(active.nodes)\r\n const done = total.filter(Boolean)\r\n const percent = done.length / total.length\r\n open.element.classList.add('running')\r\n open.element.style.setProperty('--progress', percent * 100 + '%')\r\n open.primary.element.classList.remove('mdi-progress-pencil')\r\n open.primary.element.classList.add('mdi-play')\r\n }\r\n\r\n #removeActive() {\r\n if (!this.activeElement) return\r\n this.activeElement.element.classList.remove('running')\r\n this.activeElement.element.style.removeProperty('--progress')\r\n this.activeElement.primary.element.classList.add('mdi-progress-pencil')\r\n this.activeElement.primary.element.classList.remove('mdi-play')\r\n }\r\n\r\n #getFavoriteIcon(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite ? 'star' : 'file-outline'\r\n }\r\n\r\n #getFavoriteOverIcon(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite ? 'star-off' : 'star-outline'\r\n }\r\n\r\n #getFavoriteTooltip(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite\r\n ? 'Remove this workflow from your favorites'\r\n : 'Add this workflow to your favorites'\r\n }\r\n\r\n #getFavoriteButton(workflow: ComfyWorkflow, primary: boolean) {\r\n return new ComfyButton({\r\n icon: this.#getFavoriteIcon(workflow),\r\n overIcon: this.#getFavoriteOverIcon(workflow),\r\n iconSize: 18,\r\n classList:\r\n 'comfyui-button comfyui-workflows-file-action-favorite' +\r\n (primary ? ' comfyui-workflows-file-action-primary' : ''),\r\n tooltip: this.#getFavoriteTooltip(workflow),\r\n action: (e) => {\r\n e.stopImmediatePropagation()\r\n workflow.favorite(!workflow.isFavorite)\r\n }\r\n })\r\n }\r\n\r\n #getDeleteButton(workflow: ComfyWorkflow) {\r\n const deleteButton = new ComfyButton({\r\n icon: 'delete',\r\n tooltip: 'Delete this workflow',\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n iconSize: 18,\r\n action: async (e, btn) => {\r\n e.stopImmediatePropagation()\r\n\r\n if (btn.icon === 'delete-empty') {\r\n btn.enabled = false\r\n await workflow.delete()\r\n await this.load()\r\n } else {\r\n btn.icon = 'delete-empty'\r\n btn.element.style.background = 'red'\r\n }\r\n }\r\n })\r\n deleteButton.element.addEventListener('mouseleave', () => {\r\n deleteButton.icon = 'delete'\r\n deleteButton.element.style.removeProperty('background')\r\n })\r\n return deleteButton\r\n }\r\n\r\n #getInsertButton(workflow: ComfyWorkflow) {\r\n return new ComfyButton({\r\n icon: 'file-move-outline',\r\n iconSize: 18,\r\n tooltip: 'Insert this workflow into the current workflow',\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n action: (e) => {\r\n if (!this.app.shiftDown) {\r\n this.popup.open = false\r\n }\r\n e.stopImmediatePropagation()\r\n if (!this.app.shiftDown) {\r\n this.popup.open = false\r\n }\r\n workflow.insert()\r\n }\r\n })\r\n }\r\n\r\n /** @param {ComfyWorkflow} workflow */\r\n #getRenameButton(workflow: ComfyWorkflow) {\r\n return new ComfyButton({\r\n icon: 'pencil',\r\n tooltip: workflow.path\r\n ? 'Rename this workflow'\r\n : \"This workflow can't be renamed as it hasn't been saved.\",\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n iconSize: 18,\r\n enabled: !!workflow.path,\r\n action: async (e) => {\r\n e.stopImmediatePropagation()\r\n const newName = prompt('Enter new name', workflow.path)\r\n if (newName) {\r\n await workflow.rename(newName)\r\n }\r\n }\r\n })\r\n }\r\n\r\n #getWorkflowElement(workflow: ComfyWorkflow) {\r\n return new WorkflowElement(this, workflow, {\r\n primary: this.#getFavoriteButton(workflow, true),\r\n buttons: [\r\n this.#getInsertButton(workflow),\r\n this.#getRenameButton(workflow),\r\n this.#getDeleteButton(workflow)\r\n ]\r\n })\r\n }\r\n\r\n #createLeafNode(workflow: ComfyWorkflow) {\r\n const fileNode = this.#getWorkflowElement(workflow)\r\n this.treeFiles[workflow.path] = fileNode\r\n return fileNode\r\n }\r\n\r\n #createNode(currentPath, workflow, i, currentRoot) {\r\n const part = workflow.pathParts[i]\r\n\r\n const parentNode = $el(\r\n 'ul' + (this.treeState[currentPath] ? '' : '.closed'),\r\n {\r\n $: (el) => {\r\n el.onclick = (e) => {\r\n this.#expandNode(el, workflow, currentPath, i)\r\n e.stopImmediatePropagation()\r\n }\r\n }\r\n }\r\n )\r\n currentRoot.append(parentNode)\r\n\r\n // Create a node for the current part and an inner UL for its children if it isnt a leaf node\r\n const leaf = i === workflow.pathParts.length - 1\r\n let nodeElement\r\n if (leaf) {\r\n nodeElement = this.#createLeafNode(workflow).element\r\n } else {\r\n nodeElement = $el('li', [\r\n $el('i.mdi.mdi-18px.mdi-folder'),\r\n $el('span', part)\r\n ])\r\n }\r\n parentNode.append(nodeElement)\r\n return parentNode\r\n }\r\n}\r\n\r\nclass WorkflowElement {\r\n parent: ComfyWorkflowsContent\r\n workflow: ComfyWorkflow\r\n primary: TPrimary\r\n buttons: ComfyButton[]\r\n element: HTMLElement\r\n constructor(\r\n parent: ComfyWorkflowsContent,\r\n workflow: ComfyWorkflow,\r\n {\r\n tagName = 'li',\r\n primary,\r\n buttons\r\n }: { tagName?: string; primary: TPrimary; buttons: ComfyButton[] }\r\n ) {\r\n this.parent = parent\r\n this.workflow = workflow\r\n this.primary = primary\r\n this.buttons = buttons\r\n\r\n this.element = $el(\r\n tagName + '.comfyui-workflows-tree-file',\r\n {\r\n onclick: () => {\r\n workflow.load()\r\n this.parent.popup.open = false\r\n },\r\n title: this.workflow.path\r\n },\r\n [\r\n this.primary?.element,\r\n $el('span', workflow.name),\r\n ...buttons.map((b) => b.element)\r\n ]\r\n )\r\n }\r\n}\r\n\r\ntype WidgetSelectionDialogOptions = Array<{\r\n widget: { name: string }\r\n node: { pos: [number, number]; title: string; id: string; type: string }\r\n}>\r\n\r\nclass WidgetSelectionDialog extends ComfyAsyncDialog {\r\n #options: WidgetSelectionDialogOptions\r\n\r\n constructor(options: WidgetSelectionDialogOptions) {\r\n super()\r\n this.#options = options\r\n }\r\n\r\n show(app) {\r\n this.element.classList.add('comfy-widget-selection-dialog')\r\n return super.show(\r\n $el('div', [\r\n $el('h2', 'Select image target'),\r\n $el(\r\n 'p',\r\n \"This workflow has multiple image loader nodes, you can rename a node to include 'input' in the title for it to be automatically selected, or select one below.\"\r\n ),\r\n $el(\r\n 'section',\r\n this.#options.map((opt) => {\r\n return $el('div.comfy-widget-selection-item', [\r\n $el(\r\n 'span',\r\n { dataset: { id: opt.node.id } },\r\n `${opt.node.title ?? opt.node.type} ${opt.widget.name}`\r\n ),\r\n $el(\r\n 'button.comfyui-button',\r\n {\r\n onclick: () => {\r\n app.canvas.ds.offset[0] = -opt.node.pos[0] + 50\r\n app.canvas.ds.offset[1] = -opt.node.pos[1] + 50\r\n app.canvas.selectNode(opt.node)\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n },\r\n 'Show'\r\n ),\r\n $el(\r\n 'button.comfyui-button.primary',\r\n {\r\n onclick: () => {\r\n this.close(opt)\r\n }\r\n },\r\n 'Select'\r\n )\r\n ])\r\n })\r\n )\r\n ])\r\n )\r\n }\r\n}\r\n","// Within Vue component context, you can directly call useToast().add()\r\n// instead of going through the store.\r\n// The store is useful when you need to call it from outside the Vue component context.\r\nimport { defineStore } from 'pinia'\r\nimport type { ToastMessageOptions } from 'primevue/toast'\r\n\r\nexport const useToastStore = defineStore('toast', {\r\n state: () => ({\r\n messagesToAdd: [] as ToastMessageOptions[],\r\n messagesToRemove: [] as ToastMessageOptions[],\r\n removeAllRequested: false\r\n }),\r\n\r\n actions: {\r\n add(message: ToastMessageOptions) {\r\n this.messagesToAdd = [...this.messagesToAdd, message]\r\n },\r\n remove(message: ToastMessageOptions) {\r\n this.messagesToRemove = [...this.messagesToRemove, message]\r\n },\r\n removeAll() {\r\n this.removeAllRequested = true\r\n }\r\n }\r\n})\r\n","import { StatusWsMessageStatus } from '@/types/apiTypes'\r\nimport { api } from '../../api'\r\nimport { ComfyButton } from '../components/button'\r\nimport { useToastStore } from '@/stores/toastStore'\r\n\r\nexport function getInterruptButton(visibility: string) {\r\n const btn = new ComfyButton({\r\n icon: 'close',\r\n tooltip: 'Cancel current generation',\r\n enabled: false,\r\n action: async () => {\r\n await api.interrupt()\r\n useToastStore().add({\r\n severity: 'info',\r\n summary: 'Interrupted',\r\n detail: 'Execution has been interrupted',\r\n life: 1000\r\n })\r\n },\r\n classList: ['comfyui-button', 'comfyui-interrupt-button', visibility]\r\n })\r\n\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n const sz = detail?.exec_info?.queue_remaining\r\n btn.enabled = sz > 0\r\n }\r\n )\r\n\r\n return btn\r\n}\r\n","import type { ComfyApp } from '@/scripts/app'\r\nimport { api } from '../../api'\r\nimport { $el } from '../../ui'\r\nimport { downloadBlob } from '../../utils'\r\nimport { ComfyButton } from '../components/button'\r\nimport { ComfyButtonGroup } from '../components/buttonGroup'\r\nimport { ComfySplitButton } from '../components/splitButton'\r\nimport { ComfyQueueButton } from './queueButton'\r\nimport { ComfyWorkflowsMenu } from './workflows'\r\nimport { getInterruptButton } from './interruptButton'\r\nimport './menu.css'\r\nimport type { ComfySettingsDialog } from '../settings'\r\n\r\ntype MenuPosition = 'Disabled' | 'Top' | 'Bottom'\r\n\r\nconst collapseOnMobile = (t) => {\r\n ;(t.element ?? t).classList.add('comfyui-menu-mobile-collapse')\r\n return t\r\n}\r\nconst showOnMobile = (t) => {\r\n ;(t.element ?? t).classList.add('lt-lg-show')\r\n return t\r\n}\r\n\r\nexport class ComfyAppMenu {\r\n #sizeBreak = 'lg'\r\n #lastSizeBreaks = {\r\n lg: null,\r\n md: null,\r\n sm: null,\r\n xs: null\r\n }\r\n #sizeBreaks = Object.keys(this.#lastSizeBreaks)\r\n #cachedInnerSize = null\r\n #cacheTimeout = null\r\n app: ComfyApp\r\n workflows: ComfyWorkflowsMenu\r\n logo: HTMLElement\r\n saveButton: ComfySplitButton\r\n actionsGroup: ComfyButtonGroup\r\n settingsGroup: ComfyButtonGroup\r\n viewGroup: ComfyButtonGroup\r\n mobileMenuButton: ComfyButton\r\n queueButton: ComfyQueueButton\r\n element: HTMLElement\r\n menuPositionSetting: ReturnType\r\n position: MenuPosition\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n\r\n this.workflows = new ComfyWorkflowsMenu(app)\r\n const getSaveButton = (t?: string) =>\r\n new ComfyButton({\r\n icon: 'content-save',\r\n tooltip: 'Save the current workflow',\r\n action: () => app.workflowManager.activeWorkflow.save(),\r\n content: t\r\n })\r\n\r\n this.logo = $el('h1.comfyui-logo.nlg-hide', { title: 'ComfyUI' }, 'ComfyUI')\r\n this.saveButton = new ComfySplitButton(\r\n {\r\n primary: getSaveButton(),\r\n mode: 'hover',\r\n position: 'absolute'\r\n },\r\n getSaveButton('Save'),\r\n new ComfyButton({\r\n icon: 'content-save-edit',\r\n content: 'Save As',\r\n tooltip: 'Save the current graph as a new workflow',\r\n action: () => app.workflowManager.activeWorkflow.save(true)\r\n }),\r\n new ComfyButton({\r\n icon: 'download',\r\n content: 'Export',\r\n tooltip: 'Export the current workflow as JSON',\r\n action: () => this.exportWorkflow('workflow', 'workflow')\r\n }),\r\n new ComfyButton({\r\n icon: 'api',\r\n content: 'Export (API Format)',\r\n tooltip:\r\n 'Export the current workflow as JSON for use with the ComfyUI API',\r\n action: () => this.exportWorkflow('workflow_api', 'output'),\r\n visibilitySetting: { id: 'Comfy.DevMode', showValue: true },\r\n app\r\n })\r\n )\r\n this.actionsGroup = new ComfyButtonGroup(\r\n new ComfyButton({\r\n icon: 'refresh',\r\n content: 'Refresh',\r\n tooltip: 'Refresh widgets in nodes to find new models or files',\r\n action: () => app.refreshComboInNodes()\r\n }),\r\n new ComfyButton({\r\n icon: 'clipboard-edit-outline',\r\n content: 'Clipspace',\r\n tooltip: 'Open Clipspace window',\r\n action: () => app['openClipspace']()\r\n }),\r\n new ComfyButton({\r\n icon: 'fit-to-page-outline',\r\n content: 'Reset View',\r\n tooltip: 'Reset the canvas view',\r\n action: () => app.resetView()\r\n }),\r\n new ComfyButton({\r\n icon: 'cancel',\r\n content: 'Clear',\r\n tooltip: 'Clears current workflow',\r\n action: () => {\r\n if (\r\n !app.ui.settings.getSettingValue('Comfy.ConfirmClear', true) ||\r\n confirm('Clear workflow?')\r\n ) {\r\n app.clean()\r\n app.graph.clear()\r\n api.dispatchEvent(new CustomEvent('graphCleared'))\r\n }\r\n }\r\n })\r\n )\r\n // Keep the settings group as there are custom scripts attaching extra\r\n // elements to it.\r\n this.settingsGroup = new ComfyButtonGroup()\r\n this.viewGroup = new ComfyButtonGroup(\r\n getInterruptButton('nlg-hide').element\r\n )\r\n this.mobileMenuButton = new ComfyButton({\r\n icon: 'menu',\r\n action: (_, btn) => {\r\n btn.icon = this.element.classList.toggle('expanded')\r\n ? 'menu-open'\r\n : 'menu'\r\n window.dispatchEvent(new Event('resize'))\r\n },\r\n classList: 'comfyui-button comfyui-menu-button'\r\n })\r\n this.queueButton = new ComfyQueueButton(app)\r\n\r\n this.element = $el('nav.comfyui-menu.lg', { style: { display: 'none' } }, [\r\n this.logo,\r\n this.workflows.element,\r\n this.saveButton.element,\r\n collapseOnMobile(this.actionsGroup).element,\r\n $el('section.comfyui-menu-push'),\r\n collapseOnMobile(this.settingsGroup).element,\r\n collapseOnMobile(this.viewGroup).element,\r\n\r\n getInterruptButton('lt-lg-show').element,\r\n this.queueButton.element,\r\n showOnMobile(this.mobileMenuButton).element\r\n ])\r\n\r\n let resizeHandler: () => void\r\n this.menuPositionSetting = app.ui.settings.addSetting({\r\n id: 'Comfy.UseNewMenu',\r\n category: ['Comfy', 'Menu', 'UseNewMenu'],\r\n defaultValue: 'Disabled',\r\n name: 'Use new menu and workflow management.',\r\n experimental: true,\r\n tooltip: 'On small screens the menu will always be at the top.',\r\n type: 'combo',\r\n options: ['Disabled', 'Top', 'Bottom'],\r\n onChange: async (v: MenuPosition) => {\r\n if (v && v !== 'Disabled') {\r\n if (!resizeHandler) {\r\n resizeHandler = () => {\r\n this.calculateSizeBreak()\r\n }\r\n window.addEventListener('resize', resizeHandler)\r\n }\r\n this.updatePosition(v)\r\n } else {\r\n if (resizeHandler) {\r\n window.removeEventListener('resize', resizeHandler)\r\n resizeHandler = null\r\n }\r\n document.body.style.removeProperty('display')\r\n app.ui.menuContainer.style.removeProperty('display')\r\n this.element.style.display = 'none'\r\n app.ui.restoreMenuPosition()\r\n }\r\n window.dispatchEvent(new Event('resize'))\r\n }\r\n })\r\n }\r\n\r\n updatePosition(v: MenuPosition) {\r\n document.body.style.display = 'grid'\r\n this.app.ui.menuContainer.style.display = 'none'\r\n this.element.style.removeProperty('display')\r\n this.position = v\r\n if (v === 'Bottom') {\r\n this.app.bodyBottom.append(this.element)\r\n } else {\r\n this.app.bodyTop.prepend(this.element)\r\n }\r\n this.calculateSizeBreak()\r\n }\r\n\r\n updateSizeBreak(idx: number, prevIdx: number, direction: number) {\r\n const newSize = this.#sizeBreaks[idx]\r\n if (newSize === this.#sizeBreak) return\r\n this.#cachedInnerSize = null\r\n clearTimeout(this.#cacheTimeout)\r\n\r\n this.#sizeBreak = this.#sizeBreaks[idx]\r\n for (let i = 0; i < this.#sizeBreaks.length; i++) {\r\n const sz = this.#sizeBreaks[i]\r\n if (sz === this.#sizeBreak) {\r\n this.element.classList.add(sz)\r\n } else {\r\n this.element.classList.remove(sz)\r\n }\r\n if (i < idx) {\r\n this.element.classList.add('lt-' + sz)\r\n } else {\r\n this.element.classList.remove('lt-' + sz)\r\n }\r\n }\r\n\r\n if (idx) {\r\n // We're on a small screen, force the menu at the top\r\n if (this.position !== 'Top') {\r\n this.updatePosition('Top')\r\n }\r\n } else if (this.position != this.menuPositionSetting.value) {\r\n // Restore user position\r\n this.updatePosition(this.menuPositionSetting.value)\r\n }\r\n\r\n // Allow multiple updates, but prevent bouncing\r\n if (!direction) {\r\n direction = prevIdx - idx\r\n } else if (direction != prevIdx - idx) {\r\n return\r\n }\r\n this.calculateSizeBreak(direction)\r\n }\r\n\r\n calculateSizeBreak(direction = 0) {\r\n let idx = this.#sizeBreaks.indexOf(this.#sizeBreak)\r\n const currIdx = idx\r\n const innerSize = this.calculateInnerSize(idx)\r\n if (window.innerWidth >= this.#lastSizeBreaks[this.#sizeBreaks[idx - 1]]) {\r\n if (idx > 0) {\r\n idx--\r\n }\r\n } else if (innerSize > this.element.clientWidth) {\r\n this.#lastSizeBreaks[this.#sizeBreak] = Math.max(\r\n window.innerWidth,\r\n innerSize\r\n )\r\n // We need to shrink\r\n if (idx < this.#sizeBreaks.length - 1) {\r\n idx++\r\n }\r\n }\r\n\r\n this.updateSizeBreak(idx, currIdx, direction)\r\n }\r\n\r\n calculateInnerSize(idx: number) {\r\n // Cache the inner size to prevent too much calculation when resizing the window\r\n clearTimeout(this.#cacheTimeout)\r\n if (this.#cachedInnerSize) {\r\n // Extend cache time\r\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\r\n } else {\r\n let innerSize = 0\r\n let count = 1\r\n for (const c of this.element.children) {\r\n if (c.classList.contains('comfyui-menu-push')) continue // ignore right push\r\n if (idx && c.classList.contains('comfyui-menu-mobile-collapse'))\r\n continue // ignore collapse items\r\n innerSize += c.clientWidth\r\n count++\r\n }\r\n innerSize += 8 * count\r\n this.#cachedInnerSize = innerSize\r\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\r\n }\r\n return this.#cachedInnerSize\r\n }\r\n\r\n getFilename(defaultName: string) {\r\n if (this.app.ui.settings.getSettingValue('Comfy.PromptFilename', true)) {\r\n defaultName = prompt('Save workflow as:', defaultName)\r\n if (!defaultName) return\r\n if (!defaultName.toLowerCase().endsWith('.json')) {\r\n defaultName += '.json'\r\n }\r\n }\r\n return defaultName\r\n }\r\n\r\n async exportWorkflow(\r\n filename: string,\r\n promptProperty: 'workflow' | 'output'\r\n ) {\r\n if (this.app.workflowManager.activeWorkflow?.path) {\r\n filename = this.app.workflowManager.activeWorkflow.name\r\n }\r\n const p = await this.app.graphToPrompt()\r\n const json = JSON.stringify(p[promptProperty], null, 2)\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const file = this.getFilename(filename)\r\n if (!file) return\r\n downloadBlob(file, blob)\r\n }\r\n}\r\n","export type NodeSourceType = 'core' | 'custom_nodes'\r\nexport type NodeSource = {\r\n type: NodeSourceType\r\n className: string\r\n displayText: string\r\n}\r\n\r\nexport const getNodeSource = (python_module: string): NodeSource => {\r\n const modules = python_module.split('.')\r\n if (['nodes', 'comfy_extras'].includes(modules[0])) {\r\n return {\r\n type: 'core',\r\n className: 'comfy-core',\r\n displayText: 'Comfy Core'\r\n }\r\n } else if (modules[0] === 'custom_nodes') {\r\n return {\r\n type: 'custom_nodes',\r\n className: 'comfy-custom-nodes',\r\n displayText: modules[1]\r\n }\r\n } else {\r\n throw new Error(`Unknown node source: ${python_module}`)\r\n }\r\n}\r\n","/**\n * Fuse.js v7.0.0 - Lightweight fuzzy-search (http://fusejs.io)\n *\n * Copyright (c) 2023 Kiro Risk (http://kiro.me)\n * All Rights Reserved. Apache Software License 2.0\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n */\n\nfunction isArray(value) {\n return !Array.isArray\n ? getTag(value) === '[object Array]'\n : Array.isArray(value)\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js\nconst INFINITY = 1 / 0;\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value\n }\n let result = value + '';\n return result == '0' && 1 / value == -INFINITY ? '-0' : result\n}\n\nfunction toString(value) {\n return value == null ? '' : baseToString(value)\n}\n\nfunction isString(value) {\n return typeof value === 'string'\n}\n\nfunction isNumber(value) {\n return typeof value === 'number'\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js\nfunction isBoolean(value) {\n return (\n value === true ||\n value === false ||\n (isObjectLike(value) && getTag(value) == '[object Boolean]')\n )\n}\n\nfunction isObject(value) {\n return typeof value === 'object'\n}\n\n// Checks if `value` is object-like.\nfunction isObjectLike(value) {\n return isObject(value) && value !== null\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null\n}\n\nfunction isBlank(value) {\n return !value.trim().length\n}\n\n// Gets the `toStringTag` of `value`.\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js\nfunction getTag(value) {\n return value == null\n ? value === undefined\n ? '[object Undefined]'\n : '[object Null]'\n : Object.prototype.toString.call(value)\n}\n\nconst EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';\n\nconst INCORRECT_INDEX_TYPE = \"Incorrect 'index' type\";\n\nconst LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) =>\n `Invalid value for key ${key}`;\n\nconst PATTERN_LENGTH_TOO_LARGE = (max) =>\n `Pattern length exceeds max of ${max}.`;\n\nconst MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`;\n\nconst INVALID_KEY_WEIGHT_VALUE = (key) =>\n `Property 'weight' in key '${key}' must be a positive integer`;\n\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nclass KeyStore {\n constructor(keys) {\n this._keys = [];\n this._keyMap = {};\n\n let totalWeight = 0;\n\n keys.forEach((key) => {\n let obj = createKey(key);\n\n this._keys.push(obj);\n this._keyMap[obj.id] = obj;\n\n totalWeight += obj.weight;\n });\n\n // Normalize weights so that their sum is equal to 1\n this._keys.forEach((key) => {\n key.weight /= totalWeight;\n });\n }\n get(keyId) {\n return this._keyMap[keyId]\n }\n keys() {\n return this._keys\n }\n toJSON() {\n return JSON.stringify(this._keys)\n }\n}\n\nfunction createKey(key) {\n let path = null;\n let id = null;\n let src = null;\n let weight = 1;\n let getFn = null;\n\n if (isString(key) || isArray(key)) {\n src = key;\n path = createKeyPath(key);\n id = createKeyId(key);\n } else {\n if (!hasOwn.call(key, 'name')) {\n throw new Error(MISSING_KEY_PROPERTY('name'))\n }\n\n const name = key.name;\n src = name;\n\n if (hasOwn.call(key, 'weight')) {\n weight = key.weight;\n\n if (weight <= 0) {\n throw new Error(INVALID_KEY_WEIGHT_VALUE(name))\n }\n }\n\n path = createKeyPath(name);\n id = createKeyId(name);\n getFn = key.getFn;\n }\n\n return { path, id, weight, src, getFn }\n}\n\nfunction createKeyPath(key) {\n return isArray(key) ? key : key.split('.')\n}\n\nfunction createKeyId(key) {\n return isArray(key) ? key.join('.') : key\n}\n\nfunction get(obj, path) {\n let list = [];\n let arr = false;\n\n const deepGet = (obj, path, index) => {\n if (!isDefined(obj)) {\n return\n }\n if (!path[index]) {\n // If there's no path left, we've arrived at the object we care about.\n list.push(obj);\n } else {\n let key = path[index];\n\n const value = obj[key];\n\n if (!isDefined(value)) {\n return\n }\n\n // If we're at the last value in the path, and if it's a string/number/bool,\n // add it to the list\n if (\n index === path.length - 1 &&\n (isString(value) || isNumber(value) || isBoolean(value))\n ) {\n list.push(toString(value));\n } else if (isArray(value)) {\n arr = true;\n // Search each item in the array.\n for (let i = 0, len = value.length; i < len; i += 1) {\n deepGet(value[i], path, index + 1);\n }\n } else if (path.length) {\n // An object. Recurse further.\n deepGet(value, path, index + 1);\n }\n }\n };\n\n // Backwards compatibility (since path used to be a string)\n deepGet(obj, isString(path) ? path.split('.') : path, 0);\n\n return arr ? list : list[0]\n}\n\nconst MatchOptions = {\n // Whether the matches should be included in the result set. When `true`, each record in the result\n // set will include the indices of the matched characters.\n // These can consequently be used for highlighting purposes.\n includeMatches: false,\n // When `true`, the matching function will continue to the end of a search pattern even if\n // a perfect match has already been located in the string.\n findAllMatches: false,\n // Minimum number of characters that must be matched before a result is considered a match\n minMatchCharLength: 1\n};\n\nconst BasicOptions = {\n // When `true`, the algorithm continues searching to the end of the input even if a perfect\n // match is found before the end of the same input.\n isCaseSensitive: false,\n // When true, the matching function will continue to the end of a search pattern even if\n includeScore: false,\n // List of properties that will be searched. This also supports nested properties.\n keys: [],\n // Whether to sort the result list, by score\n shouldSort: true,\n // Default sort function: sort by ascending score, ascending index\n sortFn: (a, b) =>\n a.score === b.score ? (a.idx < b.idx ? -1 : 1) : a.score < b.score ? -1 : 1\n};\n\nconst FuzzyOptions = {\n // Approximately where in the text is the pattern expected to be found?\n location: 0,\n // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match\n // (of both letters and location), a threshold of '1.0' would match anything.\n threshold: 0.6,\n // Determines how close the match must be to the fuzzy location (specified above).\n // An exact letter match which is 'distance' characters away from the fuzzy location\n // would score as a complete mismatch. A distance of '0' requires the match be at\n // the exact location specified, a threshold of '1000' would require a perfect match\n // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.\n distance: 100\n};\n\nconst AdvancedOptions = {\n // When `true`, it enables the use of unix-like search commands\n useExtendedSearch: false,\n // The get function to use when fetching an object's properties.\n // The default will search nested paths *ie foo.bar.baz*\n getFn: get,\n // When `true`, search will ignore `location` and `distance`, so it won't matter\n // where in the string the pattern appears.\n // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score\n ignoreLocation: false,\n // When `true`, the calculation for the relevance score (used for sorting) will\n // ignore the field-length norm.\n // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm\n ignoreFieldNorm: false,\n // The weight to determine how much field length norm effects scoring.\n fieldNormWeight: 1\n};\n\nvar Config = {\n ...BasicOptions,\n ...MatchOptions,\n ...FuzzyOptions,\n ...AdvancedOptions\n};\n\nconst SPACE = /[^ ]+/g;\n\n// Field-length norm: the shorter the field, the higher the weight.\n// Set to 3 decimals to reduce index size.\nfunction norm(weight = 1, mantissa = 3) {\n const cache = new Map();\n const m = Math.pow(10, mantissa);\n\n return {\n get(value) {\n const numTokens = value.match(SPACE).length;\n\n if (cache.has(numTokens)) {\n return cache.get(numTokens)\n }\n\n // Default function is 1/sqrt(x), weight makes that variable\n const norm = 1 / Math.pow(numTokens, 0.5 * weight);\n\n // In place of `toFixed(mantissa)`, for faster computation\n const n = parseFloat(Math.round(norm * m) / m);\n\n cache.set(numTokens, n);\n\n return n\n },\n clear() {\n cache.clear();\n }\n }\n}\n\nclass FuseIndex {\n constructor({\n getFn = Config.getFn,\n fieldNormWeight = Config.fieldNormWeight\n } = {}) {\n this.norm = norm(fieldNormWeight, 3);\n this.getFn = getFn;\n this.isCreated = false;\n\n this.setIndexRecords();\n }\n setSources(docs = []) {\n this.docs = docs;\n }\n setIndexRecords(records = []) {\n this.records = records;\n }\n setKeys(keys = []) {\n this.keys = keys;\n this._keysMap = {};\n keys.forEach((key, idx) => {\n this._keysMap[key.id] = idx;\n });\n }\n create() {\n if (this.isCreated || !this.docs.length) {\n return\n }\n\n this.isCreated = true;\n\n // List is Array\n if (isString(this.docs[0])) {\n this.docs.forEach((doc, docIndex) => {\n this._addString(doc, docIndex);\n });\n } else {\n // List is Array\n this.docs.forEach((doc, docIndex) => {\n this._addObject(doc, docIndex);\n });\n }\n\n this.norm.clear();\n }\n // Adds a doc to the end of the index\n add(doc) {\n const idx = this.size();\n\n if (isString(doc)) {\n this._addString(doc, idx);\n } else {\n this._addObject(doc, idx);\n }\n }\n // Removes the doc at the specified index of the index\n removeAt(idx) {\n this.records.splice(idx, 1);\n\n // Change ref index of every subsquent doc\n for (let i = idx, len = this.size(); i < len; i += 1) {\n this.records[i].i -= 1;\n }\n }\n getValueForItemAtKeyId(item, keyId) {\n return item[this._keysMap[keyId]]\n }\n size() {\n return this.records.length\n }\n _addString(doc, docIndex) {\n if (!isDefined(doc) || isBlank(doc)) {\n return\n }\n\n let record = {\n v: doc,\n i: docIndex,\n n: this.norm.get(doc)\n };\n\n this.records.push(record);\n }\n _addObject(doc, docIndex) {\n let record = { i: docIndex, $: {} };\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n this.keys.forEach((key, keyIndex) => {\n let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path);\n\n if (!isDefined(value)) {\n return\n }\n\n if (isArray(value)) {\n let subRecords = [];\n const stack = [{ nestedArrIndex: -1, value }];\n\n while (stack.length) {\n const { nestedArrIndex, value } = stack.pop();\n\n if (!isDefined(value)) {\n continue\n }\n\n if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n i: nestedArrIndex,\n n: this.norm.get(value)\n };\n\n subRecords.push(subRecord);\n } else if (isArray(value)) {\n value.forEach((item, k) => {\n stack.push({\n nestedArrIndex: k,\n value: item\n });\n });\n } else ;\n }\n record.$[keyIndex] = subRecords;\n } else if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n n: this.norm.get(value)\n };\n\n record.$[keyIndex] = subRecord;\n }\n });\n\n this.records.push(record);\n }\n toJSON() {\n return {\n keys: this.keys,\n records: this.records\n }\n }\n}\n\nfunction createIndex(\n keys,\n docs,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys.map(createKey));\n myIndex.setSources(docs);\n myIndex.create();\n return myIndex\n}\n\nfunction parseIndex(\n data,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const { keys, records } = data;\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys);\n myIndex.setIndexRecords(records);\n return myIndex\n}\n\nfunction computeScore$1(\n pattern,\n {\n errors = 0,\n currentLocation = 0,\n expectedLocation = 0,\n distance = Config.distance,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n const accuracy = errors / pattern.length;\n\n if (ignoreLocation) {\n return accuracy\n }\n\n const proximity = Math.abs(expectedLocation - currentLocation);\n\n if (!distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy\n }\n\n return accuracy + proximity / distance\n}\n\nfunction convertMaskToIndices(\n matchmask = [],\n minMatchCharLength = Config.minMatchCharLength\n) {\n let indices = [];\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (let len = matchmask.length; i < len; i += 1) {\n let match = matchmask[i];\n if (match && start === -1) {\n start = i;\n } else if (!match && start !== -1) {\n end = i - 1;\n if (end - start + 1 >= minMatchCharLength) {\n indices.push([start, end]);\n }\n start = -1;\n }\n }\n\n // (i-1 - start) + 1 => i - start\n if (matchmask[i - 1] && i - start >= minMatchCharLength) {\n indices.push([start, i - 1]);\n }\n\n return indices\n}\n\n// Machine word size\nconst MAX_BITS = 32;\n\nfunction search(\n text,\n pattern,\n patternAlphabet,\n {\n location = Config.location,\n distance = Config.distance,\n threshold = Config.threshold,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n includeMatches = Config.includeMatches,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n if (pattern.length > MAX_BITS) {\n throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS))\n }\n\n const patternLen = pattern.length;\n // Set starting location at beginning text and initialize the alphabet.\n const textLen = text.length;\n // Handle the case when location > text.length\n const expectedLocation = Math.max(0, Math.min(location, textLen));\n // Highest score beyond which we give up.\n let currentThreshold = threshold;\n // Is there a nearby exact match? (speedup)\n let bestLocation = expectedLocation;\n\n // Performance: only computer matches when the minMatchCharLength > 1\n // OR if `includeMatches` is true.\n const computeMatches = minMatchCharLength > 1 || includeMatches;\n // A mask of the matches, used for building the indices\n const matchMask = computeMatches ? Array(textLen) : [];\n\n let index;\n\n // Get all exact matches, here for speed up\n while ((index = text.indexOf(pattern, bestLocation)) > -1) {\n let score = computeScore$1(pattern, {\n currentLocation: index,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n currentThreshold = Math.min(score, currentThreshold);\n bestLocation = index + patternLen;\n\n if (computeMatches) {\n let i = 0;\n while (i < patternLen) {\n matchMask[index + i] = 1;\n i += 1;\n }\n }\n }\n\n // Reset the best location\n bestLocation = -1;\n\n let lastBitArr = [];\n let finalScore = 1;\n let binMax = patternLen + textLen;\n\n const mask = 1 << (patternLen - 1);\n\n for (let i = 0; i < patternLen; i += 1) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from the match location we can stray\n // at this error level.\n let binMin = 0;\n let binMid = binMax;\n\n while (binMin < binMid) {\n const score = computeScore$1(pattern, {\n errors: i,\n currentLocation: expectedLocation + binMid,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score <= currentThreshold) {\n binMin = binMid;\n } else {\n binMax = binMid;\n }\n\n binMid = Math.floor((binMax - binMin) / 2 + binMin);\n }\n\n // Use the result from this iteration as the maximum for the next.\n binMax = binMid;\n\n let start = Math.max(1, expectedLocation - binMid + 1);\n let finish = findAllMatches\n ? textLen\n : Math.min(expectedLocation + binMid, textLen) + patternLen;\n\n // Initialize the bit array\n let bitArr = Array(finish + 2);\n\n bitArr[finish + 1] = (1 << i) - 1;\n\n for (let j = finish; j >= start; j -= 1) {\n let currentLocation = j - 1;\n let charMatch = patternAlphabet[text.charAt(currentLocation)];\n\n if (computeMatches) {\n // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)\n matchMask[currentLocation] = +!!charMatch;\n }\n\n // First pass: exact match\n bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch;\n\n // Subsequent passes: fuzzy match\n if (i) {\n bitArr[j] |=\n ((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1 | lastBitArr[j + 1];\n }\n\n if (bitArr[j] & mask) {\n finalScore = computeScore$1(pattern, {\n errors: i,\n currentLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (finalScore <= currentThreshold) {\n // Indeed it is\n currentThreshold = finalScore;\n bestLocation = currentLocation;\n\n // Already passed `loc`, downhill from here on in.\n if (bestLocation <= expectedLocation) {\n break\n }\n\n // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.\n start = Math.max(1, 2 * expectedLocation - bestLocation);\n }\n }\n }\n\n // No hope for a (better) match at greater error levels.\n const score = computeScore$1(pattern, {\n errors: i + 1,\n currentLocation: expectedLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score > currentThreshold) {\n break\n }\n\n lastBitArr = bitArr;\n }\n\n const result = {\n isMatch: bestLocation >= 0,\n // Count exact matches (those with a score of 0) to be \"almost\" exact\n score: Math.max(0.001, finalScore)\n };\n\n if (computeMatches) {\n const indices = convertMaskToIndices(matchMask, minMatchCharLength);\n if (!indices.length) {\n result.isMatch = false;\n } else if (includeMatches) {\n result.indices = indices;\n }\n }\n\n return result\n}\n\nfunction createPatternAlphabet(pattern) {\n let mask = {};\n\n for (let i = 0, len = pattern.length; i < len; i += 1) {\n const char = pattern.charAt(i);\n mask[char] = (mask[char] || 0) | (1 << (len - i - 1));\n }\n\n return mask\n}\n\nclass BitapSearch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n this.options = {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreLocation\n };\n\n this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n\n this.chunks = [];\n\n if (!this.pattern.length) {\n return\n }\n\n const addChunk = (pattern, startIndex) => {\n this.chunks.push({\n pattern,\n alphabet: createPatternAlphabet(pattern),\n startIndex\n });\n };\n\n const len = this.pattern.length;\n\n if (len > MAX_BITS) {\n let i = 0;\n const remainder = len % MAX_BITS;\n const end = len - remainder;\n\n while (i < end) {\n addChunk(this.pattern.substr(i, MAX_BITS), i);\n i += MAX_BITS;\n }\n\n if (remainder) {\n const startIndex = len - MAX_BITS;\n addChunk(this.pattern.substr(startIndex), startIndex);\n }\n } else {\n addChunk(this.pattern, 0);\n }\n }\n\n searchIn(text) {\n const { isCaseSensitive, includeMatches } = this.options;\n\n if (!isCaseSensitive) {\n text = text.toLowerCase();\n }\n\n // Exact match\n if (this.pattern === text) {\n let result = {\n isMatch: true,\n score: 0\n };\n\n if (includeMatches) {\n result.indices = [[0, text.length - 1]];\n }\n\n return result\n }\n\n // Otherwise, use Bitap algorithm\n const {\n location,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n ignoreLocation\n } = this.options;\n\n let allIndices = [];\n let totalScore = 0;\n let hasMatches = false;\n\n this.chunks.forEach(({ pattern, alphabet, startIndex }) => {\n const { isMatch, score, indices } = search(text, pattern, alphabet, {\n location: location + startIndex,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n includeMatches,\n ignoreLocation\n });\n\n if (isMatch) {\n hasMatches = true;\n }\n\n totalScore += score;\n\n if (isMatch && indices) {\n allIndices = [...allIndices, ...indices];\n }\n });\n\n let result = {\n isMatch: hasMatches,\n score: hasMatches ? totalScore / this.chunks.length : 1\n };\n\n if (hasMatches && includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n}\n\nclass BaseMatch {\n constructor(pattern) {\n this.pattern = pattern;\n }\n static isMultiMatch(pattern) {\n return getMatch(pattern, this.multiRegex)\n }\n static isSingleMatch(pattern) {\n return getMatch(pattern, this.singleRegex)\n }\n search(/*text*/) {}\n}\n\nfunction getMatch(pattern, exp) {\n const matches = pattern.match(exp);\n return matches ? matches[1] : null\n}\n\n// Token: 'file\n\nclass ExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'exact'\n }\n static get multiRegex() {\n return /^=\"(.*)\"$/\n }\n static get singleRegex() {\n return /^=(.*)$/\n }\n search(text) {\n const isMatch = text === this.pattern;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !fire\n\nclass InverseExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!(.*)$/\n }\n search(text) {\n const index = text.indexOf(this.pattern);\n const isMatch = index === -1;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: ^file\n\nclass PrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'prefix-exact'\n }\n static get multiRegex() {\n return /^\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^\\^(.*)$/\n }\n search(text) {\n const isMatch = text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !^fire\n\nclass InversePrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-prefix-exact'\n }\n static get multiRegex() {\n return /^!\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!\\^(.*)$/\n }\n search(text) {\n const isMatch = !text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: .file$\n\nclass SuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'suffix-exact'\n }\n static get multiRegex() {\n return /^\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^(.*)\\$$/\n }\n search(text) {\n const isMatch = text.endsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [text.length - this.pattern.length, text.length - 1]\n }\n }\n}\n\n// Token: !.file$\n\nclass InverseSuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-suffix-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^!(.*)\\$$/\n }\n search(text) {\n const isMatch = !text.endsWith(this.pattern);\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\nclass FuzzyMatch extends BaseMatch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n super(pattern);\n this._bitapSearch = new BitapSearch(pattern, {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreLocation\n });\n }\n static get type() {\n return 'fuzzy'\n }\n static get multiRegex() {\n return /^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^(.*)$/\n }\n search(text) {\n return this._bitapSearch.searchIn(text)\n }\n}\n\n// Token: 'file\n\nclass IncludeMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'include'\n }\n static get multiRegex() {\n return /^'\"(.*)\"$/\n }\n static get singleRegex() {\n return /^'(.*)$/\n }\n search(text) {\n let location = 0;\n let index;\n\n const indices = [];\n const patternLen = this.pattern.length;\n\n // Get all exact matches\n while ((index = text.indexOf(this.pattern, location)) > -1) {\n location = index + patternLen;\n indices.push([index, location - 1]);\n }\n\n const isMatch = !!indices.length;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices\n }\n }\n}\n\n// ❗Order is important. DO NOT CHANGE.\nconst searchers = [\n ExactMatch,\n IncludeMatch,\n PrefixExactMatch,\n InversePrefixExactMatch,\n InverseSuffixExactMatch,\n SuffixExactMatch,\n InverseExactMatch,\n FuzzyMatch\n];\n\nconst searchersLen = searchers.length;\n\n// Regex to split by spaces, but keep anything in quotes together\nconst SPACE_RE = / +(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)/;\nconst OR_TOKEN = '|';\n\n// Return a 2D array representation of the query, for simpler parsing.\n// Example:\n// \"^core go$ | rb$ | py$ xy$\" => [[\"^core\", \"go$\"], [\"rb$\"], [\"py$\", \"xy$\"]]\nfunction parseQuery(pattern, options = {}) {\n return pattern.split(OR_TOKEN).map((item) => {\n let query = item\n .trim()\n .split(SPACE_RE)\n .filter((item) => item && !!item.trim());\n\n let results = [];\n for (let i = 0, len = query.length; i < len; i += 1) {\n const queryItem = query[i];\n\n // 1. Handle multiple query match (i.e, once that are quoted, like `\"hello world\"`)\n let found = false;\n let idx = -1;\n while (!found && ++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isMultiMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n found = true;\n }\n }\n\n if (found) {\n continue\n }\n\n // 2. Handle single query matches (i.e, once that are *not* quoted)\n idx = -1;\n while (++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isSingleMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n break\n }\n }\n }\n\n return results\n })\n}\n\n// These extended matchers can return an array of matches, as opposed\n// to a singl match\nconst MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]);\n\n/**\n * Command-like searching\n * ======================\n *\n * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,\n * search in a given text.\n *\n * Search syntax:\n *\n * | Token | Match type | Description |\n * | ----------- | -------------------------- | -------------------------------------- |\n * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |\n * | `=scheme` | exact-match | Items that are `scheme` |\n * | `'python` | include-match | Items that include `python` |\n * | `!ruby` | inverse-exact-match | Items that do not include `ruby` |\n * | `^java` | prefix-exact-match | Items that start with `java` |\n * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |\n * | `.js$` | suffix-exact-match | Items that end with `.js` |\n * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |\n *\n * A single pipe character acts as an OR operator. For example, the following\n * query matches entries that start with `core` and end with either`go`, `rb`,\n * or`py`.\n *\n * ```\n * ^core go$ | rb$ | py$\n * ```\n */\nclass ExtendedSearch {\n constructor(\n pattern,\n {\n isCaseSensitive = Config.isCaseSensitive,\n includeMatches = Config.includeMatches,\n minMatchCharLength = Config.minMatchCharLength,\n ignoreLocation = Config.ignoreLocation,\n findAllMatches = Config.findAllMatches,\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance\n } = {}\n ) {\n this.query = null;\n this.options = {\n isCaseSensitive,\n includeMatches,\n minMatchCharLength,\n findAllMatches,\n ignoreLocation,\n location,\n threshold,\n distance\n };\n\n this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n this.query = parseQuery(this.pattern, this.options);\n }\n\n static condition(_, options) {\n return options.useExtendedSearch\n }\n\n searchIn(text) {\n const query = this.query;\n\n if (!query) {\n return {\n isMatch: false,\n score: 1\n }\n }\n\n const { includeMatches, isCaseSensitive } = this.options;\n\n text = isCaseSensitive ? text : text.toLowerCase();\n\n let numMatches = 0;\n let allIndices = [];\n let totalScore = 0;\n\n // ORs\n for (let i = 0, qLen = query.length; i < qLen; i += 1) {\n const searchers = query[i];\n\n // Reset indices\n allIndices.length = 0;\n numMatches = 0;\n\n // ANDs\n for (let j = 0, pLen = searchers.length; j < pLen; j += 1) {\n const searcher = searchers[j];\n const { isMatch, indices, score } = searcher.search(text);\n\n if (isMatch) {\n numMatches += 1;\n totalScore += score;\n if (includeMatches) {\n const type = searcher.constructor.type;\n if (MultiMatchSet.has(type)) {\n allIndices = [...allIndices, ...indices];\n } else {\n allIndices.push(indices);\n }\n }\n } else {\n totalScore = 0;\n numMatches = 0;\n allIndices.length = 0;\n break\n }\n }\n\n // OR condition, so if TRUE, return\n if (numMatches) {\n let result = {\n isMatch: true,\n score: totalScore / numMatches\n };\n\n if (includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n }\n\n // Nothing was matched\n return {\n isMatch: false,\n score: 1\n }\n }\n}\n\nconst registeredSearchers = [];\n\nfunction register(...args) {\n registeredSearchers.push(...args);\n}\n\nfunction createSearcher(pattern, options) {\n for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {\n let searcherClass = registeredSearchers[i];\n if (searcherClass.condition(pattern, options)) {\n return new searcherClass(pattern, options)\n }\n }\n\n return new BitapSearch(pattern, options)\n}\n\nconst LogicalOperator = {\n AND: '$and',\n OR: '$or'\n};\n\nconst KeyType = {\n PATH: '$path',\n PATTERN: '$val'\n};\n\nconst isExpression = (query) =>\n !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);\n\nconst isPath = (query) => !!query[KeyType.PATH];\n\nconst isLeaf = (query) =>\n !isArray(query) && isObject(query) && !isExpression(query);\n\nconst convertToExplicit = (query) => ({\n [LogicalOperator.AND]: Object.keys(query).map((key) => ({\n [key]: query[key]\n }))\n});\n\n// When `auto` is `true`, the parse function will infer and initialize and add\n// the appropriate `Searcher` instance\nfunction parse(query, options, { auto = true } = {}) {\n const next = (query) => {\n let keys = Object.keys(query);\n\n const isQueryPath = isPath(query);\n\n if (!isQueryPath && keys.length > 1 && !isExpression(query)) {\n return next(convertToExplicit(query))\n }\n\n if (isLeaf(query)) {\n const key = isQueryPath ? query[KeyType.PATH] : keys[0];\n\n const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];\n\n if (!isString(pattern)) {\n throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key))\n }\n\n const obj = {\n keyId: createKeyId(key),\n pattern\n };\n\n if (auto) {\n obj.searcher = createSearcher(pattern, options);\n }\n\n return obj\n }\n\n let node = {\n children: [],\n operator: keys[0]\n };\n\n keys.forEach((key) => {\n const value = query[key];\n\n if (isArray(value)) {\n value.forEach((item) => {\n node.children.push(next(item));\n });\n }\n });\n\n return node\n };\n\n if (!isExpression(query)) {\n query = convertToExplicit(query);\n }\n\n return next(query)\n}\n\n// Practical scoring function\nfunction computeScore(\n results,\n { ignoreFieldNorm = Config.ignoreFieldNorm }\n) {\n results.forEach((result) => {\n let totalScore = 1;\n\n result.matches.forEach(({ key, norm, score }) => {\n const weight = key ? key.weight : null;\n\n totalScore *= Math.pow(\n score === 0 && weight ? Number.EPSILON : score,\n (weight || 1) * (ignoreFieldNorm ? 1 : norm)\n );\n });\n\n result.score = totalScore;\n });\n}\n\nfunction transformMatches(result, data) {\n const matches = result.matches;\n data.matches = [];\n\n if (!isDefined(matches)) {\n return\n }\n\n matches.forEach((match) => {\n if (!isDefined(match.indices) || !match.indices.length) {\n return\n }\n\n const { indices, value } = match;\n\n let obj = {\n indices,\n value\n };\n\n if (match.key) {\n obj.key = match.key.src;\n }\n\n if (match.idx > -1) {\n obj.refIndex = match.idx;\n }\n\n data.matches.push(obj);\n });\n}\n\nfunction transformScore(result, data) {\n data.score = result.score;\n}\n\nfunction format(\n results,\n docs,\n {\n includeMatches = Config.includeMatches,\n includeScore = Config.includeScore\n } = {}\n) {\n const transformers = [];\n\n if (includeMatches) transformers.push(transformMatches);\n if (includeScore) transformers.push(transformScore);\n\n return results.map((result) => {\n const { idx } = result;\n\n const data = {\n item: docs[idx],\n refIndex: idx\n };\n\n if (transformers.length) {\n transformers.forEach((transformer) => {\n transformer(result, data);\n });\n }\n\n return data\n })\n}\n\nclass Fuse {\n constructor(docs, options = {}, index) {\n this.options = { ...Config, ...options };\n\n if (\n this.options.useExtendedSearch &&\n !true\n ) {\n throw new Error(EXTENDED_SEARCH_UNAVAILABLE)\n }\n\n this._keyStore = new KeyStore(this.options.keys);\n\n this.setCollection(docs, index);\n }\n\n setCollection(docs, index) {\n this._docs = docs;\n\n if (index && !(index instanceof FuseIndex)) {\n throw new Error(INCORRECT_INDEX_TYPE)\n }\n\n this._myIndex =\n index ||\n createIndex(this.options.keys, this._docs, {\n getFn: this.options.getFn,\n fieldNormWeight: this.options.fieldNormWeight\n });\n }\n\n add(doc) {\n if (!isDefined(doc)) {\n return\n }\n\n this._docs.push(doc);\n this._myIndex.add(doc);\n }\n\n remove(predicate = (/* doc, idx */) => false) {\n const results = [];\n\n for (let i = 0, len = this._docs.length; i < len; i += 1) {\n const doc = this._docs[i];\n if (predicate(doc, i)) {\n this.removeAt(i);\n i -= 1;\n len -= 1;\n\n results.push(doc);\n }\n }\n\n return results\n }\n\n removeAt(idx) {\n this._docs.splice(idx, 1);\n this._myIndex.removeAt(idx);\n }\n\n getIndex() {\n return this._myIndex\n }\n\n search(query, { limit = -1 } = {}) {\n const {\n includeMatches,\n includeScore,\n shouldSort,\n sortFn,\n ignoreFieldNorm\n } = this.options;\n\n let results = isString(query)\n ? isString(this._docs[0])\n ? this._searchStringList(query)\n : this._searchObjectList(query)\n : this._searchLogical(query);\n\n computeScore(results, { ignoreFieldNorm });\n\n if (shouldSort) {\n results.sort(sortFn);\n }\n\n if (isNumber(limit) && limit > -1) {\n results = results.slice(0, limit);\n }\n\n return format(results, this._docs, {\n includeMatches,\n includeScore\n })\n }\n\n _searchStringList(query) {\n const searcher = createSearcher(query, this.options);\n const { records } = this._myIndex;\n const results = [];\n\n // Iterate over every string in the index\n records.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n results.push({\n item: text,\n idx,\n matches: [{ score, value: text, norm, indices }]\n });\n }\n });\n\n return results\n }\n\n _searchLogical(query) {\n\n const expression = parse(query, this.options);\n\n const evaluate = (node, item, idx) => {\n if (!node.children) {\n const { keyId, searcher } = node;\n\n const matches = this._findMatches({\n key: this._keyStore.get(keyId),\n value: this._myIndex.getValueForItemAtKeyId(item, keyId),\n searcher\n });\n\n if (matches && matches.length) {\n return [\n {\n idx,\n item,\n matches\n }\n ]\n }\n\n return []\n }\n\n const res = [];\n for (let i = 0, len = node.children.length; i < len; i += 1) {\n const child = node.children[i];\n const result = evaluate(child, item, idx);\n if (result.length) {\n res.push(...result);\n } else if (node.operator === LogicalOperator.AND) {\n return []\n }\n }\n return res\n };\n\n const records = this._myIndex.records;\n const resultMap = {};\n const results = [];\n\n records.forEach(({ $: item, i: idx }) => {\n if (isDefined(item)) {\n let expResults = evaluate(expression, item, idx);\n\n if (expResults.length) {\n // Dedupe when adding\n if (!resultMap[idx]) {\n resultMap[idx] = { idx, item, matches: [] };\n results.push(resultMap[idx]);\n }\n expResults.forEach(({ matches }) => {\n resultMap[idx].matches.push(...matches);\n });\n }\n }\n });\n\n return results\n }\n\n _searchObjectList(query) {\n const searcher = createSearcher(query, this.options);\n const { keys, records } = this._myIndex;\n const results = [];\n\n // List is Array\n records.forEach(({ $: item, i: idx }) => {\n if (!isDefined(item)) {\n return\n }\n\n let matches = [];\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n keys.forEach((key, keyIndex) => {\n matches.push(\n ...this._findMatches({\n key,\n value: item[keyIndex],\n searcher\n })\n );\n });\n\n if (matches.length) {\n results.push({\n idx,\n item,\n matches\n });\n }\n });\n\n return results\n }\n _findMatches({ key, value, searcher }) {\n if (!isDefined(value)) {\n return []\n }\n\n let matches = [];\n\n if (isArray(value)) {\n value.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({\n score,\n key,\n value: text,\n idx,\n norm,\n indices\n });\n }\n });\n } else {\n const { v: text, n: norm } = value;\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({ score, key, value: text, norm, indices });\n }\n }\n\n return matches\n }\n}\n\nFuse.version = '7.0.0';\nFuse.createIndex = createIndex;\nFuse.parseIndex = parseIndex;\nFuse.config = Config;\n\n{\n Fuse.parseQuery = parse;\n}\n\n{\n register(ExtendedSearch);\n}\n\nexport { Fuse as default };\n","import { ComfyNodeDefImpl } from '@/stores/nodeDefStore'\r\nimport { getNodeSource } from '@/types/nodeSource'\r\nimport Fuse, { IFuseOptions, FuseSearchOptions } from 'fuse.js'\r\nimport _ from 'lodash'\r\n\r\nexport class FuseSearch {\r\n private fuse: Fuse\r\n public readonly data: T[]\r\n\r\n constructor(\r\n data: T[],\r\n options?: IFuseOptions,\r\n createIndex: boolean = true\r\n ) {\r\n this.data = data\r\n const index =\r\n createIndex && options?.keys\r\n ? Fuse.createIndex(options.keys, data)\r\n : undefined\r\n this.fuse = new Fuse(data, options, index)\r\n }\r\n\r\n public search(query: string, options?: FuseSearchOptions): T[] {\r\n if (!query || query === '') {\r\n return [...this.data]\r\n }\r\n return this.fuse.search(query, options).map((result) => result.item)\r\n }\r\n}\r\n\r\nexport type FilterAndValue = [NodeFilter, T]\r\n\r\nexport abstract class NodeFilter {\r\n public abstract readonly id: string\r\n public abstract readonly name: string\r\n public abstract readonly invokeSequence: string\r\n public abstract readonly longInvokeSequence: string\r\n public readonly fuseSearch: FuseSearch\r\n\r\n constructor(\r\n nodeDefs: ComfyNodeDefImpl[],\r\n options?: IFuseOptions\r\n ) {\r\n this.fuseSearch = new FuseSearch(this.getAllNodeOptions(nodeDefs), options)\r\n }\r\n\r\n private getAllNodeOptions(nodeDefs: ComfyNodeDefImpl[]): FilterOptionT[] {\r\n return [\r\n ...new Set(\r\n nodeDefs.reduce((acc, nodeDef) => {\r\n return [...acc, ...this.getNodeOptions(nodeDef)]\r\n }, [])\r\n )\r\n ]\r\n }\r\n\r\n public abstract getNodeOptions(node: ComfyNodeDefImpl): FilterOptionT[]\r\n\r\n public matches(node: ComfyNodeDefImpl, value: FilterOptionT): boolean {\r\n if (value === '*') {\r\n return true\r\n }\r\n const options = this.getNodeOptions(node)\r\n return (\r\n options.includes(value) || _.some(options, (option) => option === '*')\r\n )\r\n }\r\n}\r\n\r\nexport class InputTypeFilter extends NodeFilter {\r\n public readonly id: string = 'input'\r\n public readonly name = 'Input Type'\r\n public readonly invokeSequence = 'i'\r\n public readonly longInvokeSequence = 'input'\r\n\r\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\r\n return node.input.all.map((input) => input.type)\r\n }\r\n}\r\n\r\nexport class OutputTypeFilter extends NodeFilter {\r\n public readonly id: string = 'output'\r\n public readonly name = 'Output Type'\r\n public readonly invokeSequence = 'o'\r\n public readonly longInvokeSequence = 'output'\r\n\r\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\r\n return node.output.all.map((output) => output.type)\r\n }\r\n}\r\n\r\nexport class NodeSourceFilter extends NodeFilter {\r\n public readonly id: string = 'source'\r\n public readonly name = 'Source'\r\n public readonly invokeSequence = 's'\r\n public readonly longInvokeSequence = 'source'\r\n\r\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\r\n return [getNodeSource(node.python_module).displayText]\r\n }\r\n}\r\n\r\nexport class NodeCategoryFilter extends NodeFilter {\r\n public readonly id: string = 'category'\r\n public readonly name = 'Category'\r\n public readonly invokeSequence = 'c'\r\n public readonly longInvokeSequence = 'category'\r\n\r\n public override getNodeOptions(node: ComfyNodeDefImpl): string[] {\r\n return [node.category]\r\n }\r\n}\r\n\r\nexport class NodeSearchService {\r\n public readonly nodeFuseSearch: FuseSearch\r\n public readonly nodeFilters: NodeFilter[]\r\n\r\n constructor(data: ComfyNodeDefImpl[]) {\r\n this.nodeFuseSearch = new FuseSearch(data, {\r\n keys: ['name', 'display_name'],\r\n includeScore: true,\r\n threshold: 0.3,\r\n shouldSort: true,\r\n useExtendedSearch: true\r\n })\r\n\r\n const filterSearchOptions = {\r\n includeScore: true,\r\n threshold: 0.3,\r\n shouldSort: true\r\n }\r\n\r\n this.nodeFilters = [\r\n new InputTypeFilter(data, filterSearchOptions),\r\n new OutputTypeFilter(data, filterSearchOptions),\r\n new NodeCategoryFilter(data, filterSearchOptions)\r\n ]\r\n\r\n if (data[0].python_module !== undefined) {\r\n this.nodeFilters.push(new NodeSourceFilter(data, filterSearchOptions))\r\n }\r\n }\r\n\r\n public endsWithFilterStartSequence(query: string): boolean {\r\n return query.endsWith(':')\r\n }\r\n\r\n public searchNode(\r\n query: string,\r\n filters: FilterAndValue[] = [],\r\n options?: FuseSearchOptions\r\n ): ComfyNodeDefImpl[] {\r\n const matchedNodes = this.nodeFuseSearch.search(query)\r\n\r\n const results = matchedNodes.filter((node) => {\r\n return _.every(filters, (filterAndValue) => {\r\n const [filter, value] = filterAndValue\r\n return filter.matches(node, value)\r\n })\r\n })\r\n\r\n return options?.limit ? results.slice(0, options.limit) : results\r\n }\r\n\r\n public getFilterById(id: string): NodeFilter | undefined {\r\n return this.nodeFilters.find((filter) => filter.id === id)\r\n }\r\n}\r\n","export var TransformationType;\n(function (TransformationType) {\n TransformationType[TransformationType[\"PLAIN_TO_CLASS\"] = 0] = \"PLAIN_TO_CLASS\";\n TransformationType[TransformationType[\"CLASS_TO_PLAIN\"] = 1] = \"CLASS_TO_PLAIN\";\n TransformationType[TransformationType[\"CLASS_TO_CLASS\"] = 2] = \"CLASS_TO_CLASS\";\n})(TransformationType || (TransformationType = {}));\n//# sourceMappingURL=transformation-type.enum.js.map","import { TransformationType } from './enums';\n/**\n * Storage all library metadata.\n */\nvar MetadataStorage = /** @class */ (function () {\n function MetadataStorage() {\n // -------------------------------------------------------------------------\n // Properties\n // -------------------------------------------------------------------------\n this._typeMetadatas = new Map();\n this._transformMetadatas = new Map();\n this._exposeMetadatas = new Map();\n this._excludeMetadatas = new Map();\n this._ancestorsMap = new Map();\n }\n // -------------------------------------------------------------------------\n // Adder Methods\n // -------------------------------------------------------------------------\n MetadataStorage.prototype.addTypeMetadata = function (metadata) {\n if (!this._typeMetadatas.has(metadata.target)) {\n this._typeMetadatas.set(metadata.target, new Map());\n }\n this._typeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);\n };\n MetadataStorage.prototype.addTransformMetadata = function (metadata) {\n if (!this._transformMetadatas.has(metadata.target)) {\n this._transformMetadatas.set(metadata.target, new Map());\n }\n if (!this._transformMetadatas.get(metadata.target).has(metadata.propertyName)) {\n this._transformMetadatas.get(metadata.target).set(metadata.propertyName, []);\n }\n this._transformMetadatas.get(metadata.target).get(metadata.propertyName).push(metadata);\n };\n MetadataStorage.prototype.addExposeMetadata = function (metadata) {\n if (!this._exposeMetadatas.has(metadata.target)) {\n this._exposeMetadatas.set(metadata.target, new Map());\n }\n this._exposeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);\n };\n MetadataStorage.prototype.addExcludeMetadata = function (metadata) {\n if (!this._excludeMetadatas.has(metadata.target)) {\n this._excludeMetadatas.set(metadata.target, new Map());\n }\n this._excludeMetadatas.get(metadata.target).set(metadata.propertyName, metadata);\n };\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n MetadataStorage.prototype.findTransformMetadatas = function (target, propertyName, transformationType) {\n return this.findMetadatas(this._transformMetadatas, target, propertyName).filter(function (metadata) {\n if (!metadata.options)\n return true;\n if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)\n return true;\n if (metadata.options.toClassOnly === true) {\n return (transformationType === TransformationType.CLASS_TO_CLASS ||\n transformationType === TransformationType.PLAIN_TO_CLASS);\n }\n if (metadata.options.toPlainOnly === true) {\n return transformationType === TransformationType.CLASS_TO_PLAIN;\n }\n return true;\n });\n };\n MetadataStorage.prototype.findExcludeMetadata = function (target, propertyName) {\n return this.findMetadata(this._excludeMetadatas, target, propertyName);\n };\n MetadataStorage.prototype.findExposeMetadata = function (target, propertyName) {\n return this.findMetadata(this._exposeMetadatas, target, propertyName);\n };\n MetadataStorage.prototype.findExposeMetadataByCustomName = function (target, name) {\n return this.getExposedMetadatas(target).find(function (metadata) {\n return metadata.options && metadata.options.name === name;\n });\n };\n MetadataStorage.prototype.findTypeMetadata = function (target, propertyName) {\n return this.findMetadata(this._typeMetadatas, target, propertyName);\n };\n MetadataStorage.prototype.getStrategy = function (target) {\n var excludeMap = this._excludeMetadatas.get(target);\n var exclude = excludeMap && excludeMap.get(undefined);\n var exposeMap = this._exposeMetadatas.get(target);\n var expose = exposeMap && exposeMap.get(undefined);\n if ((exclude && expose) || (!exclude && !expose))\n return 'none';\n return exclude ? 'excludeAll' : 'exposeAll';\n };\n MetadataStorage.prototype.getExposedMetadatas = function (target) {\n return this.getMetadata(this._exposeMetadatas, target);\n };\n MetadataStorage.prototype.getExcludedMetadatas = function (target) {\n return this.getMetadata(this._excludeMetadatas, target);\n };\n MetadataStorage.prototype.getExposedProperties = function (target, transformationType) {\n return this.getExposedMetadatas(target)\n .filter(function (metadata) {\n if (!metadata.options)\n return true;\n if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)\n return true;\n if (metadata.options.toClassOnly === true) {\n return (transformationType === TransformationType.CLASS_TO_CLASS ||\n transformationType === TransformationType.PLAIN_TO_CLASS);\n }\n if (metadata.options.toPlainOnly === true) {\n return transformationType === TransformationType.CLASS_TO_PLAIN;\n }\n return true;\n })\n .map(function (metadata) { return metadata.propertyName; });\n };\n MetadataStorage.prototype.getExcludedProperties = function (target, transformationType) {\n return this.getExcludedMetadatas(target)\n .filter(function (metadata) {\n if (!metadata.options)\n return true;\n if (metadata.options.toClassOnly === true && metadata.options.toPlainOnly === true)\n return true;\n if (metadata.options.toClassOnly === true) {\n return (transformationType === TransformationType.CLASS_TO_CLASS ||\n transformationType === TransformationType.PLAIN_TO_CLASS);\n }\n if (metadata.options.toPlainOnly === true) {\n return transformationType === TransformationType.CLASS_TO_PLAIN;\n }\n return true;\n })\n .map(function (metadata) { return metadata.propertyName; });\n };\n MetadataStorage.prototype.clear = function () {\n this._typeMetadatas.clear();\n this._exposeMetadatas.clear();\n this._excludeMetadatas.clear();\n this._ancestorsMap.clear();\n };\n // -------------------------------------------------------------------------\n // Private Methods\n // -------------------------------------------------------------------------\n MetadataStorage.prototype.getMetadata = function (metadatas, target) {\n var metadataFromTargetMap = metadatas.get(target);\n var metadataFromTarget;\n if (metadataFromTargetMap) {\n metadataFromTarget = Array.from(metadataFromTargetMap.values()).filter(function (meta) { return meta.propertyName !== undefined; });\n }\n var metadataFromAncestors = [];\n for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {\n var ancestor = _a[_i];\n var ancestorMetadataMap = metadatas.get(ancestor);\n if (ancestorMetadataMap) {\n var metadataFromAncestor = Array.from(ancestorMetadataMap.values()).filter(function (meta) { return meta.propertyName !== undefined; });\n metadataFromAncestors.push.apply(metadataFromAncestors, metadataFromAncestor);\n }\n }\n return metadataFromAncestors.concat(metadataFromTarget || []);\n };\n MetadataStorage.prototype.findMetadata = function (metadatas, target, propertyName) {\n var metadataFromTargetMap = metadatas.get(target);\n if (metadataFromTargetMap) {\n var metadataFromTarget = metadataFromTargetMap.get(propertyName);\n if (metadataFromTarget) {\n return metadataFromTarget;\n }\n }\n for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {\n var ancestor = _a[_i];\n var ancestorMetadataMap = metadatas.get(ancestor);\n if (ancestorMetadataMap) {\n var ancestorResult = ancestorMetadataMap.get(propertyName);\n if (ancestorResult) {\n return ancestorResult;\n }\n }\n }\n return undefined;\n };\n MetadataStorage.prototype.findMetadatas = function (metadatas, target, propertyName) {\n var metadataFromTargetMap = metadatas.get(target);\n var metadataFromTarget;\n if (metadataFromTargetMap) {\n metadataFromTarget = metadataFromTargetMap.get(propertyName);\n }\n var metadataFromAncestorsTarget = [];\n for (var _i = 0, _a = this.getAncestors(target); _i < _a.length; _i++) {\n var ancestor = _a[_i];\n var ancestorMetadataMap = metadatas.get(ancestor);\n if (ancestorMetadataMap) {\n if (ancestorMetadataMap.has(propertyName)) {\n metadataFromAncestorsTarget.push.apply(metadataFromAncestorsTarget, ancestorMetadataMap.get(propertyName));\n }\n }\n }\n return metadataFromAncestorsTarget\n .slice()\n .reverse()\n .concat((metadataFromTarget || []).slice().reverse());\n };\n MetadataStorage.prototype.getAncestors = function (target) {\n if (!target)\n return [];\n if (!this._ancestorsMap.has(target)) {\n var ancestors = [];\n for (var baseClass = Object.getPrototypeOf(target.prototype.constructor); typeof baseClass.prototype !== 'undefined'; baseClass = Object.getPrototypeOf(baseClass.prototype.constructor)) {\n ancestors.push(baseClass);\n }\n this._ancestorsMap.set(target, ancestors);\n }\n return this._ancestorsMap.get(target);\n };\n return MetadataStorage;\n}());\nexport { MetadataStorage };\n//# sourceMappingURL=MetadataStorage.js.map","import { MetadataStorage } from './MetadataStorage';\n/**\n * Default metadata storage is used as singleton and can be used to storage all metadatas.\n */\nexport var defaultMetadataStorage = new MetadataStorage();\n//# sourceMappingURL=storage.js.map","/**\n * This function returns the global object across Node and browsers.\n *\n * Note: `globalThis` is the standardized approach however it has been added to\n * Node.js in version 12. We need to include this snippet until Node 12 EOL.\n */\nexport function getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: Cannot find name 'window'.\n if (typeof window !== 'undefined') {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: Cannot find name 'window'.\n return window;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: Cannot find name 'self'.\n if (typeof self !== 'undefined') {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: Cannot find name 'self'.\n return self;\n }\n}\n//# sourceMappingURL=get-global.util.js.map","export function isPromise(p) {\n return p !== null && typeof p === 'object' && typeof p.then === 'function';\n}\n//# sourceMappingURL=is-promise.util.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { defaultMetadataStorage } from './storage';\nimport { TransformationType } from './enums';\nimport { getGlobal, isPromise } from './utils';\nfunction instantiateArrayType(arrayType) {\n var array = new arrayType();\n if (!(array instanceof Set) && !('push' in array)) {\n return [];\n }\n return array;\n}\nvar TransformOperationExecutor = /** @class */ (function () {\n // -------------------------------------------------------------------------\n // Constructor\n // -------------------------------------------------------------------------\n function TransformOperationExecutor(transformationType, options) {\n this.transformationType = transformationType;\n this.options = options;\n // -------------------------------------------------------------------------\n // Private Properties\n // -------------------------------------------------------------------------\n this.recursionStack = new Set();\n }\n // -------------------------------------------------------------------------\n // Public Methods\n // -------------------------------------------------------------------------\n TransformOperationExecutor.prototype.transform = function (source, value, targetType, arrayType, isMap, level) {\n var _this = this;\n if (level === void 0) { level = 0; }\n if (Array.isArray(value) || value instanceof Set) {\n var newValue_1 = arrayType && this.transformationType === TransformationType.PLAIN_TO_CLASS\n ? instantiateArrayType(arrayType)\n : [];\n value.forEach(function (subValue, index) {\n var subSource = source ? source[index] : undefined;\n if (!_this.options.enableCircularCheck || !_this.isCircular(subValue)) {\n var realTargetType = void 0;\n if (typeof targetType !== 'function' &&\n targetType &&\n targetType.options &&\n targetType.options.discriminator &&\n targetType.options.discriminator.property &&\n targetType.options.discriminator.subTypes) {\n if (_this.transformationType === TransformationType.PLAIN_TO_CLASS) {\n realTargetType = targetType.options.discriminator.subTypes.find(function (subType) {\n return subType.name === subValue[targetType.options.discriminator.property];\n });\n var options = { newObject: newValue_1, object: subValue, property: undefined };\n var newType = targetType.typeFunction(options);\n realTargetType === undefined ? (realTargetType = newType) : (realTargetType = realTargetType.value);\n if (!targetType.options.keepDiscriminatorProperty)\n delete subValue[targetType.options.discriminator.property];\n }\n if (_this.transformationType === TransformationType.CLASS_TO_CLASS) {\n realTargetType = subValue.constructor;\n }\n if (_this.transformationType === TransformationType.CLASS_TO_PLAIN) {\n subValue[targetType.options.discriminator.property] = targetType.options.discriminator.subTypes.find(function (subType) { return subType.value === subValue.constructor; }).name;\n }\n }\n else {\n realTargetType = targetType;\n }\n var value_1 = _this.transform(subSource, subValue, realTargetType, undefined, subValue instanceof Map, level + 1);\n if (newValue_1 instanceof Set) {\n newValue_1.add(value_1);\n }\n else {\n newValue_1.push(value_1);\n }\n }\n else if (_this.transformationType === TransformationType.CLASS_TO_CLASS) {\n if (newValue_1 instanceof Set) {\n newValue_1.add(subValue);\n }\n else {\n newValue_1.push(subValue);\n }\n }\n });\n return newValue_1;\n }\n else if (targetType === String && !isMap) {\n if (value === null || value === undefined)\n return value;\n return String(value);\n }\n else if (targetType === Number && !isMap) {\n if (value === null || value === undefined)\n return value;\n return Number(value);\n }\n else if (targetType === Boolean && !isMap) {\n if (value === null || value === undefined)\n return value;\n return Boolean(value);\n }\n else if ((targetType === Date || value instanceof Date) && !isMap) {\n if (value instanceof Date) {\n return new Date(value.valueOf());\n }\n if (value === null || value === undefined)\n return value;\n return new Date(value);\n }\n else if (!!getGlobal().Buffer && (targetType === Buffer || value instanceof Buffer) && !isMap) {\n if (value === null || value === undefined)\n return value;\n return Buffer.from(value);\n }\n else if (isPromise(value) && !isMap) {\n return new Promise(function (resolve, reject) {\n value.then(function (data) { return resolve(_this.transform(undefined, data, targetType, undefined, undefined, level + 1)); }, reject);\n });\n }\n else if (!isMap && value !== null && typeof value === 'object' && typeof value.then === 'function') {\n // Note: We should not enter this, as promise has been handled above\n // This option simply returns the Promise preventing a JS error from happening and should be an inaccessible path.\n return value; // skip promise transformation\n }\n else if (typeof value === 'object' && value !== null) {\n // try to guess the type\n if (!targetType && value.constructor !== Object /* && TransformationType === TransformationType.CLASS_TO_PLAIN*/)\n if (!Array.isArray(value) && value.constructor === Array) {\n // Somebody attempts to convert special Array like object to Array, eg:\n // const evilObject = { '100000000': '100000000', __proto__: [] };\n // This could be used to cause Denial-of-service attack so we don't allow it.\n // See prevent-array-bomb.spec.ts for more details.\n }\n else {\n // We are good we can use the built-in constructor\n targetType = value.constructor;\n }\n if (!targetType && source)\n targetType = source.constructor;\n if (this.options.enableCircularCheck) {\n // add transformed type to prevent circular references\n this.recursionStack.add(value);\n }\n var keys = this.getKeys(targetType, value, isMap);\n var newValue = source ? source : {};\n if (!source &&\n (this.transformationType === TransformationType.PLAIN_TO_CLASS ||\n this.transformationType === TransformationType.CLASS_TO_CLASS)) {\n if (isMap) {\n newValue = new Map();\n }\n else if (targetType) {\n newValue = new targetType();\n }\n else {\n newValue = {};\n }\n }\n var _loop_1 = function (key) {\n if (key === '__proto__' || key === 'constructor') {\n return \"continue\";\n }\n var valueKey = key;\n var newValueKey = key, propertyName = key;\n if (!this_1.options.ignoreDecorators && targetType) {\n if (this_1.transformationType === TransformationType.PLAIN_TO_CLASS) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadataByCustomName(targetType, key);\n if (exposeMetadata) {\n propertyName = exposeMetadata.propertyName;\n newValueKey = exposeMetadata.propertyName;\n }\n }\n else if (this_1.transformationType === TransformationType.CLASS_TO_PLAIN ||\n this_1.transformationType === TransformationType.CLASS_TO_CLASS) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadata(targetType, key);\n if (exposeMetadata && exposeMetadata.options && exposeMetadata.options.name) {\n newValueKey = exposeMetadata.options.name;\n }\n }\n }\n // get a subvalue\n var subValue = undefined;\n if (this_1.transformationType === TransformationType.PLAIN_TO_CLASS) {\n /**\n * This section is added for the following report:\n * https://github.com/typestack/class-transformer/issues/596\n *\n * We should not call functions or constructors when transforming to class.\n */\n subValue = value[valueKey];\n }\n else {\n if (value instanceof Map) {\n subValue = value.get(valueKey);\n }\n else if (value[valueKey] instanceof Function) {\n subValue = value[valueKey]();\n }\n else {\n subValue = value[valueKey];\n }\n }\n // determine a type\n var type = undefined, isSubValueMap = subValue instanceof Map;\n if (targetType && isMap) {\n type = targetType;\n }\n else if (targetType) {\n var metadata_1 = defaultMetadataStorage.findTypeMetadata(targetType, propertyName);\n if (metadata_1) {\n var options = { newObject: newValue, object: value, property: propertyName };\n var newType = metadata_1.typeFunction ? metadata_1.typeFunction(options) : metadata_1.reflectedType;\n if (metadata_1.options &&\n metadata_1.options.discriminator &&\n metadata_1.options.discriminator.property &&\n metadata_1.options.discriminator.subTypes) {\n if (!(value[valueKey] instanceof Array)) {\n if (this_1.transformationType === TransformationType.PLAIN_TO_CLASS) {\n type = metadata_1.options.discriminator.subTypes.find(function (subType) {\n if (subValue && subValue instanceof Object && metadata_1.options.discriminator.property in subValue) {\n return subType.name === subValue[metadata_1.options.discriminator.property];\n }\n });\n type === undefined ? (type = newType) : (type = type.value);\n if (!metadata_1.options.keepDiscriminatorProperty) {\n if (subValue && subValue instanceof Object && metadata_1.options.discriminator.property in subValue) {\n delete subValue[metadata_1.options.discriminator.property];\n }\n }\n }\n if (this_1.transformationType === TransformationType.CLASS_TO_CLASS) {\n type = subValue.constructor;\n }\n if (this_1.transformationType === TransformationType.CLASS_TO_PLAIN) {\n if (subValue) {\n subValue[metadata_1.options.discriminator.property] = metadata_1.options.discriminator.subTypes.find(function (subType) { return subType.value === subValue.constructor; }).name;\n }\n }\n }\n else {\n type = metadata_1;\n }\n }\n else {\n type = newType;\n }\n isSubValueMap = isSubValueMap || metadata_1.reflectedType === Map;\n }\n else if (this_1.options.targetMaps) {\n // try to find a type in target maps\n this_1.options.targetMaps\n .filter(function (map) { return map.target === targetType && !!map.properties[propertyName]; })\n .forEach(function (map) { return (type = map.properties[propertyName]); });\n }\n else if (this_1.options.enableImplicitConversion &&\n this_1.transformationType === TransformationType.PLAIN_TO_CLASS) {\n // if we have no registererd type via the @Type() decorator then we check if we have any\n // type declarations in reflect-metadata (type declaration is emited only if some decorator is added to the property.)\n var reflectedType = Reflect.getMetadata('design:type', targetType.prototype, propertyName);\n if (reflectedType) {\n type = reflectedType;\n }\n }\n }\n // if value is an array try to get its custom array type\n var arrayType_1 = Array.isArray(value[valueKey])\n ? this_1.getReflectedType(targetType, propertyName)\n : undefined;\n // const subValueKey = TransformationType === TransformationType.PLAIN_TO_CLASS && newKeyName ? newKeyName : key;\n var subSource = source ? source[valueKey] : undefined;\n // if its deserialization then type if required\n // if we uncomment this types like string[] will not work\n // if (this.transformationType === TransformationType.PLAIN_TO_CLASS && !type && subValue instanceof Object && !(subValue instanceof Date))\n // throw new Error(`Cannot determine type for ${(targetType as any).name }.${propertyName}, did you forget to specify a @Type?`);\n // if newValue is a source object that has method that match newKeyName then skip it\n if (newValue.constructor.prototype) {\n var descriptor = Object.getOwnPropertyDescriptor(newValue.constructor.prototype, newValueKey);\n if ((this_1.transformationType === TransformationType.PLAIN_TO_CLASS ||\n this_1.transformationType === TransformationType.CLASS_TO_CLASS) &&\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ((descriptor && !descriptor.set) || newValue[newValueKey] instanceof Function))\n return \"continue\";\n }\n if (!this_1.options.enableCircularCheck || !this_1.isCircular(subValue)) {\n var transformKey = this_1.transformationType === TransformationType.PLAIN_TO_CLASS ? newValueKey : key;\n var finalValue = void 0;\n if (this_1.transformationType === TransformationType.CLASS_TO_PLAIN) {\n // Get original value\n finalValue = value[transformKey];\n // Apply custom transformation\n finalValue = this_1.applyCustomTransformations(finalValue, targetType, transformKey, value, this_1.transformationType);\n // If nothing change, it means no custom transformation was applied, so use the subValue.\n finalValue = value[transformKey] === finalValue ? subValue : finalValue;\n // Apply the default transformation\n finalValue = this_1.transform(subSource, finalValue, type, arrayType_1, isSubValueMap, level + 1);\n }\n else {\n if (subValue === undefined && this_1.options.exposeDefaultValues) {\n // Set default value if nothing provided\n finalValue = newValue[newValueKey];\n }\n else {\n finalValue = this_1.transform(subSource, subValue, type, arrayType_1, isSubValueMap, level + 1);\n finalValue = this_1.applyCustomTransformations(finalValue, targetType, transformKey, value, this_1.transformationType);\n }\n }\n if (finalValue !== undefined || this_1.options.exposeUnsetFields) {\n if (newValue instanceof Map) {\n newValue.set(newValueKey, finalValue);\n }\n else {\n newValue[newValueKey] = finalValue;\n }\n }\n }\n else if (this_1.transformationType === TransformationType.CLASS_TO_CLASS) {\n var finalValue = subValue;\n finalValue = this_1.applyCustomTransformations(finalValue, targetType, key, value, this_1.transformationType);\n if (finalValue !== undefined || this_1.options.exposeUnsetFields) {\n if (newValue instanceof Map) {\n newValue.set(newValueKey, finalValue);\n }\n else {\n newValue[newValueKey] = finalValue;\n }\n }\n }\n };\n var this_1 = this;\n // traverse over keys\n for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {\n var key = keys_1[_i];\n _loop_1(key);\n }\n if (this.options.enableCircularCheck) {\n this.recursionStack.delete(value);\n }\n return newValue;\n }\n else {\n return value;\n }\n };\n TransformOperationExecutor.prototype.applyCustomTransformations = function (value, target, key, obj, transformationType) {\n var _this = this;\n var metadatas = defaultMetadataStorage.findTransformMetadatas(target, key, this.transformationType);\n // apply versioning options\n if (this.options.version !== undefined) {\n metadatas = metadatas.filter(function (metadata) {\n if (!metadata.options)\n return true;\n return _this.checkVersion(metadata.options.since, metadata.options.until);\n });\n }\n // apply grouping options\n if (this.options.groups && this.options.groups.length) {\n metadatas = metadatas.filter(function (metadata) {\n if (!metadata.options)\n return true;\n return _this.checkGroups(metadata.options.groups);\n });\n }\n else {\n metadatas = metadatas.filter(function (metadata) {\n return !metadata.options || !metadata.options.groups || !metadata.options.groups.length;\n });\n }\n metadatas.forEach(function (metadata) {\n value = metadata.transformFn({ value: value, key: key, obj: obj, type: transformationType, options: _this.options });\n });\n return value;\n };\n // preventing circular references\n TransformOperationExecutor.prototype.isCircular = function (object) {\n return this.recursionStack.has(object);\n };\n TransformOperationExecutor.prototype.getReflectedType = function (target, propertyName) {\n if (!target)\n return undefined;\n var meta = defaultMetadataStorage.findTypeMetadata(target, propertyName);\n return meta ? meta.reflectedType : undefined;\n };\n TransformOperationExecutor.prototype.getKeys = function (target, object, isMap) {\n var _this = this;\n // determine exclusion strategy\n var strategy = defaultMetadataStorage.getStrategy(target);\n if (strategy === 'none')\n strategy = this.options.strategy || 'exposeAll'; // exposeAll is default strategy\n // get all keys that need to expose\n var keys = [];\n if (strategy === 'exposeAll' || isMap) {\n if (object instanceof Map) {\n keys = Array.from(object.keys());\n }\n else {\n keys = Object.keys(object);\n }\n }\n if (isMap) {\n // expose & exclude do not apply for map keys only to fields\n return keys;\n }\n /**\n * If decorators are ignored but we don't want the extraneous values, then we use the\n * metadata to decide which property is needed, but doesn't apply the decorator effect.\n */\n if (this.options.ignoreDecorators && this.options.excludeExtraneousValues && target) {\n var exposedProperties = defaultMetadataStorage.getExposedProperties(target, this.transformationType);\n var excludedProperties = defaultMetadataStorage.getExcludedProperties(target, this.transformationType);\n keys = __spreadArray(__spreadArray([], exposedProperties, true), excludedProperties, true);\n }\n if (!this.options.ignoreDecorators && target) {\n // add all exposed to list of keys\n var exposedProperties = defaultMetadataStorage.getExposedProperties(target, this.transformationType);\n if (this.transformationType === TransformationType.PLAIN_TO_CLASS) {\n exposedProperties = exposedProperties.map(function (key) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadata(target, key);\n if (exposeMetadata && exposeMetadata.options && exposeMetadata.options.name) {\n return exposeMetadata.options.name;\n }\n return key;\n });\n }\n if (this.options.excludeExtraneousValues) {\n keys = exposedProperties;\n }\n else {\n keys = keys.concat(exposedProperties);\n }\n // exclude excluded properties\n var excludedProperties_1 = defaultMetadataStorage.getExcludedProperties(target, this.transformationType);\n if (excludedProperties_1.length > 0) {\n keys = keys.filter(function (key) {\n return !excludedProperties_1.includes(key);\n });\n }\n // apply versioning options\n if (this.options.version !== undefined) {\n keys = keys.filter(function (key) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadata(target, key);\n if (!exposeMetadata || !exposeMetadata.options)\n return true;\n return _this.checkVersion(exposeMetadata.options.since, exposeMetadata.options.until);\n });\n }\n // apply grouping options\n if (this.options.groups && this.options.groups.length) {\n keys = keys.filter(function (key) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadata(target, key);\n if (!exposeMetadata || !exposeMetadata.options)\n return true;\n return _this.checkGroups(exposeMetadata.options.groups);\n });\n }\n else {\n keys = keys.filter(function (key) {\n var exposeMetadata = defaultMetadataStorage.findExposeMetadata(target, key);\n return (!exposeMetadata ||\n !exposeMetadata.options ||\n !exposeMetadata.options.groups ||\n !exposeMetadata.options.groups.length);\n });\n }\n }\n // exclude prefixed properties\n if (this.options.excludePrefixes && this.options.excludePrefixes.length) {\n keys = keys.filter(function (key) {\n return _this.options.excludePrefixes.every(function (prefix) {\n return key.substr(0, prefix.length) !== prefix;\n });\n });\n }\n // make sure we have unique keys\n keys = keys.filter(function (key, index, self) {\n return self.indexOf(key) === index;\n });\n return keys;\n };\n TransformOperationExecutor.prototype.checkVersion = function (since, until) {\n var decision = true;\n if (decision && since)\n decision = this.options.version >= since;\n if (decision && until)\n decision = this.options.version < until;\n return decision;\n };\n TransformOperationExecutor.prototype.checkGroups = function (groups) {\n if (!groups)\n return true;\n return this.options.groups.some(function (optionGroup) { return groups.includes(optionGroup); });\n };\n return TransformOperationExecutor;\n}());\nexport { TransformOperationExecutor };\n//# sourceMappingURL=TransformOperationExecutor.js.map","/**\n * These are the default options used by any transformation operation.\n */\nexport var defaultOptions = {\n enableCircularCheck: false,\n enableImplicitConversion: false,\n excludeExtraneousValues: false,\n excludePrefixes: undefined,\n exposeDefaultValues: false,\n exposeUnsetFields: true,\n groups: undefined,\n ignoreDecorators: false,\n strategy: undefined,\n targetMaps: undefined,\n version: undefined,\n};\n//# sourceMappingURL=default-options.constant.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { TransformOperationExecutor } from './TransformOperationExecutor';\nimport { TransformationType } from './enums';\nimport { defaultOptions } from './constants/default-options.constant';\nvar ClassTransformer = /** @class */ (function () {\n function ClassTransformer() {\n }\n ClassTransformer.prototype.instanceToPlain = function (object, options) {\n var executor = new TransformOperationExecutor(TransformationType.CLASS_TO_PLAIN, __assign(__assign({}, defaultOptions), options));\n return executor.transform(undefined, object, undefined, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.classToPlainFromExist = function (object, plainObject, options) {\n var executor = new TransformOperationExecutor(TransformationType.CLASS_TO_PLAIN, __assign(__assign({}, defaultOptions), options));\n return executor.transform(plainObject, object, undefined, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.plainToInstance = function (cls, plain, options) {\n var executor = new TransformOperationExecutor(TransformationType.PLAIN_TO_CLASS, __assign(__assign({}, defaultOptions), options));\n return executor.transform(undefined, plain, cls, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.plainToClassFromExist = function (clsObject, plain, options) {\n var executor = new TransformOperationExecutor(TransformationType.PLAIN_TO_CLASS, __assign(__assign({}, defaultOptions), options));\n return executor.transform(clsObject, plain, undefined, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.instanceToInstance = function (object, options) {\n var executor = new TransformOperationExecutor(TransformationType.CLASS_TO_CLASS, __assign(__assign({}, defaultOptions), options));\n return executor.transform(undefined, object, undefined, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.classToClassFromExist = function (object, fromObject, options) {\n var executor = new TransformOperationExecutor(TransformationType.CLASS_TO_CLASS, __assign(__assign({}, defaultOptions), options));\n return executor.transform(fromObject, object, undefined, undefined, undefined, undefined);\n };\n ClassTransformer.prototype.serialize = function (object, options) {\n return JSON.stringify(this.instanceToPlain(object, options));\n };\n /**\n * Deserializes given JSON string to a object of the given class.\n */\n ClassTransformer.prototype.deserialize = function (cls, json, options) {\n var jsonObject = JSON.parse(json);\n return this.plainToInstance(cls, jsonObject, options);\n };\n /**\n * Deserializes given JSON string to an array of objects of the given class.\n */\n ClassTransformer.prototype.deserializeArray = function (cls, json, options) {\n var jsonObject = JSON.parse(json);\n return this.plainToInstance(cls, jsonObject, options);\n };\n return ClassTransformer;\n}());\nexport { ClassTransformer };\n//# sourceMappingURL=ClassTransformer.js.map","import { defaultMetadataStorage } from '../storage';\n/**\n * Marks the given class or property as excluded. By default the property is excluded in both\n * constructorToPlain and plainToConstructor transformations. It can be limited to only one direction\n * via using the `toPlainOnly` or `toClassOnly` option.\n *\n * Can be applied to class definitions and properties.\n */\nexport function Exclude(options) {\n if (options === void 0) { options = {}; }\n /**\n * NOTE: The `propertyName` property must be marked as optional because\n * this decorator used both as a class and a property decorator and the\n * Typescript compiler will freak out if we make it mandatory as a class\n * decorator only receives one parameter.\n */\n return function (object, propertyName) {\n defaultMetadataStorage.addExcludeMetadata({\n target: object instanceof Function ? object : object.constructor,\n propertyName: propertyName,\n options: options,\n });\n };\n}\n//# sourceMappingURL=exclude.decorator.js.map","import { defaultMetadataStorage } from '../storage';\n/**\n * Marks the given class or property as included. By default the property is included in both\n * constructorToPlain and plainToConstructor transformations. It can be limited to only one direction\n * via using the `toPlainOnly` or `toClassOnly` option.\n *\n * Can be applied to class definitions and properties.\n */\nexport function Expose(options) {\n if (options === void 0) { options = {}; }\n /**\n * NOTE: The `propertyName` property must be marked as optional because\n * this decorator used both as a class and a property decorator and the\n * Typescript compiler will freak out if we make it mandatory as a class\n * decorator only receives one parameter.\n */\n return function (object, propertyName) {\n defaultMetadataStorage.addExposeMetadata({\n target: object instanceof Function ? object : object.constructor,\n propertyName: propertyName,\n options: options,\n });\n };\n}\n//# sourceMappingURL=expose.decorator.js.map","import { ClassTransformer } from '../ClassTransformer';\n/**\n * Return the class instance only with the exposed properties.\n *\n * Can be applied to functions and getters/setters only.\n */\nexport function TransformInstanceToInstance(params) {\n return function (target, propertyKey, descriptor) {\n var classTransformer = new ClassTransformer();\n var originalMethod = descriptor.value;\n descriptor.value = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = originalMethod.apply(this, args);\n var isPromise = !!result && (typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function';\n return isPromise\n ? result.then(function (data) { return classTransformer.instanceToInstance(data, params); })\n : classTransformer.instanceToInstance(result, params);\n };\n };\n}\n//# sourceMappingURL=transform-instance-to-instance.decorator.js.map","import { ClassTransformer } from '../ClassTransformer';\n/**\n * Transform the object from class to plain object and return only with the exposed properties.\n *\n * Can be applied to functions and getters/setters only.\n */\nexport function TransformInstanceToPlain(params) {\n return function (target, propertyKey, descriptor) {\n var classTransformer = new ClassTransformer();\n var originalMethod = descriptor.value;\n descriptor.value = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = originalMethod.apply(this, args);\n var isPromise = !!result && (typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function';\n return isPromise\n ? result.then(function (data) { return classTransformer.instanceToPlain(data, params); })\n : classTransformer.instanceToPlain(result, params);\n };\n };\n}\n//# sourceMappingURL=transform-instance-to-plain.decorator.js.map","import { ClassTransformer } from '../ClassTransformer';\n/**\n * Return the class instance only with the exposed properties.\n *\n * Can be applied to functions and getters/setters only.\n */\nexport function TransformPlainToInstance(classType, params) {\n return function (target, propertyKey, descriptor) {\n var classTransformer = new ClassTransformer();\n var originalMethod = descriptor.value;\n descriptor.value = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = originalMethod.apply(this, args);\n var isPromise = !!result && (typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function';\n return isPromise\n ? result.then(function (data) { return classTransformer.plainToInstance(classType, data, params); })\n : classTransformer.plainToInstance(classType, result, params);\n };\n };\n}\n//# sourceMappingURL=transform-plain-to-instance.decorator.js.map","import { defaultMetadataStorage } from '../storage';\n/**\n * Defines a custom logic for value transformation.\n *\n * Can be applied to properties only.\n */\nexport function Transform(transformFn, options) {\n if (options === void 0) { options = {}; }\n return function (target, propertyName) {\n defaultMetadataStorage.addTransformMetadata({\n target: target.constructor,\n propertyName: propertyName,\n transformFn: transformFn,\n options: options,\n });\n };\n}\n//# sourceMappingURL=transform.decorator.js.map","import { defaultMetadataStorage } from '../storage';\n/**\n * Specifies a type of the property.\n * The given TypeFunction can return a constructor. A discriminator can be given in the options.\n *\n * Can be applied to properties only.\n */\nexport function Type(typeFunction, options) {\n if (options === void 0) { options = {}; }\n return function (target, propertyName) {\n var reflectedType = Reflect.getMetadata('design:type', target, propertyName);\n defaultMetadataStorage.addTypeMetadata({\n target: target.constructor,\n propertyName: propertyName,\n reflectedType: reflectedType,\n typeFunction: typeFunction,\n options: options,\n });\n };\n}\n//# sourceMappingURL=type.decorator.js.map","import { ClassTransformer } from './ClassTransformer';\nexport { ClassTransformer } from './ClassTransformer';\nexport * from './decorators';\nexport * from './interfaces';\nexport * from './enums';\nvar classTransformer = new ClassTransformer();\nexport function classToPlain(object, options) {\n return classTransformer.instanceToPlain(object, options);\n}\nexport function instanceToPlain(object, options) {\n return classTransformer.instanceToPlain(object, options);\n}\nexport function classToPlainFromExist(object, plainObject, options) {\n return classTransformer.classToPlainFromExist(object, plainObject, options);\n}\nexport function plainToClass(cls, plain, options) {\n return classTransformer.plainToInstance(cls, plain, options);\n}\nexport function plainToInstance(cls, plain, options) {\n return classTransformer.plainToInstance(cls, plain, options);\n}\nexport function plainToClassFromExist(clsObject, plain, options) {\n return classTransformer.plainToClassFromExist(clsObject, plain, options);\n}\nexport function instanceToInstance(object, options) {\n return classTransformer.instanceToInstance(object, options);\n}\nexport function classToClassFromExist(object, fromObject, options) {\n return classTransformer.classToClassFromExist(object, fromObject, options);\n}\nexport function serialize(object, options) {\n return classTransformer.serialize(object, options);\n}\n/**\n * Deserializes given JSON string to a object of the given class.\n *\n * @deprecated This function is being removed. Please use the following instead:\n * ```\n * instanceToClass(cls, JSON.parse(json), options)\n * ```\n */\nexport function deserialize(cls, json, options) {\n return classTransformer.deserialize(cls, json, options);\n}\n/**\n * Deserializes given JSON string to an array of objects of the given class.\n *\n * @deprecated This function is being removed. Please use the following instead:\n * ```\n * JSON.parse(json).map(value => instanceToClass(cls, value, options))\n * ```\n *\n */\nexport function deserializeArray(cls, json, options) {\n return classTransformer.deserializeArray(cls, json, options);\n}\n//# sourceMappingURL=index.js.map","import { NodeSearchService } from '@/services/nodeSearchService'\r\nimport { ComfyNodeDef } from '@/types/apiTypes'\r\nimport { defineStore } from 'pinia'\r\nimport { Type, Transform, plainToClass, Expose } from 'class-transformer'\r\nimport { ComfyWidgetConstructor } from '@/scripts/widgets'\r\nimport { TreeNode } from 'primevue/treenode'\r\nimport { buildTree } from '@/utils/treeUtil'\r\n\r\nexport class BaseInputSpec {\r\n name: string\r\n type: string\r\n tooltip?: string\r\n default?: T\r\n\r\n @Type(() => Boolean)\r\n forceInput?: boolean\r\n\r\n static isInputSpec(obj: any): boolean {\r\n return (\r\n Array.isArray(obj) &&\r\n obj.length >= 1 &&\r\n (typeof obj[0] === 'string' || Array.isArray(obj[0]))\r\n )\r\n }\r\n}\r\n\r\nexport class NumericInputSpec extends BaseInputSpec {\r\n @Type(() => Number)\r\n min?: number\r\n\r\n @Type(() => Number)\r\n max?: number\r\n\r\n @Type(() => Number)\r\n step?: number\r\n}\r\n\r\nexport class IntInputSpec extends NumericInputSpec {\r\n type: 'INT' = 'INT'\r\n}\r\n\r\nexport class FloatInputSpec extends NumericInputSpec {\r\n type: 'FLOAT' = 'FLOAT'\r\n\r\n @Type(() => Number)\r\n round?: number\r\n}\r\n\r\nexport class BooleanInputSpec extends BaseInputSpec {\r\n type: 'BOOLEAN' = 'BOOLEAN'\r\n\r\n labelOn?: string\r\n labelOff?: string\r\n}\r\n\r\nexport class StringInputSpec extends BaseInputSpec {\r\n type: 'STRING' = 'STRING'\r\n\r\n @Type(() => Boolean)\r\n multiline?: boolean\r\n\r\n @Type(() => Boolean)\r\n dynamicPrompts?: boolean\r\n}\r\n\r\nexport class ComboInputSpec extends BaseInputSpec {\r\n type: string = 'COMBO'\r\n\r\n @Transform(({ value }) => value[0])\r\n comboOptions: any[]\r\n\r\n @Type(() => Boolean)\r\n controlAfterGenerate?: boolean\r\n\r\n @Type(() => Boolean)\r\n imageUpload?: boolean\r\n}\r\n\r\nexport class CustomInputSpec extends BaseInputSpec {}\r\n\r\nexport class ComfyInputsSpec {\r\n @Transform(({ value }) => ComfyInputsSpec.transformInputSpecRecord(value))\r\n required: Record = {}\r\n\r\n @Transform(({ value }) => ComfyInputsSpec.transformInputSpecRecord(value))\r\n optional: Record = {}\r\n\r\n hidden?: Record\r\n\r\n private static transformInputSpecRecord(\r\n record: Record\r\n ): Record {\r\n if (!record) return record\r\n const result: Record = {}\r\n for (const [key, value] of Object.entries(record)) {\r\n result[key] = ComfyInputsSpec.transformSingleInputSpec(key, value)\r\n }\r\n return result\r\n }\r\n\r\n private static transformSingleInputSpec(\r\n name: string,\r\n value: any\r\n ): BaseInputSpec {\r\n if (!BaseInputSpec.isInputSpec(value)) return value\r\n\r\n const [typeRaw, _spec] = value\r\n const spec = _spec ?? {}\r\n const type = Array.isArray(typeRaw) ? 'COMBO' : value[0]\r\n\r\n switch (type) {\r\n case 'INT':\r\n return plainToClass(IntInputSpec, { name, type, ...spec })\r\n case 'FLOAT':\r\n return plainToClass(FloatInputSpec, { name, type, ...spec })\r\n case 'BOOLEAN':\r\n return plainToClass(BooleanInputSpec, { name, type, ...spec })\r\n case 'STRING':\r\n return plainToClass(StringInputSpec, { name, type, ...spec })\r\n case 'COMBO':\r\n return plainToClass(ComboInputSpec, {\r\n name,\r\n type,\r\n ...spec,\r\n comboOptions: typeRaw,\r\n default: spec.default ?? typeRaw[0]\r\n })\r\n default:\r\n return plainToClass(CustomInputSpec, { name, type, ...spec })\r\n }\r\n }\r\n\r\n get all() {\r\n return [...Object.values(this.required), ...Object.values(this.optional)]\r\n }\r\n\r\n getInput(name: string): BaseInputSpec | undefined {\r\n return this.required[name] ?? this.optional[name]\r\n }\r\n}\r\n\r\nexport class ComfyOutputSpec {\r\n constructor(\r\n public index: number,\r\n // Name is not unique for output params\r\n public name: string,\r\n public type: string,\r\n public is_list: boolean,\r\n public comboOptions?: any[],\r\n public tooltip?: string\r\n ) {}\r\n}\r\n\r\nexport class ComfyOutputsSpec {\r\n constructor(public outputs: ComfyOutputSpec[]) {}\r\n\r\n get all() {\r\n return this.outputs\r\n }\r\n}\r\n\r\nexport class ComfyNodeDefImpl {\r\n name: string\r\n display_name: string\r\n category: string\r\n python_module: string\r\n description: string\r\n\r\n @Transform(({ value, obj }) => value ?? obj.category === '', {\r\n toClassOnly: true\r\n })\r\n @Type(() => Boolean)\r\n @Expose()\r\n deprecated: boolean\r\n\r\n @Transform(\r\n ({ value, obj }) => value ?? obj.category.startsWith('_for_testing'),\r\n {\r\n toClassOnly: true\r\n }\r\n )\r\n @Type(() => Boolean)\r\n @Expose()\r\n experimental: boolean\r\n\r\n @Type(() => ComfyInputsSpec)\r\n input: ComfyInputsSpec\r\n\r\n @Transform(({ obj }) => ComfyNodeDefImpl.transformOutputSpec(obj))\r\n output: ComfyOutputsSpec\r\n\r\n private static transformOutputSpec(obj: any): ComfyOutputsSpec {\r\n const { output, output_is_list, output_name, output_tooltips } = obj\r\n const result = output.map((type: string | any[], index: number) => {\r\n const typeString = Array.isArray(type) ? 'COMBO' : type\r\n\r\n return new ComfyOutputSpec(\r\n index,\r\n output_name[index],\r\n typeString,\r\n output_is_list[index],\r\n Array.isArray(type) ? type : undefined,\r\n output_tooltips?.[index]\r\n )\r\n })\r\n return new ComfyOutputsSpec(result)\r\n }\r\n}\r\n\r\nexport const SYSTEM_NODE_DEFS: Record = {\r\n PrimitiveNode: {\r\n name: 'PrimitiveNode',\r\n display_name: 'Primitive',\r\n category: 'utils',\r\n input: { required: {}, optional: {} },\r\n output: ['*'],\r\n output_name: ['connect to widget input'],\r\n output_is_list: [false],\r\n python_module: 'nodes',\r\n description: 'Primitive values like numbers, strings, and booleans.'\r\n },\r\n Reroute: {\r\n name: 'Reroute',\r\n display_name: 'Reroute',\r\n category: 'utils',\r\n input: { required: { '': ['*'] }, optional: {} },\r\n output: ['*'],\r\n output_name: [''],\r\n output_is_list: [false],\r\n python_module: 'nodes',\r\n description: 'Reroute the connection to another node.'\r\n },\r\n Note: {\r\n name: 'Note',\r\n display_name: 'Note',\r\n category: 'utils',\r\n input: { required: {}, optional: {} },\r\n output: [],\r\n output_name: [],\r\n output_is_list: [],\r\n python_module: 'nodes',\r\n description: 'Node that add notes to your project'\r\n }\r\n}\r\n\r\ninterface State {\r\n nodeDefsByName: Record\r\n widgets: Record\r\n showDeprecated: boolean\r\n showExperimental: boolean\r\n}\r\n\r\nexport const useNodeDefStore = defineStore('nodeDef', {\r\n state: (): State => ({\r\n nodeDefsByName: {},\r\n widgets: {},\r\n showDeprecated: false,\r\n showExperimental: false\r\n }),\r\n getters: {\r\n nodeDefs(state) {\r\n return Object.values(state.nodeDefsByName)\r\n },\r\n // Node defs that are not deprecated\r\n visibleNodeDefs(state) {\r\n return this.nodeDefs.filter(\r\n (nodeDef: ComfyNodeDefImpl) =>\r\n (state.showDeprecated || !nodeDef.deprecated) &&\r\n (state.showExperimental || !nodeDef.experimental)\r\n )\r\n },\r\n nodeSearchService() {\r\n return new NodeSearchService(this.visibleNodeDefs)\r\n },\r\n nodeTree(): TreeNode {\r\n return buildTree(this.visibleNodeDefs, (nodeDef: ComfyNodeDefImpl) => [\r\n ...nodeDef.category.split('/'),\r\n nodeDef.display_name\r\n ])\r\n }\r\n },\r\n actions: {\r\n updateNodeDefs(nodeDefs: ComfyNodeDef[]) {\r\n const newNodeDefsByName: { [key: string]: ComfyNodeDefImpl } = {}\r\n for (const nodeDef of nodeDefs) {\r\n newNodeDefsByName[nodeDef.name] = plainToClass(\r\n ComfyNodeDefImpl,\r\n nodeDef\r\n )\r\n }\r\n this.nodeDefsByName = newNodeDefsByName\r\n },\r\n updateWidgets(widgets: Record) {\r\n this.widgets = widgets\r\n },\r\n getWidgetType(type: string, inputName: string) {\r\n if (type === 'COMBO') {\r\n return 'COMBO'\r\n } else if (`${type}:${inputName}` in this.widgets) {\r\n return `${type}:${inputName}`\r\n } else if (type in this.widgets) {\r\n return type\r\n } else {\r\n return null\r\n }\r\n },\r\n inputIsWidget(spec: BaseInputSpec) {\r\n return this.getWidgetType(spec.type, spec.name) !== null\r\n }\r\n }\r\n})\r\n","import { SidebarTabExtension, ToastManager } from '@/types/extensionTypes'\r\nimport { defineStore } from 'pinia'\r\nimport { useToastStore } from './toastStore'\r\n\r\ninterface WorkspaceState {\r\n spinner: boolean\r\n activeSidebarTab: string | null\r\n sidebarTabs: SidebarTabExtension[]\r\n}\r\n\r\nexport const useWorkspaceStore = defineStore('workspace', {\r\n state: (): WorkspaceState => ({\r\n spinner: false,\r\n activeSidebarTab: null,\r\n sidebarTabs: []\r\n }),\r\n getters: {\r\n toast(): ToastManager {\r\n return useToastStore()\r\n }\r\n },\r\n actions: {\r\n updateActiveSidebarTab(tabId: string) {\r\n this.activeSidebarTab = tabId\r\n },\r\n registerSidebarTab(tab: SidebarTabExtension) {\r\n this.sidebarTabs = [...this.sidebarTabs, tab]\r\n },\r\n unregisterSidebarTab(id: string) {\r\n const index = this.sidebarTabs.findIndex((tab) => tab.id === id)\r\n if (index !== -1) {\r\n const tab = this.sidebarTabs[index]\r\n if (tab.type === 'custom' && tab.destroy) {\r\n tab.destroy()\r\n }\r\n const newSidebarTabs = [...this.sidebarTabs]\r\n newSidebarTabs.splice(index, 1)\r\n this.sidebarTabs = newSidebarTabs\r\n }\r\n },\r\n getSidebarTabs() {\r\n return [...this.sidebarTabs]\r\n }\r\n }\r\n})\r\n","import { ComfyLogging } from './logging'\r\nimport { ComfyWidgetConstructor, ComfyWidgets, initWidgets } from './widgets'\r\nimport { ComfyUI, $el } from './ui'\r\nimport { api } from './api'\r\nimport { defaultGraph } from './defaultGraph'\r\nimport {\r\n getPngMetadata,\r\n getWebpMetadata,\r\n getFlacMetadata,\r\n importA1111,\r\n getLatentMetadata\r\n} from './pnginfo'\r\nimport { addDomClippingSetting } from './domWidget'\r\nimport { createImageHost, calculateImageGrid } from './ui/imagePreview'\r\nimport { DraggableList } from './ui/draggableList'\r\nimport { applyTextReplacements, addStylesheet } from './utils'\r\nimport type { ComfyExtension } from '@/types/comfy'\r\nimport {\r\n type ComfyWorkflowJSON,\r\n validateComfyWorkflow\r\n} from '../types/comfyWorkflow'\r\nimport { ComfyNodeDef, StatusWsMessageStatus } from '@/types/apiTypes'\r\nimport { lightenColor } from '@/utils/colorUtil'\r\nimport { ComfyAppMenu } from './ui/menu/index'\r\nimport { getStorageValue } from './utils'\r\nimport { ComfyWorkflowManager, ComfyWorkflow } from './workflows'\r\nimport {\r\n LGraphCanvas,\r\n LGraph,\r\n LGraphNode,\r\n LiteGraph\r\n} from '@comfyorg/litegraph'\r\nimport { StorageLocation } from '@/types/settingTypes'\r\n\r\n// CSS imports. style.css must be imported later as it overwrites some litegraph styles.\r\nimport '@comfyorg/litegraph/style.css'\r\nimport '../assets/css/style.css'\r\nimport { ExtensionManager } from '@/types/extensionTypes'\r\nimport {\r\n ComfyNodeDefImpl,\r\n SYSTEM_NODE_DEFS,\r\n useNodeDefStore\r\n} from '@/stores/nodeDefStore'\r\nimport { Vector2 } from '@comfyorg/litegraph'\r\nimport _ from 'lodash'\r\nimport { showLoadWorkflowWarning } from '@/services/dialogService'\r\nimport { useSettingStore } from '@/stores/settingStore'\r\nimport { useToastStore } from '@/stores/toastStore'\r\nimport type { ToastMessageOptions } from 'primevue/toast'\r\nimport { useWorkspaceStore } from '@/stores/workspaceStateStore'\r\n\r\nexport const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview'\r\n\r\nfunction sanitizeNodeName(string) {\r\n let entityMap = {\r\n '&': '',\r\n '<': '',\r\n '>': '',\r\n '\"': '',\r\n \"'\": '',\r\n '`': '',\r\n '=': ''\r\n }\r\n return String(string).replace(/[&<>\"'`=]/g, function fromEntityMap(s) {\r\n return entityMap[s]\r\n })\r\n}\r\n\r\n/**\r\n * @typedef {import(\"types/comfy\").ComfyExtension} ComfyExtension\r\n */\r\n\r\nexport class ComfyApp {\r\n /**\r\n * List of entries to queue\r\n * @type {{number: number, batchCount: number}[]}\r\n */\r\n #queueItems = []\r\n /**\r\n * If the queue is currently being processed\r\n * @type {boolean}\r\n */\r\n #processingQueue = false\r\n\r\n /**\r\n * Content Clipboard\r\n * @type {serialized node object}\r\n */\r\n static clipspace = null\r\n static clipspace_invalidate_handler = null\r\n static open_maskeditor = null\r\n static clipspace_return_node = null\r\n\r\n // Force vite to import utils.ts as part of index.\r\n // Force import of DraggableList.\r\n static utils = {\r\n applyTextReplacements,\r\n addStylesheet,\r\n DraggableList\r\n }\r\n\r\n vueAppReady: boolean\r\n ui: ComfyUI\r\n logging: ComfyLogging\r\n extensions: ComfyExtension[]\r\n extensionManager: ExtensionManager\r\n _nodeOutputs: Record\r\n nodePreviewImages: Record\r\n shiftDown: boolean\r\n graph: LGraph\r\n enableWorkflowViewRestore: any\r\n canvas: LGraphCanvas\r\n dragOverNode: LGraphNode | null\r\n canvasEl: HTMLCanvasElement\r\n // x, y, scale\r\n zoom_drag_start: [number, number, number] | null\r\n lastNodeErrors: any[] | null\r\n runningNodeId: number | null\r\n lastExecutionError: { node_id: number } | null\r\n progress: { value: number; max: number } | null\r\n configuringGraph: boolean\r\n isNewUserSession: boolean\r\n storageLocation: StorageLocation\r\n multiUserServer: boolean\r\n ctx: CanvasRenderingContext2D\r\n widgets: Record\r\n workflowManager: ComfyWorkflowManager\r\n bodyTop: HTMLElement\r\n bodyLeft: HTMLElement\r\n bodyRight: HTMLElement\r\n bodyBottom: HTMLElement\r\n canvasContainer: HTMLElement\r\n menu: ComfyAppMenu\r\n\r\n constructor() {\r\n this.vueAppReady = false\r\n this.ui = new ComfyUI(this)\r\n this.logging = new ComfyLogging(this)\r\n this.workflowManager = new ComfyWorkflowManager(this)\r\n this.bodyTop = $el('div.comfyui-body-top', { parent: document.body })\r\n this.bodyLeft = $el('div.comfyui-body-left', { parent: document.body })\r\n this.bodyRight = $el('div.comfyui-body-right', { parent: document.body })\r\n this.bodyBottom = $el('div.comfyui-body-bottom', { parent: document.body })\r\n this.canvasContainer = $el('div.graph-canvas-container', {\r\n parent: document.body\r\n })\r\n this.menu = new ComfyAppMenu(this)\r\n\r\n /**\r\n * List of extensions that are registered with the app\r\n * @type {ComfyExtension[]}\r\n */\r\n this.extensions = []\r\n\r\n /**\r\n * Stores the execution output data for each node\r\n * @type {Record}\r\n */\r\n this.nodeOutputs = {}\r\n\r\n /**\r\n * Stores the preview image data for each node\r\n * @type {Record}\r\n */\r\n this.nodePreviewImages = {}\r\n\r\n /**\r\n * If the shift key on the keyboard is pressed\r\n * @type {boolean}\r\n */\r\n this.shiftDown = false\r\n }\r\n\r\n get nodeOutputs() {\r\n return this._nodeOutputs\r\n }\r\n\r\n set nodeOutputs(value) {\r\n this._nodeOutputs = value\r\n this.#invokeExtensions('onNodeOutputsUpdated', value)\r\n }\r\n\r\n getPreviewFormatParam() {\r\n let preview_format = this.ui.settings.getSettingValue('Comfy.PreviewFormat')\r\n if (preview_format) return `&preview=${preview_format}`\r\n else return ''\r\n }\r\n\r\n getRandParam() {\r\n return '&rand=' + Math.random()\r\n }\r\n\r\n static isImageNode(node) {\r\n return (\r\n node.imgs ||\r\n (node &&\r\n node.widgets &&\r\n node.widgets.findIndex((obj) => obj.name === 'image') >= 0)\r\n )\r\n }\r\n\r\n static onClipspaceEditorSave() {\r\n if (ComfyApp.clipspace_return_node) {\r\n ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)\r\n }\r\n }\r\n\r\n static onClipspaceEditorClosed() {\r\n ComfyApp.clipspace_return_node = null\r\n }\r\n\r\n static copyToClipspace(node) {\r\n var widgets = null\r\n if (node.widgets) {\r\n widgets = node.widgets.map(({ type, name, value }) => ({\r\n type,\r\n name,\r\n value\r\n }))\r\n }\r\n\r\n var imgs = undefined\r\n var orig_imgs = undefined\r\n if (node.imgs != undefined) {\r\n imgs = []\r\n orig_imgs = []\r\n\r\n for (let i = 0; i < node.imgs.length; i++) {\r\n imgs[i] = new Image()\r\n imgs[i].src = node.imgs[i].src\r\n orig_imgs[i] = imgs[i]\r\n }\r\n }\r\n\r\n var selectedIndex = 0\r\n if (node.imageIndex) {\r\n selectedIndex = node.imageIndex\r\n }\r\n\r\n ComfyApp.clipspace = {\r\n widgets: widgets,\r\n imgs: imgs,\r\n original_imgs: orig_imgs,\r\n images: node.images,\r\n selectedIndex: selectedIndex,\r\n img_paste_mode: 'selected' // reset to default im_paste_mode state on copy action\r\n }\r\n\r\n ComfyApp.clipspace_return_node = null\r\n\r\n if (ComfyApp.clipspace_invalidate_handler) {\r\n ComfyApp.clipspace_invalidate_handler()\r\n }\r\n }\r\n\r\n static pasteFromClipspace(node) {\r\n if (ComfyApp.clipspace) {\r\n // image paste\r\n if (ComfyApp.clipspace.imgs && node.imgs) {\r\n if (node.images && ComfyApp.clipspace.images) {\r\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\r\n node.images = [\r\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\r\n ]\r\n } else {\r\n node.images = ComfyApp.clipspace.images\r\n }\r\n\r\n if (app.nodeOutputs[node.id + ''])\r\n app.nodeOutputs[node.id + ''].images = node.images\r\n }\r\n\r\n if (ComfyApp.clipspace.imgs) {\r\n // deep-copy to cut link with clipspace\r\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\r\n const img = new Image()\r\n img.src =\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\r\n node.imgs = [img]\r\n node.imageIndex = 0\r\n } else {\r\n const imgs = []\r\n for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) {\r\n imgs[i] = new Image()\r\n imgs[i].src = ComfyApp.clipspace.imgs[i].src\r\n node.imgs = imgs\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (node.widgets) {\r\n if (ComfyApp.clipspace.images) {\r\n const clip_image =\r\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\r\n const index = node.widgets.findIndex((obj) => obj.name === 'image')\r\n if (index >= 0) {\r\n if (\r\n node.widgets[index].type != 'image' &&\r\n typeof node.widgets[index].value == 'string' &&\r\n clip_image.filename\r\n ) {\r\n node.widgets[index].value =\r\n (clip_image.subfolder ? clip_image.subfolder + '/' : '') +\r\n clip_image.filename +\r\n (clip_image.type ? ` [${clip_image.type}]` : '')\r\n } else {\r\n node.widgets[index].value = clip_image\r\n }\r\n }\r\n }\r\n if (ComfyApp.clipspace.widgets) {\r\n ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => {\r\n const prop = Object.values(node.widgets).find(\r\n // @ts-expect-errorg\r\n (obj) => obj.type === type && obj.name === name\r\n )\r\n // @ts-expect-error\r\n if (prop && prop.type != 'button') {\r\n if (\r\n // @ts-expect-error\r\n prop.type != 'image' &&\r\n // @ts-expect-error\r\n typeof prop.value == 'string' &&\r\n value.filename\r\n ) {\r\n // @ts-expect-error\r\n prop.value =\r\n (value.subfolder ? value.subfolder + '/' : '') +\r\n value.filename +\r\n (value.type ? ` [${value.type}]` : '')\r\n } else {\r\n // @ts-expect-error\r\n prop.value = value\r\n // @ts-expect-error\r\n prop.callback(value)\r\n }\r\n }\r\n })\r\n }\r\n }\r\n\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n }\r\n\r\n /**\r\n * Invoke an extension callback\r\n * @param {keyof ComfyExtension} method The extension callback to execute\r\n * @param {any[]} args Any arguments to pass to the callback\r\n * @returns\r\n */\r\n #invokeExtensions(method, ...args) {\r\n let results = []\r\n for (const ext of this.extensions) {\r\n if (method in ext) {\r\n try {\r\n results.push(ext[method](...args, this))\r\n } catch (error) {\r\n console.error(\r\n `Error calling extension '${ext.name}' method '${method}'`,\r\n { error },\r\n { extension: ext },\r\n { args }\r\n )\r\n }\r\n }\r\n }\r\n return results\r\n }\r\n\r\n /**\r\n * Invoke an async extension callback\r\n * Each callback will be invoked concurrently\r\n * @param {string} method The extension callback to execute\r\n * @param {...any} args Any arguments to pass to the callback\r\n * @returns\r\n */\r\n async #invokeExtensionsAsync(method, ...args) {\r\n return await Promise.all(\r\n this.extensions.map(async (ext) => {\r\n if (method in ext) {\r\n try {\r\n return await ext[method](...args, this)\r\n } catch (error) {\r\n console.error(\r\n `Error calling extension '${ext.name}' method '${method}'`,\r\n { error },\r\n { extension: ext },\r\n { args }\r\n )\r\n }\r\n }\r\n })\r\n )\r\n }\r\n\r\n #addRestoreWorkflowView() {\r\n const serialize = LGraph.prototype.serialize\r\n const self = this\r\n LGraph.prototype.serialize = function () {\r\n const workflow = serialize.apply(this, arguments)\r\n\r\n // Store the drag & scale info in the serialized workflow if the setting is enabled\r\n if (self.enableWorkflowViewRestore.value) {\r\n if (!workflow.extra) {\r\n workflow.extra = {}\r\n }\r\n workflow.extra.ds = {\r\n scale: self.canvas.ds.scale,\r\n offset: self.canvas.ds.offset\r\n }\r\n } else if (workflow.extra?.ds) {\r\n // Clear any old view data\r\n delete workflow.extra.ds\r\n }\r\n\r\n return workflow\r\n }\r\n this.enableWorkflowViewRestore = this.ui.settings.addSetting({\r\n id: 'Comfy.EnableWorkflowViewRestore',\r\n category: ['Comfy', 'Workflow', 'EnableWorkflowViewRestore'],\r\n name: 'Save and restore canvas position and zoom level in workflows',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n }\r\n\r\n /**\r\n * Adds special context menu handling for nodes\r\n * e.g. this adds Open Image functionality for nodes that show images\r\n * @param {*} node The node to add the menu handler\r\n */\r\n #addNodeContextMenuHandler(node) {\r\n function getCopyImageOption(img) {\r\n if (typeof window.ClipboardItem === 'undefined') return []\r\n return [\r\n {\r\n content: 'Copy Image',\r\n callback: async () => {\r\n const url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n\r\n const writeImage = async (blob) => {\r\n await navigator.clipboard.write([\r\n new ClipboardItem({\r\n [blob.type]: blob\r\n })\r\n ])\r\n }\r\n\r\n try {\r\n const data = await fetch(url)\r\n const blob = await data.blob()\r\n try {\r\n await writeImage(blob)\r\n } catch (error) {\r\n // Chrome seems to only support PNG on write, convert and try again\r\n if (blob.type !== 'image/png') {\r\n const canvas = $el('canvas', {\r\n width: img.naturalWidth,\r\n height: img.naturalHeight\r\n }) as HTMLCanvasElement\r\n const ctx = canvas.getContext('2d')\r\n let image\r\n if (typeof window.createImageBitmap === 'undefined') {\r\n image = new Image()\r\n const p = new Promise((resolve, reject) => {\r\n image.onload = resolve\r\n image.onerror = reject\r\n }).finally(() => {\r\n URL.revokeObjectURL(image.src)\r\n })\r\n image.src = URL.createObjectURL(blob)\r\n await p\r\n } else {\r\n image = await createImageBitmap(blob)\r\n }\r\n try {\r\n ctx.drawImage(image, 0, 0)\r\n canvas.toBlob(writeImage, 'image/png')\r\n } finally {\r\n if (typeof image.close === 'function') {\r\n image.close()\r\n }\r\n }\r\n\r\n return\r\n }\r\n throw error\r\n }\r\n } catch (error) {\r\n alert('Error copying image: ' + (error.message ?? error))\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n\r\n node.prototype.getExtraMenuOptions = function (_, options) {\r\n if (this.imgs) {\r\n // If this node has images then we add an open in new tab item\r\n let img\r\n if (this.imageIndex != null) {\r\n // An image is selected so select that\r\n img = this.imgs[this.imageIndex]\r\n } else if (this.overIndex != null) {\r\n // No image is selected but one is hovered\r\n img = this.imgs[this.overIndex]\r\n }\r\n if (img) {\r\n options.unshift(\r\n {\r\n content: 'Open Image',\r\n callback: () => {\r\n let url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n window.open(url, '_blank')\r\n }\r\n },\r\n ...getCopyImageOption(img),\r\n {\r\n content: 'Save Image',\r\n callback: () => {\r\n const a = document.createElement('a')\r\n let url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n a.href = url.toString()\r\n a.setAttribute(\r\n 'download',\r\n new URLSearchParams(url.search).get('filename')\r\n )\r\n document.body.append(a)\r\n a.click()\r\n requestAnimationFrame(() => a.remove())\r\n }\r\n }\r\n )\r\n }\r\n }\r\n\r\n options.push({\r\n content: 'Bypass',\r\n callback: (obj) => {\r\n if (this.mode === 4) this.mode = 0\r\n else this.mode = 4\r\n this.graph.change()\r\n }\r\n })\r\n\r\n // prevent conflict of clipspace content\r\n if (!ComfyApp.clipspace_return_node) {\r\n options.push({\r\n content: 'Copy (Clipspace)',\r\n callback: (obj) => {\r\n ComfyApp.copyToClipspace(this)\r\n }\r\n })\r\n\r\n if (ComfyApp.clipspace != null) {\r\n options.push({\r\n content: 'Paste (Clipspace)',\r\n callback: () => {\r\n ComfyApp.pasteFromClipspace(this)\r\n }\r\n })\r\n }\r\n\r\n if (ComfyApp.isImageNode(this)) {\r\n options.push({\r\n content: 'Open in MaskEditor',\r\n callback: (obj) => {\r\n ComfyApp.copyToClipspace(this)\r\n ComfyApp.clipspace_return_node = this\r\n ComfyApp.open_maskeditor()\r\n }\r\n })\r\n }\r\n }\r\n }\r\n }\r\n\r\n #addNodeKeyHandler(node) {\r\n const app = this\r\n const origNodeOnKeyDown = node.prototype.onKeyDown\r\n\r\n node.prototype.onKeyDown = function (e) {\r\n if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e) === false) {\r\n return false\r\n }\r\n\r\n if (this.flags.collapsed || !this.imgs || this.imageIndex === null) {\r\n return\r\n }\r\n\r\n let handled = false\r\n\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\r\n if (e.key === 'ArrowLeft') {\r\n this.imageIndex -= 1\r\n } else if (e.key === 'ArrowRight') {\r\n this.imageIndex += 1\r\n }\r\n this.imageIndex %= this.imgs.length\r\n\r\n if (this.imageIndex < 0) {\r\n this.imageIndex = this.imgs.length + this.imageIndex\r\n }\r\n handled = true\r\n } else if (e.key === 'Escape') {\r\n this.imageIndex = null\r\n handled = true\r\n }\r\n\r\n if (handled === true) {\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Adds Custom drawing logic for nodes\r\n * e.g. Draws images and handles thumbnail navigation on nodes that output images\r\n * @param {*} node The node to add the draw handler\r\n */\r\n #addDrawBackgroundHandler(node) {\r\n const app = this\r\n\r\n function getImageTop(node) {\r\n let shiftY\r\n if (node.imageOffset != null) {\r\n shiftY = node.imageOffset\r\n } else {\r\n if (node.widgets?.length) {\r\n const w = node.widgets[node.widgets.length - 1]\r\n shiftY = w.last_y\r\n if (w.computeSize) {\r\n shiftY += w.computeSize()[1] + 4\r\n } else if (w.computedHeight) {\r\n shiftY += w.computedHeight\r\n } else {\r\n shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n } else {\r\n shiftY = node.computeSize()[1]\r\n }\r\n }\r\n return shiftY\r\n }\r\n\r\n node.prototype.setSizeForImage = function (force) {\r\n if (!force && this.animatedImages) return\r\n\r\n if (this.inputHeight || this.freeWidgetSpace > 210) {\r\n this.setSize(this.size)\r\n return\r\n }\r\n const minHeight = getImageTop(this) + 220\r\n if (this.size[1] < minHeight) {\r\n this.setSize([this.size[0], minHeight])\r\n }\r\n }\r\n\r\n function unsafeDrawBackground(ctx) {\r\n if (!this.flags.collapsed) {\r\n let imgURLs = []\r\n let imagesChanged = false\r\n\r\n const output = app.nodeOutputs[this.id + '']\r\n if (output?.images) {\r\n this.animatedImages = output?.animated?.find(Boolean)\r\n if (this.images !== output.images) {\r\n this.images = output.images\r\n imagesChanged = true\r\n imgURLs = imgURLs.concat(\r\n output.images.map((params) => {\r\n return api.apiURL(\r\n '/view?' +\r\n new URLSearchParams(params).toString() +\r\n (this.animatedImages ? '' : app.getPreviewFormatParam()) +\r\n app.getRandParam()\r\n )\r\n })\r\n )\r\n }\r\n }\r\n\r\n const preview = app.nodePreviewImages[this.id + '']\r\n if (this.preview !== preview) {\r\n this.preview = preview\r\n imagesChanged = true\r\n if (preview != null) {\r\n imgURLs.push(preview)\r\n }\r\n }\r\n\r\n if (imagesChanged) {\r\n this.imageIndex = null\r\n if (imgURLs.length > 0) {\r\n Promise.all(\r\n imgURLs.map((src) => {\r\n return new Promise((r) => {\r\n const img = new Image()\r\n img.onload = () => r(img)\r\n img.onerror = () => r(null)\r\n img.src = src\r\n })\r\n })\r\n ).then((imgs) => {\r\n if (\r\n (!output || this.images === output.images) &&\r\n (!preview || this.preview === preview)\r\n ) {\r\n this.imgs = imgs.filter(Boolean)\r\n this.setSizeForImage?.()\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n })\r\n } else {\r\n this.imgs = null\r\n }\r\n }\r\n\r\n const calculateGrid = (w, h, n) => {\r\n let columns, rows, cellsize\r\n\r\n if (w > h) {\r\n cellsize = h\r\n columns = Math.ceil(w / cellsize)\r\n rows = Math.ceil(n / columns)\r\n } else {\r\n cellsize = w\r\n rows = Math.ceil(h / cellsize)\r\n columns = Math.ceil(n / rows)\r\n }\r\n\r\n while (columns * rows < n) {\r\n cellsize++\r\n if (w >= h) {\r\n columns = Math.ceil(w / cellsize)\r\n rows = Math.ceil(n / columns)\r\n } else {\r\n rows = Math.ceil(h / cellsize)\r\n columns = Math.ceil(n / rows)\r\n }\r\n }\r\n\r\n const cell_size = Math.min(w / columns, h / rows)\r\n return { cell_size, columns, rows }\r\n }\r\n\r\n const is_all_same_aspect_ratio = (imgs) => {\r\n // assume: imgs.length >= 2\r\n let ratio = imgs[0].naturalWidth / imgs[0].naturalHeight\r\n\r\n for (let i = 1; i < imgs.length; i++) {\r\n let this_ratio = imgs[i].naturalWidth / imgs[i].naturalHeight\r\n if (ratio != this_ratio) return false\r\n }\r\n\r\n return true\r\n }\r\n\r\n if (this.imgs?.length) {\r\n const widgetIdx = this.widgets?.findIndex(\r\n (w) => w.name === ANIM_PREVIEW_WIDGET\r\n )\r\n\r\n if (this.animatedImages) {\r\n // Instead of using the canvas we'll use a IMG\r\n if (widgetIdx > -1) {\r\n // Replace content\r\n const widget = this.widgets[widgetIdx]\r\n widget.options.host.updateImages(this.imgs)\r\n } else {\r\n const host = createImageHost(this)\r\n this.setSizeForImage(true)\r\n const widget = this.addDOMWidget(\r\n ANIM_PREVIEW_WIDGET,\r\n 'img',\r\n host.el,\r\n {\r\n host,\r\n getHeight: host.getHeight,\r\n onDraw: host.onDraw,\r\n hideOnZoom: false\r\n }\r\n )\r\n widget.serializeValue = () => undefined\r\n widget.options.host.updateImages(this.imgs)\r\n }\r\n return\r\n }\r\n\r\n if (widgetIdx > -1) {\r\n this.widgets[widgetIdx].onRemove?.()\r\n this.widgets.splice(widgetIdx, 1)\r\n }\r\n\r\n const canvas = app.graph.list_of_graphcanvas[0]\r\n const mouse = canvas.graph_mouse\r\n if (!canvas.pointer_is_down && this.pointerDown) {\r\n if (\r\n mouse[0] === this.pointerDown.pos[0] &&\r\n mouse[1] === this.pointerDown.pos[1]\r\n ) {\r\n this.imageIndex = this.pointerDown.index\r\n }\r\n this.pointerDown = null\r\n }\r\n\r\n let imageIndex = this.imageIndex\r\n const numImages = this.imgs.length\r\n if (numImages === 1 && !imageIndex) {\r\n this.imageIndex = imageIndex = 0\r\n }\r\n\r\n const top = getImageTop(this)\r\n var shiftY = top\r\n\r\n let dw = this.size[0]\r\n let dh = this.size[1]\r\n dh -= shiftY\r\n\r\n if (imageIndex == null) {\r\n var cellWidth, cellHeight, shiftX, cell_padding, cols\r\n\r\n const compact_mode = is_all_same_aspect_ratio(this.imgs)\r\n if (!compact_mode) {\r\n // use rectangle cell style and border line\r\n cell_padding = 2\r\n const { cell_size, columns, rows } = calculateGrid(\r\n dw,\r\n dh,\r\n numImages\r\n )\r\n cols = columns\r\n\r\n cellWidth = cell_size\r\n cellHeight = cell_size\r\n shiftX = (dw - cell_size * cols) / 2\r\n shiftY = (dh - cell_size * rows) / 2 + top\r\n } else {\r\n cell_padding = 0\r\n ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(\r\n this.imgs,\r\n dw,\r\n dh\r\n ))\r\n }\r\n\r\n let anyHovered = false\r\n this.imageRects = []\r\n for (let i = 0; i < numImages; i++) {\r\n const img = this.imgs[i]\r\n const row = Math.floor(i / cols)\r\n const col = i % cols\r\n const x = col * cellWidth + shiftX\r\n const y = row * cellHeight + shiftY\r\n if (!anyHovered) {\r\n anyHovered = LiteGraph.isInsideRectangle(\r\n mouse[0],\r\n mouse[1],\r\n x + this.pos[0],\r\n y + this.pos[1],\r\n cellWidth,\r\n cellHeight\r\n )\r\n if (anyHovered) {\r\n this.overIndex = i\r\n let value = 110\r\n if (canvas.pointer_is_down) {\r\n if (!this.pointerDown || this.pointerDown.index !== i) {\r\n this.pointerDown = { index: i, pos: [...mouse] }\r\n }\r\n value = 125\r\n }\r\n ctx.filter = `contrast(${value}%) brightness(${value}%)`\r\n canvas.canvas.style.cursor = 'pointer'\r\n }\r\n }\r\n this.imageRects.push([x, y, cellWidth, cellHeight])\r\n\r\n let wratio = cellWidth / img.width\r\n let hratio = cellHeight / img.height\r\n var ratio = Math.min(wratio, hratio)\r\n\r\n let imgHeight = ratio * img.height\r\n let imgY =\r\n row * cellHeight + shiftY + (cellHeight - imgHeight) / 2\r\n let imgWidth = ratio * img.width\r\n let imgX = col * cellWidth + shiftX + (cellWidth - imgWidth) / 2\r\n\r\n ctx.drawImage(\r\n img,\r\n imgX + cell_padding,\r\n imgY + cell_padding,\r\n imgWidth - cell_padding * 2,\r\n imgHeight - cell_padding * 2\r\n )\r\n if (!compact_mode) {\r\n // rectangle cell and border line style\r\n ctx.strokeStyle = '#8F8F8F'\r\n ctx.lineWidth = 1\r\n ctx.strokeRect(\r\n x + cell_padding,\r\n y + cell_padding,\r\n cellWidth - cell_padding * 2,\r\n cellHeight - cell_padding * 2\r\n )\r\n }\r\n\r\n ctx.filter = 'none'\r\n }\r\n\r\n if (!anyHovered) {\r\n this.pointerDown = null\r\n this.overIndex = null\r\n }\r\n } else {\r\n // Draw individual\r\n let w = this.imgs[imageIndex].naturalWidth\r\n let h = this.imgs[imageIndex].naturalHeight\r\n\r\n const scaleX = dw / w\r\n const scaleY = dh / h\r\n const scale = Math.min(scaleX, scaleY, 1)\r\n\r\n w *= scale\r\n h *= scale\r\n\r\n let x = (dw - w) / 2\r\n let y = (dh - h) / 2 + shiftY\r\n ctx.drawImage(this.imgs[imageIndex], x, y, w, h)\r\n\r\n const drawButton = (x, y, sz, text) => {\r\n const hovered = LiteGraph.isInsideRectangle(\r\n mouse[0],\r\n mouse[1],\r\n x + this.pos[0],\r\n y + this.pos[1],\r\n sz,\r\n sz\r\n )\r\n let fill = '#333'\r\n let textFill = '#fff'\r\n let isClicking = false\r\n if (hovered) {\r\n canvas.canvas.style.cursor = 'pointer'\r\n if (canvas.pointer_is_down) {\r\n fill = '#1e90ff'\r\n isClicking = true\r\n } else {\r\n fill = '#eee'\r\n textFill = '#000'\r\n }\r\n } else {\r\n this.pointerWasDown = null\r\n }\r\n\r\n ctx.fillStyle = fill\r\n ctx.beginPath()\r\n ctx.roundRect(x, y, sz, sz, [4])\r\n ctx.fill()\r\n ctx.fillStyle = textFill\r\n ctx.font = '12px Arial'\r\n ctx.textAlign = 'center'\r\n ctx.fillText(text, x + 15, y + 20)\r\n\r\n return isClicking\r\n }\r\n\r\n if (numImages > 1) {\r\n if (\r\n drawButton(\r\n dw - 40,\r\n dh + top - 40,\r\n 30,\r\n `${this.imageIndex + 1}/${numImages}`\r\n )\r\n ) {\r\n let i =\r\n this.imageIndex + 1 >= numImages ? 0 : this.imageIndex + 1\r\n if (!this.pointerDown || !this.pointerDown.index === i) {\r\n this.pointerDown = { index: i, pos: [...mouse] }\r\n }\r\n }\r\n\r\n if (drawButton(dw - 40, top + 10, 30, `x`)) {\r\n if (!this.pointerDown || !this.pointerDown.index === null) {\r\n this.pointerDown = { index: null, pos: [...mouse] }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n node.prototype.onDrawBackground = function (ctx) {\r\n try {\r\n unsafeDrawBackground.call(this, ctx)\r\n } catch (error) {\r\n console.error('Error drawing node background', error)\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Adds a handler allowing drag+drop of files onto the window to load workflows\r\n */\r\n #addDropHandler() {\r\n // Get prompt from dropped PNG or json\r\n document.addEventListener('drop', async (event) => {\r\n event.preventDefault()\r\n event.stopPropagation()\r\n\r\n const n = this.dragOverNode\r\n this.dragOverNode = null\r\n // Node handles file drop, we dont use the built in onDropFile handler as its buggy\r\n // If you drag multiple files it will call it multiple times with the same file\r\n // @ts-expect-error This is not a standard event. TODO fix it.\r\n if (n && n.onDragDrop && (await n.onDragDrop(event))) {\r\n return\r\n }\r\n // Dragging from Chrome->Firefox there is a file but its a bmp, so ignore that\r\n if (\r\n event.dataTransfer.files.length &&\r\n event.dataTransfer.files[0].type !== 'image/bmp'\r\n ) {\r\n await this.handleFile(event.dataTransfer.files[0])\r\n } else {\r\n // Try loading the first URI in the transfer list\r\n const validTypes = ['text/uri-list', 'text/x-moz-url']\r\n const match = [...event.dataTransfer.types].find((t) =>\r\n validTypes.find((v) => t === v)\r\n )\r\n if (match) {\r\n const uri = event.dataTransfer.getData(match)?.split('\\n')?.[0]\r\n if (uri) {\r\n await this.handleFile(await (await fetch(uri)).blob())\r\n }\r\n }\r\n }\r\n })\r\n\r\n // Always clear over node on drag leave\r\n this.canvasEl.addEventListener('dragleave', async () => {\r\n if (this.dragOverNode) {\r\n this.dragOverNode = null\r\n this.graph.setDirtyCanvas(false, true)\r\n }\r\n })\r\n\r\n // Add handler for dropping onto a specific node\r\n this.canvasEl.addEventListener(\r\n 'dragover',\r\n (e) => {\r\n this.canvas.adjustMouseEvent(e)\r\n // @ts-expect-error: canvasX and canvasY are added by adjustMouseEvent in litegraph\r\n const node = this.graph.getNodeOnPos(e.canvasX, e.canvasY)\r\n if (node) {\r\n // @ts-expect-error This is not a standard event. TODO fix it.\r\n if (node.onDragOver && node.onDragOver(e)) {\r\n this.dragOverNode = node\r\n\r\n // dragover event is fired very frequently, run this on an animation frame\r\n requestAnimationFrame(() => {\r\n this.graph.setDirtyCanvas(false, true)\r\n })\r\n return\r\n }\r\n }\r\n this.dragOverNode = null\r\n },\r\n false\r\n )\r\n }\r\n\r\n /**\r\n * Adds a handler on paste that extracts and loads images or workflows from pasted JSON data\r\n */\r\n #addPasteHandler() {\r\n document.addEventListener('paste', async (e: ClipboardEvent) => {\r\n // ctrl+shift+v is used to paste nodes with connections\r\n // this is handled by litegraph\r\n if (this.shiftDown) return\r\n\r\n // @ts-expect-error: Property 'clipboardData' does not exist on type 'Window & typeof globalThis'.\r\n // Did you mean 'Clipboard'?ts(2551)\r\n // TODO: Not sure what the code wants to do.\r\n let data = e.clipboardData || window.clipboardData\r\n const items = data.items\r\n\r\n // Look for image paste data\r\n for (const item of items) {\r\n if (item.type.startsWith('image/')) {\r\n var imageNode = null\r\n\r\n // If an image node is selected, paste into it\r\n if (\r\n this.canvas.current_node &&\r\n this.canvas.current_node.is_selected &&\r\n ComfyApp.isImageNode(this.canvas.current_node)\r\n ) {\r\n imageNode = this.canvas.current_node\r\n }\r\n\r\n // No image node selected: add a new one\r\n if (!imageNode) {\r\n const newNode = LiteGraph.createNode('LoadImage')\r\n newNode.pos = [...this.canvas.graph_mouse]\r\n imageNode = this.graph.add(newNode)\r\n this.graph.change()\r\n }\r\n const blob = item.getAsFile()\r\n imageNode.pasteFile(blob)\r\n return\r\n }\r\n }\r\n\r\n // No image found. Look for node data\r\n data = data.getData('text/plain')\r\n let workflow: ComfyWorkflowJSON\r\n try {\r\n data = data.slice(data.indexOf('{'))\r\n workflow = JSON.parse(data)\r\n } catch (err) {\r\n try {\r\n data = data.slice(data.indexOf('workflow\\n'))\r\n data = data.slice(data.indexOf('{'))\r\n workflow = JSON.parse(data)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n if (workflow && workflow.version && workflow.nodes && workflow.extra) {\r\n await this.loadGraphData(workflow)\r\n } else {\r\n if (\r\n (e.target instanceof HTMLTextAreaElement &&\r\n e.target.type === 'textarea') ||\r\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\r\n ) {\r\n return\r\n }\r\n\r\n // Litegraph default paste\r\n this.canvas.pasteFromClipboard()\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Adds a handler on copy that serializes selected nodes to JSON\r\n */\r\n #addCopyHandler() {\r\n document.addEventListener('copy', (e) => {\r\n if (!(e.target instanceof Element)) {\r\n return\r\n }\r\n if (\r\n (e.target instanceof HTMLTextAreaElement &&\r\n e.target.type === 'textarea') ||\r\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\r\n ) {\r\n // Default system copy\r\n return\r\n }\r\n const isTargetInGraph =\r\n e.target.classList.contains('litegraph') ||\r\n e.target.classList.contains('graph-canvas-container')\r\n\r\n // copy nodes and clear clipboard\r\n if (isTargetInGraph && this.canvas.selected_nodes) {\r\n this.canvas.copyToClipboard()\r\n e.clipboardData.setData('text', ' ') //clearData doesn't remove images from clipboard\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Handle mouse\r\n *\r\n * Move group by header\r\n */\r\n #addProcessMouseHandler() {\r\n const self = this\r\n\r\n const origProcessMouseDown = LGraphCanvas.prototype.processMouseDown\r\n LGraphCanvas.prototype.processMouseDown = function (e) {\r\n // prepare for ctrl+shift drag: zoom start\r\n if (e.ctrlKey && e.shiftKey && e.buttons) {\r\n self.zoom_drag_start = [e.x, e.y, this.ds.scale]\r\n return\r\n }\r\n\r\n const res = origProcessMouseDown.apply(this, arguments)\r\n\r\n this.selected_group_moving = false\r\n\r\n if (this.selected_group && !this.selected_group_resizing) {\r\n var font_size =\r\n this.selected_group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\r\n var height = font_size * 1.4\r\n\r\n // Move group by header\r\n if (\r\n LiteGraph.isInsideRectangle(\r\n // @ts-expect-error\r\n e.canvasX,\r\n // @ts-expect-error\r\n e.canvasY,\r\n this.selected_group.pos[0],\r\n this.selected_group.pos[1],\r\n this.selected_group.size[0],\r\n height\r\n )\r\n ) {\r\n this.selected_group_moving = true\r\n }\r\n }\r\n\r\n return res\r\n }\r\n const origProcessMouseMove = LGraphCanvas.prototype.processMouseMove\r\n LGraphCanvas.prototype.processMouseMove = function (e) {\r\n // handle ctrl+shift drag\r\n if (e.ctrlKey && e.shiftKey && self.zoom_drag_start) {\r\n // stop canvas zoom action\r\n if (!e.buttons) {\r\n self.zoom_drag_start = null\r\n return\r\n }\r\n\r\n // calculate delta\r\n let deltaY = e.y - self.zoom_drag_start[1]\r\n let startScale = self.zoom_drag_start[2]\r\n\r\n let scale = startScale - deltaY / 100\r\n\r\n this.ds.changeScale(scale, [\r\n self.zoom_drag_start[0],\r\n self.zoom_drag_start[1]\r\n ])\r\n this.graph.change()\r\n\r\n return\r\n }\r\n\r\n const orig_selected_group = this.selected_group\r\n\r\n if (\r\n this.selected_group &&\r\n !this.selected_group_resizing &&\r\n !this.selected_group_moving\r\n ) {\r\n this.selected_group = null\r\n }\r\n\r\n const res = origProcessMouseMove.apply(this, arguments)\r\n\r\n if (\r\n orig_selected_group &&\r\n !this.selected_group_resizing &&\r\n !this.selected_group_moving\r\n ) {\r\n this.selected_group = orig_selected_group\r\n }\r\n\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Handle keypress\r\n *\r\n * Ctrl + M mute/unmute selected nodes\r\n */\r\n #addProcessKeyHandler() {\r\n const self = this\r\n const origProcessKey = LGraphCanvas.prototype.processKey\r\n LGraphCanvas.prototype.processKey = function (e) {\r\n if (!this.graph) {\r\n return\r\n }\r\n\r\n var block_default = false\r\n\r\n if (e.target instanceof Element && e.target.localName == 'input') {\r\n return\r\n }\r\n\r\n if (e.type == 'keydown' && !e.repeat) {\r\n // Ctrl + M mute/unmute\r\n if (e.key === 'm' && (e.metaKey || e.ctrlKey)) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n if (this.selected_nodes[i].mode === 2) {\r\n // never\r\n this.selected_nodes[i].mode = 0 // always\r\n } else {\r\n this.selected_nodes[i].mode = 2 // never\r\n }\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Ctrl + B bypass\r\n if (e.key === 'b' && (e.metaKey || e.ctrlKey)) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n if (this.selected_nodes[i].mode === 4) {\r\n // never\r\n this.selected_nodes[i].mode = 0 // always\r\n } else {\r\n this.selected_nodes[i].mode = 4 // never\r\n }\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Alt + C collapse/uncollapse\r\n if (e.key === 'c' && e.altKey) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n this.selected_nodes[i].collapse()\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Ctrl+C Copy\r\n if (e.key === 'c' && (e.metaKey || e.ctrlKey)) {\r\n // Trigger onCopy\r\n return true\r\n }\r\n\r\n // Ctrl+V Paste\r\n if (\r\n (e.key === 'v' || e.key == 'V') &&\r\n (e.metaKey || e.ctrlKey) &&\r\n !e.shiftKey\r\n ) {\r\n // Trigger onPaste\r\n return true\r\n }\r\n\r\n if (e.key === '+' && e.altKey) {\r\n block_default = true\r\n let scale = this.ds.scale * 1.1\r\n this.ds.changeScale(scale, [\r\n this.ds.element.width / 2,\r\n this.ds.element.height / 2\r\n ])\r\n this.graph.change()\r\n }\r\n\r\n if (e.key === '-' && e.altKey) {\r\n block_default = true\r\n let scale = (this.ds.scale * 1) / 1.1\r\n this.ds.changeScale(scale, [\r\n this.ds.element.width / 2,\r\n this.ds.element.height / 2\r\n ])\r\n this.graph.change()\r\n }\r\n }\r\n\r\n this.graph.change()\r\n\r\n if (block_default) {\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n\r\n // Fall through to Litegraph defaults\r\n return origProcessKey.apply(this, arguments)\r\n }\r\n }\r\n\r\n /**\r\n * Draws group header bar\r\n */\r\n #addDrawGroupsHandler() {\r\n const self = this\r\n const origDrawGroups = LGraphCanvas.prototype.drawGroups\r\n LGraphCanvas.prototype.drawGroups = function (canvas, ctx) {\r\n if (!this.graph) {\r\n return\r\n }\r\n\r\n var groups = this.graph._groups\r\n\r\n ctx.save()\r\n ctx.globalAlpha = 0.7 * this.editor_alpha\r\n\r\n for (var i = 0; i < groups.length; ++i) {\r\n var group = groups[i]\r\n\r\n if (!LiteGraph.overlapBounding(this.visible_area, group._bounding)) {\r\n continue\r\n } //out of the visible area\r\n\r\n ctx.fillStyle = group.color || '#335'\r\n ctx.strokeStyle = group.color || '#335'\r\n var pos = group._pos\r\n var size = group._size\r\n ctx.globalAlpha = 0.25 * this.editor_alpha\r\n ctx.beginPath()\r\n var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\r\n ctx.rect(pos[0] + 0.5, pos[1] + 0.5, size[0], font_size * 1.4)\r\n ctx.fill()\r\n ctx.globalAlpha = this.editor_alpha\r\n }\r\n\r\n ctx.restore()\r\n\r\n const res = origDrawGroups.apply(this, arguments)\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Draws node highlights (executing, drag drop) and progress bar\r\n */\r\n #addDrawNodeHandler() {\r\n const origDrawNodeShape = LGraphCanvas.prototype.drawNodeShape\r\n const self = this\r\n LGraphCanvas.prototype.drawNodeShape = function (\r\n node,\r\n ctx,\r\n size,\r\n fgcolor,\r\n bgcolor,\r\n selected,\r\n mouse_over\r\n ) {\r\n const res = origDrawNodeShape.apply(this, arguments)\r\n\r\n const nodeErrors = self.lastNodeErrors?.[node.id]\r\n\r\n let color = null\r\n let lineWidth = 1\r\n if (node.id === +self.runningNodeId) {\r\n color = '#0f0'\r\n } else if (self.dragOverNode && node.id === self.dragOverNode.id) {\r\n color = 'dodgerblue'\r\n } else if (nodeErrors?.errors) {\r\n color = 'red'\r\n lineWidth = 2\r\n } else if (\r\n self.lastExecutionError &&\r\n +self.lastExecutionError.node_id === node.id\r\n ) {\r\n color = '#f0f'\r\n lineWidth = 2\r\n }\r\n\r\n if (color) {\r\n const shape =\r\n // @ts-expect-error\r\n node._shape || node.constructor.shape || LiteGraph.ROUND_SHAPE\r\n ctx.lineWidth = lineWidth\r\n ctx.globalAlpha = 0.8\r\n ctx.beginPath()\r\n if (shape == LiteGraph.BOX_SHAPE)\r\n ctx.rect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT\r\n )\r\n else if (\r\n shape == LiteGraph.ROUND_SHAPE ||\r\n (shape == LiteGraph.CARD_SHAPE && node.flags.collapsed)\r\n )\r\n ctx.roundRect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\r\n this.round_radius * 2\r\n )\r\n else if (shape == LiteGraph.CARD_SHAPE)\r\n ctx.roundRect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\r\n [this.round_radius * 2, this.round_radius * 2, 2, 2]\r\n )\r\n else if (shape == LiteGraph.CIRCLE_SHAPE)\r\n ctx.arc(\r\n size[0] * 0.5,\r\n size[1] * 0.5,\r\n size[0] * 0.5 + 6,\r\n 0,\r\n Math.PI * 2\r\n )\r\n ctx.strokeStyle = color\r\n ctx.stroke()\r\n ctx.strokeStyle = fgcolor\r\n ctx.globalAlpha = 1\r\n }\r\n\r\n if (self.progress && node.id === +self.runningNodeId) {\r\n ctx.fillStyle = 'green'\r\n ctx.fillRect(\r\n 0,\r\n 0,\r\n size[0] * (self.progress.value / self.progress.max),\r\n 6\r\n )\r\n ctx.fillStyle = bgcolor\r\n }\r\n\r\n // Highlight inputs that failed validation\r\n if (nodeErrors) {\r\n ctx.lineWidth = 2\r\n ctx.strokeStyle = 'red'\r\n for (const error of nodeErrors.errors) {\r\n if (error.extra_info && error.extra_info.input_name) {\r\n const inputIndex = node.findInputSlot(error.extra_info.input_name)\r\n if (inputIndex !== -1) {\r\n let pos = node.getConnectionPos(true, inputIndex)\r\n ctx.beginPath()\r\n ctx.arc(\r\n pos[0] - node.pos[0],\r\n pos[1] - node.pos[1],\r\n 12,\r\n 0,\r\n 2 * Math.PI,\r\n false\r\n )\r\n ctx.stroke()\r\n }\r\n }\r\n }\r\n }\r\n\r\n return res\r\n }\r\n\r\n const origDrawNode = LGraphCanvas.prototype.drawNode\r\n LGraphCanvas.prototype.drawNode = function (node, ctx) {\r\n var editor_alpha = this.editor_alpha\r\n var old_color = node.color\r\n var old_bgcolor = node.bgcolor\r\n\r\n if (node.mode === 2) {\r\n // never\r\n this.editor_alpha = 0.4\r\n }\r\n\r\n // ComfyUI's custom node mode enum value 4 => bypass/never.\r\n // @ts-expect-error\r\n if (node.mode === 4) {\r\n // never\r\n node.bgcolor = '#FF00FF'\r\n this.editor_alpha = 0.2\r\n }\r\n\r\n const adjustColor = (color?: string) => {\r\n return color ? lightenColor(color, 0.5) : color\r\n }\r\n if (app.ui.settings.getSettingValue('Comfy.ColorPalette') === 'light') {\r\n node.bgcolor = adjustColor(node.bgcolor)\r\n node.color = adjustColor(node.color)\r\n }\r\n\r\n const res = origDrawNode.apply(this, arguments)\r\n\r\n this.editor_alpha = editor_alpha\r\n node.color = old_color\r\n node.bgcolor = old_bgcolor\r\n\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Handles updates from the API socket\r\n */\r\n #addApiUpdateHandlers() {\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n this.ui.setStatus(detail)\r\n }\r\n )\r\n\r\n api.addEventListener('progress', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n this.progress = detail\r\n this.graph.setDirtyCanvas(true, false)\r\n })\r\n\r\n api.addEventListener('executing', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n this.progress = null\r\n this.runningNodeId = detail\r\n this.graph.setDirtyCanvas(true, false)\r\n delete this.nodePreviewImages[this.runningNodeId]\r\n })\r\n\r\n api.addEventListener('executed', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n const output = this.nodeOutputs[detail.display_node || detail.node]\r\n if (detail.merge && output) {\r\n for (const k in detail.output ?? {}) {\r\n const v = output[k]\r\n if (v instanceof Array) {\r\n output[k] = v.concat(detail.output[k])\r\n } else {\r\n output[k] = detail.output[k]\r\n }\r\n }\r\n } else {\r\n this.nodeOutputs[detail.display_node || detail.node] = detail.output\r\n }\r\n const node = this.graph.getNodeById(detail.display_node || detail.node)\r\n if (node) {\r\n // @ts-expect-error\r\n if (node.onExecuted)\r\n // @ts-expect-error\r\n node.onExecuted(detail.output)\r\n }\r\n })\r\n\r\n api.addEventListener('execution_start', ({ detail }) => {\r\n this.runningNodeId = null\r\n this.lastExecutionError = null\r\n // @ts-expect-error\r\n this.graph._nodes.forEach((node) => {\r\n // @ts-expect-error\r\n if (node.onExecutionStart)\r\n // @ts-expect-error\r\n node.onExecutionStart()\r\n })\r\n })\r\n\r\n api.addEventListener('execution_error', ({ detail }) => {\r\n this.lastExecutionError = detail\r\n const formattedError = this.#formatExecutionError(detail)\r\n this.ui.dialog.show(formattedError)\r\n this.canvas.draw(true, true)\r\n })\r\n\r\n api.addEventListener('b_preview', ({ detail }) => {\r\n const id = this.runningNodeId\r\n if (id == null) return\r\n\r\n const blob = detail\r\n const blobUrl = URL.createObjectURL(blob)\r\n // @ts-expect-error\r\n this.nodePreviewImages[id] = [blobUrl]\r\n })\r\n\r\n api.init()\r\n }\r\n\r\n #addKeyboardHandler() {\r\n window.addEventListener('keydown', (e) => {\r\n this.shiftDown = e.shiftKey\r\n })\r\n window.addEventListener('keyup', (e) => {\r\n this.shiftDown = e.shiftKey\r\n })\r\n }\r\n\r\n #addConfigureHandler() {\r\n const app = this\r\n const configure = LGraph.prototype.configure\r\n // Flag that the graph is configuring to prevent nodes from running checks while its still loading\r\n LGraph.prototype.configure = function () {\r\n app.configuringGraph = true\r\n try {\r\n return configure.apply(this, arguments)\r\n } finally {\r\n app.configuringGraph = false\r\n }\r\n }\r\n }\r\n\r\n #addAfterConfigureHandler() {\r\n const app = this\r\n // @ts-expect-error\r\n const onConfigure = app.graph.onConfigure\r\n // @ts-expect-error\r\n app.graph.onConfigure = function () {\r\n // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config\r\n // @ts-expect-error\r\n for (const node of app.graph._nodes) {\r\n // @ts-expect-error\r\n node.onGraphConfigured?.()\r\n }\r\n\r\n const r = onConfigure?.apply(this, arguments)\r\n\r\n // Fire after onConfigure, used by primitives to generate widget using input nodes config\r\n // @ts-expect-error _nodes is private.\r\n for (const node of app.graph._nodes) {\r\n node.onAfterGraphConfigured?.()\r\n }\r\n\r\n return r\r\n }\r\n }\r\n\r\n /**\r\n * Loads all extensions from the API into the window in parallel\r\n */\r\n async #loadExtensions() {\r\n const extensions = await api.getExtensions()\r\n this.logging.addEntry('Comfy.App', 'debug', { Extensions: extensions })\r\n\r\n // Need to load core extensions first as some custom extensions\r\n // may depend on them.\r\n await import('../extensions/core/index')\r\n await Promise.all(\r\n extensions\r\n .filter((extension) => !extension.includes('extensions/core'))\r\n .map(async (ext) => {\r\n try {\r\n await import(/* @vite-ignore */ api.fileURL(ext))\r\n } catch (error) {\r\n console.error('Error loading extension', ext, error)\r\n }\r\n })\r\n )\r\n\r\n try {\r\n this.menu.workflows.registerExtension(this)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n async #migrateSettings() {\r\n this.isNewUserSession = true\r\n // Store all current settings\r\n const settings = Object.keys(this.ui.settings).reduce((p, n) => {\r\n const v = localStorage[`Comfy.Settings.${n}`]\r\n if (v) {\r\n try {\r\n p[n] = JSON.parse(v)\r\n } catch (error) {}\r\n }\r\n return p\r\n }, {})\r\n\r\n await api.storeSettings(settings)\r\n }\r\n\r\n async #setUser() {\r\n const userConfig = await api.getUserConfig()\r\n this.storageLocation = userConfig.storage\r\n if (typeof userConfig.migrated == 'boolean') {\r\n // Single user mode migrated true/false for if the default user is created\r\n if (!userConfig.migrated && this.storageLocation === 'server') {\r\n // Default user not created yet\r\n await this.#migrateSettings()\r\n }\r\n return\r\n }\r\n\r\n this.multiUserServer = true\r\n let user = localStorage['Comfy.userId']\r\n const users = userConfig.users ?? {}\r\n if (!user || !users[user]) {\r\n // Lift spinner / BlockUI for user selection.\r\n if (this.vueAppReady) useWorkspaceStore().spinner = false\r\n\r\n // This will rarely be hit so move the loading to on demand\r\n const { UserSelectionScreen } = await import('./ui/userSelection')\r\n\r\n this.ui.menuContainer.style.display = 'none'\r\n const { userId, username, created } =\r\n await new UserSelectionScreen().show(users, user)\r\n this.ui.menuContainer.style.display = ''\r\n\r\n user = userId\r\n localStorage['Comfy.userName'] = username\r\n localStorage['Comfy.userId'] = user\r\n\r\n if (created) {\r\n api.user = user\r\n await this.#migrateSettings()\r\n }\r\n }\r\n\r\n api.user = user\r\n\r\n this.ui.settings.addSetting({\r\n id: 'Comfy.SwitchUser',\r\n name: 'Switch User',\r\n type: (name) => {\r\n let currentUser = localStorage['Comfy.userName']\r\n if (currentUser) {\r\n currentUser = ` (${currentUser})`\r\n }\r\n return $el('tr', [\r\n $el('td', [\r\n $el('label', {\r\n textContent: name\r\n })\r\n ]),\r\n $el('td', [\r\n $el('button', {\r\n textContent: name + (currentUser ?? ''),\r\n onclick: () => {\r\n delete localStorage['Comfy.userId']\r\n delete localStorage['Comfy.userName']\r\n window.location.reload()\r\n }\r\n })\r\n ])\r\n ])\r\n },\r\n // TODO: Is that the correct default value?\r\n defaultValue: undefined\r\n })\r\n }\r\n\r\n /**\r\n * Set up the app on the page\r\n */\r\n async setup(canvasEl: HTMLCanvasElement) {\r\n this.canvasEl = canvasEl\r\n await this.#setUser()\r\n\r\n this.resizeCanvas()\r\n\r\n await Promise.all([\r\n this.workflowManager.loadWorkflows(),\r\n this.ui.settings.load()\r\n ])\r\n await this.#loadExtensions()\r\n\r\n addDomClippingSetting()\r\n this.#addProcessMouseHandler()\r\n this.#addProcessKeyHandler()\r\n this.#addConfigureHandler()\r\n this.#addApiUpdateHandlers()\r\n this.#addRestoreWorkflowView()\r\n\r\n this.graph = new LGraph()\r\n\r\n this.#addAfterConfigureHandler()\r\n\r\n this.canvas = new LGraphCanvas(canvasEl, this.graph)\r\n this.ctx = canvasEl.getContext('2d')\r\n\r\n LiteGraph.alt_drag_do_clone_nodes = true\r\n\r\n this.graph.start()\r\n\r\n // Ensure the canvas fills the window\r\n this.resizeCanvas()\r\n window.addEventListener('resize', () => this.resizeCanvas())\r\n const ro = new ResizeObserver(() => this.resizeCanvas())\r\n ro.observe(this.bodyTop)\r\n ro.observe(this.bodyLeft)\r\n ro.observe(this.bodyRight)\r\n ro.observe(this.bodyBottom)\r\n\r\n await this.#invokeExtensionsAsync('init')\r\n await this.registerNodes()\r\n initWidgets(this)\r\n\r\n // Load previous workflow\r\n let restored = false\r\n try {\r\n const loadWorkflow = async (json) => {\r\n if (json) {\r\n const workflow = JSON.parse(json)\r\n const workflowName = getStorageValue('Comfy.PreviousWorkflow')\r\n await this.loadGraphData(workflow, true, true, workflowName)\r\n return true\r\n }\r\n }\r\n const clientId = api.initialClientId ?? api.clientId\r\n restored =\r\n (clientId &&\r\n (await loadWorkflow(\r\n sessionStorage.getItem(`workflow:${clientId}`)\r\n ))) ||\r\n (await loadWorkflow(localStorage.getItem('workflow')))\r\n } catch (err) {\r\n console.error('Error loading previous workflow', err)\r\n }\r\n\r\n // We failed to restore a workflow so load the default\r\n if (!restored) {\r\n await this.loadGraphData()\r\n }\r\n\r\n // Save current workflow automatically\r\n setInterval(() => {\r\n const sortNodes =\r\n this.vueAppReady &&\r\n useSettingStore().get('Comfy.Workflow.SortNodeIdOnSave')\r\n const workflow = JSON.stringify(this.graph.serialize({ sortNodes }))\r\n localStorage.setItem('workflow', workflow)\r\n if (api.clientId) {\r\n sessionStorage.setItem(`workflow:${api.clientId}`, workflow)\r\n }\r\n }, 1000)\r\n\r\n this.#addDrawNodeHandler()\r\n this.#addDrawGroupsHandler()\r\n this.#addDropHandler()\r\n this.#addCopyHandler()\r\n this.#addPasteHandler()\r\n this.#addKeyboardHandler()\r\n\r\n await this.#invokeExtensionsAsync('setup')\r\n }\r\n\r\n resizeCanvas() {\r\n // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845\r\n const scale = Math.max(window.devicePixelRatio, 1)\r\n\r\n // Clear fixed width and height while calculating rect so it uses 100% instead\r\n this.canvasEl.height = this.canvasEl.width = NaN\r\n const { width, height } = this.canvasEl.getBoundingClientRect()\r\n this.canvasEl.width = Math.round(width * scale)\r\n this.canvasEl.height = Math.round(height * scale)\r\n this.canvasEl.getContext('2d').scale(scale, scale)\r\n this.canvas?.draw(true, true)\r\n }\r\n\r\n private updateVueAppNodeDefs(defs: Record) {\r\n // Frontend only nodes registered by custom nodes.\r\n // Example: https://github.com/rgthree/rgthree-comfy/blob/dd534e5384be8cf0c0fa35865afe2126ba75ac55/src_web/comfyui/fast_groups_bypasser.ts#L10\r\n const rawDefs = Object.fromEntries(\r\n Object.entries(LiteGraph.registered_node_types).map(([name, node]) => [\r\n name,\r\n {\r\n name,\r\n display_name: name,\r\n // @ts-expect-error\r\n category: node.category || '__frontend_only__',\r\n input: { required: {}, optional: {} },\r\n output: [],\r\n output_name: [],\r\n output_is_list: [],\r\n python_module: 'custom_nodes.frontend_only',\r\n description: `Frontend only node for ${name}`\r\n }\r\n ])\r\n )\r\n\r\n const allNodeDefs = {\r\n ...rawDefs,\r\n ...defs,\r\n ...SYSTEM_NODE_DEFS\r\n }\r\n\r\n const nodeDefStore = useNodeDefStore()\r\n nodeDefStore.updateNodeDefs(Object.values(allNodeDefs))\r\n nodeDefStore.updateWidgets(this.widgets)\r\n }\r\n\r\n /**\r\n * Registers nodes with the graph\r\n */\r\n async registerNodes() {\r\n // Load node definitions from the backend\r\n const defs = await api.getNodeDefs()\r\n await this.registerNodesFromDefs(defs)\r\n await this.#invokeExtensionsAsync('registerCustomNodes')\r\n if (this.vueAppReady) {\r\n this.updateVueAppNodeDefs(defs)\r\n }\r\n }\r\n\r\n getWidgetType(inputData, inputName) {\r\n const type = inputData[0]\r\n\r\n if (Array.isArray(type)) {\r\n return 'COMBO'\r\n } else if (`${type}:${inputName}` in this.widgets) {\r\n return `${type}:${inputName}`\r\n } else if (type in this.widgets) {\r\n return type\r\n } else {\r\n return null\r\n }\r\n }\r\n\r\n async registerNodeDef(nodeId: string, nodeData: ComfyNodeDef) {\r\n const self = this\r\n const node = Object.assign(\r\n function ComfyNode() {\r\n var inputs = nodeData['input']['required']\r\n if (nodeData['input']['optional'] != undefined) {\r\n inputs = Object.assign(\r\n {},\r\n nodeData['input']['required'],\r\n nodeData['input']['optional']\r\n )\r\n }\r\n const config = { minWidth: 1, minHeight: 1 }\r\n for (const inputName in inputs) {\r\n const inputData = inputs[inputName]\r\n const type = inputData[0]\r\n\r\n let widgetCreated = true\r\n const widgetType = self.getWidgetType(inputData, inputName)\r\n if (widgetType) {\r\n if (widgetType === 'COMBO') {\r\n Object.assign(\r\n config,\r\n self.widgets.COMBO(this, inputName, inputData, app) || {}\r\n )\r\n } else {\r\n Object.assign(\r\n config,\r\n self.widgets[widgetType](this, inputName, inputData, app) || {}\r\n )\r\n }\r\n } else {\r\n // Node connection inputs\r\n this.addInput(inputName, type)\r\n widgetCreated = false\r\n }\r\n // @ts-expect-error\r\n if (widgetCreated && inputData[1]?.forceInput && config?.widget) {\r\n // @ts-expect-error\r\n if (!config.widget.options) config.widget.options = {}\r\n // @ts-expect-error\r\n config.widget.options.forceInput = inputData[1].forceInput\r\n }\r\n // @ts-expect-error\r\n if (widgetCreated && inputData[1]?.defaultInput && config?.widget) {\r\n // @ts-expect-error\r\n if (!config.widget.options) config.widget.options = {}\r\n // @ts-expect-error\r\n config.widget.options.defaultInput = inputData[1].defaultInput\r\n }\r\n }\r\n\r\n for (const o in nodeData['output']) {\r\n let output = nodeData['output'][o]\r\n if (output instanceof Array) output = 'COMBO'\r\n const outputName = nodeData['output_name'][o] || output\r\n const outputShape = nodeData['output_is_list'][o]\r\n ? LiteGraph.GRID_SHAPE\r\n : LiteGraph.CIRCLE_SHAPE\r\n this.addOutput(outputName, output, { shape: outputShape })\r\n }\r\n\r\n const s = this.computeSize()\r\n s[0] = Math.max(config.minWidth, s[0] * 1.5)\r\n s[1] = Math.max(config.minHeight, s[1])\r\n this.size = s\r\n this.serialize_widgets = true\r\n\r\n app.#invokeExtensionsAsync('nodeCreated', this)\r\n },\r\n {\r\n title: nodeData.display_name || nodeData.name,\r\n comfyClass: nodeData.name,\r\n nodeData\r\n }\r\n )\r\n node.prototype.comfyClass = nodeData.name\r\n\r\n this.#addNodeContextMenuHandler(node)\r\n this.#addDrawBackgroundHandler(node)\r\n this.#addNodeKeyHandler(node)\r\n\r\n await this.#invokeExtensionsAsync('beforeRegisterNodeDef', node, nodeData)\r\n // @ts-expect-error\r\n LiteGraph.registerNodeType(nodeId, node)\r\n // @ts-expect-error\r\n node.category = nodeData.category\r\n }\r\n\r\n async registerNodesFromDefs(defs: Record) {\r\n await this.#invokeExtensionsAsync('addCustomNodeDefs', defs)\r\n\r\n // Generate list of known widgets\r\n this.widgets = Object.assign(\r\n {},\r\n ComfyWidgets,\r\n ...(await this.#invokeExtensionsAsync('getCustomWidgets')).filter(Boolean)\r\n )\r\n\r\n // Register a node for each definition\r\n for (const nodeId in defs) {\r\n this.registerNodeDef(nodeId, defs[nodeId])\r\n }\r\n }\r\n\r\n loadTemplateData(templateData) {\r\n if (!templateData?.templates) {\r\n return\r\n }\r\n\r\n const old = localStorage.getItem('litegrapheditor_clipboard')\r\n\r\n var maxY, nodeBottom, node\r\n\r\n for (const template of templateData.templates) {\r\n if (!template?.data) {\r\n continue\r\n }\r\n\r\n localStorage.setItem('litegrapheditor_clipboard', template.data)\r\n app.canvas.pasteFromClipboard()\r\n\r\n // Move mouse position down to paste the next template below\r\n\r\n maxY = false\r\n\r\n for (const i in app.canvas.selected_nodes) {\r\n node = app.canvas.selected_nodes[i]\r\n\r\n nodeBottom = node.pos[1] + node.size[1]\r\n\r\n if (maxY === false || nodeBottom > maxY) {\r\n maxY = nodeBottom\r\n }\r\n }\r\n\r\n app.canvas.graph_mouse[1] = maxY + 50\r\n }\r\n\r\n localStorage.setItem('litegrapheditor_clipboard', old)\r\n }\r\n\r\n showMissingNodesError(missingNodeTypes, hasAddedNodes = true) {\r\n if (this.vueAppReady)\r\n showLoadWorkflowWarning({\r\n missingNodeTypes,\r\n hasAddedNodes,\r\n maximizable: true\r\n })\r\n\r\n this.logging.addEntry('Comfy.App', 'warn', {\r\n MissingNodes: missingNodeTypes\r\n })\r\n }\r\n\r\n async changeWorkflow(callback, workflow = null) {\r\n try {\r\n this.workflowManager.activeWorkflow?.changeTracker?.store()\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n await callback()\r\n try {\r\n this.workflowManager.setWorkflow(workflow)\r\n this.workflowManager.activeWorkflow?.track()\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n async loadGraphData(\r\n graphData?: ComfyWorkflowJSON,\r\n clean: boolean = true,\r\n restore_view: boolean = true,\r\n workflow: string | null | ComfyWorkflow = null\r\n ) {\r\n if (clean !== false) {\r\n this.clean()\r\n }\r\n\r\n let reset_invalid_values = false\r\n if (!graphData) {\r\n graphData = defaultGraph\r\n reset_invalid_values = true\r\n }\r\n\r\n if (typeof structuredClone === 'undefined') {\r\n graphData = JSON.parse(JSON.stringify(graphData))\r\n } else {\r\n graphData = structuredClone(graphData)\r\n }\r\n\r\n try {\r\n this.workflowManager.setWorkflow(workflow)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n\r\n if (\r\n this.vueAppReady &&\r\n useSettingStore().get('Comfy.Validation.Workflows')\r\n ) {\r\n // TODO: Show validation error in a dialog.\r\n const validatedGraphData = await validateComfyWorkflow(\r\n graphData,\r\n /* onError=*/ alert\r\n )\r\n // If the validation failed, use the original graph data.\r\n // Ideally we should not block users from loading the workflow.\r\n graphData = validatedGraphData ?? graphData\r\n }\r\n\r\n const missingNodeTypes = []\r\n await this.#invokeExtensionsAsync(\r\n 'beforeConfigureGraph',\r\n graphData,\r\n missingNodeTypes\r\n )\r\n for (let n of graphData.nodes) {\r\n // Patch T2IAdapterLoader to ControlNetLoader since they are the same node now\r\n if (n.type == 'T2IAdapterLoader') n.type = 'ControlNetLoader'\r\n if (n.type == 'ConditioningAverage ') n.type = 'ConditioningAverage' //typo fix\r\n if (n.type == 'SDV_img2vid_Conditioning')\r\n n.type = 'SVD_img2vid_Conditioning' //typo fix\r\n\r\n // Find missing node types\r\n if (!(n.type in LiteGraph.registered_node_types)) {\r\n missingNodeTypes.push(n.type)\r\n n.type = sanitizeNodeName(n.type)\r\n }\r\n }\r\n\r\n try {\r\n this.graph.configure(graphData)\r\n if (\r\n restore_view &&\r\n this.enableWorkflowViewRestore.value &&\r\n graphData.extra?.ds\r\n ) {\r\n // @ts-expect-error\r\n // Need to set strict: true for zod to match the type [number, number]\r\n // https://github.com/colinhacks/zod/issues/3056\r\n this.canvas.ds.offset = graphData.extra.ds.offset\r\n this.canvas.ds.scale = graphData.extra.ds.scale\r\n }\r\n\r\n try {\r\n this.workflowManager.activeWorkflow?.track()\r\n } catch (error) {\r\n // TODO: Do we want silently fail here?\r\n }\r\n } catch (error) {\r\n let errorHint = []\r\n // Try extracting filename to see if it was caused by an extension script\r\n const filename =\r\n error.fileName ||\r\n (error.stack || '').match(/(\\/extensions\\/.*\\.js)/)?.[1]\r\n const pos = (filename || '').indexOf('/extensions/')\r\n if (pos > -1) {\r\n errorHint.push(\r\n $el('span', {\r\n textContent: 'This may be due to the following script:'\r\n }),\r\n $el('br'),\r\n $el('span', {\r\n style: {\r\n fontWeight: 'bold'\r\n },\r\n textContent: filename.substring(pos)\r\n })\r\n )\r\n }\r\n\r\n // Show dialog to let the user know something went wrong loading the data\r\n this.ui.dialog.show(\r\n $el('div', [\r\n $el('p', {\r\n textContent: 'Loading aborted due to error reloading workflow data'\r\n }),\r\n $el('pre', {\r\n style: { padding: '5px', backgroundColor: 'rgba(255,0,0,0.2)' },\r\n textContent: error.toString()\r\n }),\r\n $el('pre', {\r\n style: {\r\n padding: '5px',\r\n color: '#ccc',\r\n fontSize: '10px',\r\n maxHeight: '50vh',\r\n overflow: 'auto',\r\n backgroundColor: 'rgba(0,0,0,0.2)'\r\n },\r\n textContent: error.stack || 'No stacktrace available'\r\n }),\r\n ...errorHint\r\n ]).outerHTML\r\n )\r\n\r\n return\r\n }\r\n // @ts-expect-error\r\n for (const node of this.graph._nodes) {\r\n const size = node.computeSize()\r\n size[0] = Math.max(node.size[0], size[0])\r\n size[1] = Math.max(node.size[1], size[1])\r\n node.size = size\r\n if (node.widgets) {\r\n // If you break something in the backend and want to patch workflows in the frontend\r\n // This is the place to do this\r\n for (let widget of node.widgets) {\r\n if (node.type == 'KSampler' || node.type == 'KSamplerAdvanced') {\r\n if (widget.name == 'sampler_name') {\r\n if (widget.value.startsWith('sample_')) {\r\n widget.value = widget.value.slice(7)\r\n }\r\n }\r\n }\r\n if (\r\n node.type == 'KSampler' ||\r\n node.type == 'KSamplerAdvanced' ||\r\n node.type == 'PrimitiveNode'\r\n ) {\r\n if (widget.name == 'control_after_generate') {\r\n if (widget.value === true) {\r\n widget.value = 'randomize'\r\n } else if (widget.value === false) {\r\n widget.value = 'fixed'\r\n }\r\n }\r\n }\r\n if (reset_invalid_values) {\r\n if (widget.type == 'combo') {\r\n if (\r\n !widget.options.values.includes(widget.value) &&\r\n widget.options.values.length > 0\r\n ) {\r\n widget.value = widget.options.values[0]\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.#invokeExtensions('loadedGraphNode', node)\r\n }\r\n\r\n if (missingNodeTypes.length) {\r\n this.showMissingNodesError(missingNodeTypes)\r\n }\r\n await this.#invokeExtensionsAsync('afterConfigureGraph', missingNodeTypes)\r\n requestAnimationFrame(() => {\r\n this.graph.setDirtyCanvas(true, true)\r\n })\r\n }\r\n\r\n /**\r\n * Converts the current graph workflow for sending to the API\r\n * @returns The workflow and node links\r\n */\r\n async graphToPrompt(graph = this.graph, clean = true) {\r\n for (const outerNode of this.graph.computeExecutionOrder(false)) {\r\n if (outerNode.widgets) {\r\n for (const widget of outerNode.widgets) {\r\n // Allow widgets to run callbacks before a prompt has been queued\r\n // e.g. random seed before every gen\r\n widget.beforeQueued?.()\r\n }\r\n }\r\n\r\n const innerNodes = outerNode.getInnerNodes\r\n ? outerNode.getInnerNodes()\r\n : [outerNode]\r\n for (const node of innerNodes) {\r\n if (node.isVirtualNode) {\r\n // Don't serialize frontend only nodes but let them make changes\r\n if (node.applyToGraph) {\r\n node.applyToGraph()\r\n }\r\n }\r\n }\r\n }\r\n\r\n const sortNodes =\r\n this.vueAppReady &&\r\n useSettingStore().get('Comfy.Workflow.SortNodeIdOnSave')\r\n const workflow = graph.serialize({ sortNodes })\r\n const output = {}\r\n // Process nodes in order of execution\r\n for (const outerNode of graph.computeExecutionOrder(false)) {\r\n const skipNode = outerNode.mode === 2 || outerNode.mode === 4\r\n const innerNodes =\r\n !skipNode && outerNode.getInnerNodes\r\n ? outerNode.getInnerNodes()\r\n : [outerNode]\r\n for (const node of innerNodes) {\r\n if (node.isVirtualNode) {\r\n continue\r\n }\r\n\r\n if (node.mode === 2 || node.mode === 4) {\r\n // Don't serialize muted nodes\r\n continue\r\n }\r\n\r\n const inputs = {}\r\n const widgets = node.widgets\r\n\r\n // Store all widget values\r\n if (widgets) {\r\n for (const i in widgets) {\r\n const widget = widgets[i]\r\n if (!widget.options || widget.options.serialize !== false) {\r\n inputs[widget.name] = widget.serializeValue\r\n ? await widget.serializeValue(node, i)\r\n : widget.value\r\n }\r\n }\r\n }\r\n\r\n // Store all node links\r\n for (let i in node.inputs) {\r\n let parent = node.getInputNode(i)\r\n if (parent) {\r\n let link = node.getInputLink(i)\r\n while (parent.mode === 4 || parent.isVirtualNode) {\r\n let found = false\r\n if (parent.isVirtualNode) {\r\n link = parent.getInputLink(link.origin_slot)\r\n if (link) {\r\n parent = parent.getInputNode(link.target_slot)\r\n if (parent) {\r\n found = true\r\n }\r\n }\r\n } else if (link && parent.mode === 4) {\r\n let all_inputs = [link.origin_slot]\r\n if (parent.inputs) {\r\n all_inputs = all_inputs.concat(Object.keys(parent.inputs))\r\n for (let parent_input in all_inputs) {\r\n parent_input = all_inputs[parent_input]\r\n if (\r\n parent.inputs[parent_input]?.type === node.inputs[i].type\r\n ) {\r\n link = parent.getInputLink(parent_input)\r\n if (link) {\r\n parent = parent.getInputNode(parent_input)\r\n }\r\n found = true\r\n break\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!found) {\r\n break\r\n }\r\n }\r\n\r\n if (link) {\r\n if (parent?.updateLink) {\r\n link = parent.updateLink(link)\r\n }\r\n if (link) {\r\n inputs[node.inputs[i].name] = [\r\n String(link.origin_id),\r\n parseInt(link.origin_slot)\r\n ]\r\n }\r\n }\r\n }\r\n }\r\n\r\n let node_data = {\r\n inputs,\r\n class_type: node.comfyClass\r\n }\r\n\r\n if (this.ui.settings.getSettingValue('Comfy.DevMode')) {\r\n // Ignored by the backend.\r\n node_data['_meta'] = {\r\n title: node.title\r\n }\r\n }\r\n\r\n output[String(node.id)] = node_data\r\n }\r\n }\r\n\r\n // Remove inputs connected to removed nodes\r\n if (clean) {\r\n for (const o in output) {\r\n for (const i in output[o].inputs) {\r\n if (\r\n Array.isArray(output[o].inputs[i]) &&\r\n output[o].inputs[i].length === 2 &&\r\n !output[output[o].inputs[i][0]]\r\n ) {\r\n delete output[o].inputs[i]\r\n }\r\n }\r\n }\r\n }\r\n\r\n return { workflow, output }\r\n }\r\n\r\n #formatPromptError(error) {\r\n if (error == null) {\r\n return '(unknown error)'\r\n } else if (typeof error === 'string') {\r\n return error\r\n } else if (error.stack && error.message) {\r\n return error.toString()\r\n } else if (error.response) {\r\n let message = error.response.error.message\r\n if (error.response.error.details)\r\n message += ': ' + error.response.error.details\r\n for (const [nodeID, nodeError] of Object.entries(\r\n error.response.node_errors\r\n )) {\r\n // @ts-expect-error\r\n message += '\\n' + nodeError.class_type + ':'\r\n // @ts-expect-error\r\n for (const errorReason of nodeError.errors) {\r\n message +=\r\n '\\n - ' + errorReason.message + ': ' + errorReason.details\r\n }\r\n }\r\n return message\r\n }\r\n return '(unknown error)'\r\n }\r\n\r\n #formatExecutionError(error) {\r\n if (error == null) {\r\n return '(unknown error)'\r\n }\r\n\r\n const traceback = error.traceback.join('')\r\n const nodeId = error.node_id\r\n const nodeType = error.node_type\r\n\r\n return `Error occurred when executing ${nodeType}:\\n\\n${error.exception_message}\\n\\n${traceback}`\r\n }\r\n\r\n async queuePrompt(number, batchCount = 1) {\r\n this.#queueItems.push({ number, batchCount })\r\n\r\n // Only have one action process the items so each one gets a unique seed correctly\r\n if (this.#processingQueue) {\r\n return\r\n }\r\n\r\n this.#processingQueue = true\r\n this.lastNodeErrors = null\r\n\r\n try {\r\n while (this.#queueItems.length) {\r\n ;({ number, batchCount } = this.#queueItems.pop())\r\n\r\n for (let i = 0; i < batchCount; i++) {\r\n const p = await this.graphToPrompt()\r\n\r\n try {\r\n const res = await api.queuePrompt(number, p)\r\n this.lastNodeErrors = res.node_errors\r\n if (this.lastNodeErrors.length > 0) {\r\n this.canvas.draw(true, true)\r\n } else {\r\n try {\r\n this.workflowManager.storePrompt({\r\n id: res.prompt_id,\r\n nodes: Object.keys(p.output)\r\n })\r\n } catch (error) {}\r\n }\r\n } catch (error) {\r\n const formattedError = this.#formatPromptError(error)\r\n this.ui.dialog.show(formattedError)\r\n if (error.response) {\r\n this.lastNodeErrors = error.response.node_errors\r\n this.canvas.draw(true, true)\r\n }\r\n break\r\n }\r\n\r\n for (const n of p.workflow.nodes) {\r\n const node = this.graph.getNodeById(n.id)\r\n if (node.widgets) {\r\n for (const widget of node.widgets) {\r\n // Allow widgets to run callbacks after a prompt has been queued\r\n // e.g. random seed after every gen\r\n // @ts-expect-error\r\n if (widget.afterQueued) {\r\n // @ts-expect-error\r\n widget.afterQueued()\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.canvas.draw(true, true)\r\n await this.ui.queue.update()\r\n }\r\n }\r\n } finally {\r\n this.#processingQueue = false\r\n }\r\n api.dispatchEvent(\r\n new CustomEvent('promptQueued', { detail: { number, batchCount } })\r\n )\r\n return !this.lastNodeErrors\r\n }\r\n\r\n showErrorOnFileLoad(file) {\r\n this.ui.dialog.show(\r\n $el('div', [\r\n $el('p', { textContent: `Unable to find workflow in ${file.name}` })\r\n ]).outerHTML\r\n )\r\n }\r\n\r\n /**\r\n * Loads workflow data from the specified file\r\n * @param {File} file\r\n */\r\n async handleFile(file) {\r\n const removeExt = (f) => {\r\n if (!f) return f\r\n const p = f.lastIndexOf('.')\r\n if (p === -1) return f\r\n return f.substring(0, p)\r\n }\r\n const fileName = removeExt(file.name)\r\n if (file.type === 'image/png') {\r\n const pngInfo = await getPngMetadata(file)\r\n if (pngInfo?.workflow) {\r\n await this.loadGraphData(\r\n JSON.parse(pngInfo.workflow),\r\n true,\r\n true,\r\n fileName\r\n )\r\n } else if (pngInfo?.prompt) {\r\n this.loadApiJson(JSON.parse(pngInfo.prompt), fileName)\r\n } else if (pngInfo?.parameters) {\r\n this.changeWorkflow(() => {\r\n importA1111(this.graph, pngInfo.parameters)\r\n }, fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (file.type === 'image/webp') {\r\n const pngInfo = await getWebpMetadata(file)\r\n // Support loading workflows from that webp custom node.\r\n const workflow = pngInfo?.workflow || pngInfo?.Workflow\r\n const prompt = pngInfo?.prompt || pngInfo?.Prompt\r\n\r\n if (workflow) {\r\n this.loadGraphData(JSON.parse(workflow), true, true, fileName)\r\n } else if (prompt) {\r\n this.loadApiJson(JSON.parse(prompt), fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (file.type === 'audio/flac' || file.type === 'audio/x-flac') {\r\n const pngInfo = await getFlacMetadata(file)\r\n const workflow = pngInfo?.workflow || pngInfo?.Workflow\r\n const prompt = pngInfo?.prompt || pngInfo?.Prompt\r\n\r\n if (workflow) {\r\n this.loadGraphData(JSON.parse(workflow), true, true, fileName)\r\n } else if (prompt) {\r\n this.loadApiJson(JSON.parse(prompt), fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (\r\n file.type === 'application/json' ||\r\n file.name?.endsWith('.json')\r\n ) {\r\n const reader = new FileReader()\r\n reader.onload = async () => {\r\n const readerResult = reader.result as string\r\n const jsonContent = JSON.parse(readerResult)\r\n if (jsonContent?.templates) {\r\n this.loadTemplateData(jsonContent)\r\n } else if (this.isApiJson(jsonContent)) {\r\n this.loadApiJson(jsonContent, fileName)\r\n } else {\r\n await this.loadGraphData(\r\n JSON.parse(readerResult),\r\n true,\r\n false,\r\n fileName\r\n )\r\n }\r\n }\r\n reader.readAsText(file)\r\n } else if (\r\n file.name?.endsWith('.latent') ||\r\n file.name?.endsWith('.safetensors')\r\n ) {\r\n const info = await getLatentMetadata(file)\r\n // TODO define schema to LatentMetadata\r\n // @ts-expect-error\r\n if (info.workflow) {\r\n await this.loadGraphData(\r\n // @ts-expect-error\r\n JSON.parse(info.workflow),\r\n true,\r\n true,\r\n fileName\r\n )\r\n // @ts-expect-error\r\n } else if (info.prompt) {\r\n // @ts-expect-error\r\n this.loadApiJson(JSON.parse(info.prompt))\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n }\r\n\r\n isApiJson(data) {\r\n // @ts-expect-error\r\n return Object.values(data).every((v) => v.class_type)\r\n }\r\n\r\n loadApiJson(apiData, fileName: string) {\r\n const missingNodeTypes = Object.values(apiData).filter(\r\n // @ts-expect-error\r\n (n) => !LiteGraph.registered_node_types[n.class_type]\r\n )\r\n if (missingNodeTypes.length) {\r\n this.showMissingNodesError(\r\n // @ts-expect-error\r\n missingNodeTypes.map((t) => t.class_type),\r\n false\r\n )\r\n return\r\n }\r\n\r\n const ids = Object.keys(apiData)\r\n app.graph.clear()\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = LiteGraph.createNode(data.class_type)\r\n // @ts-expect-error\r\n node.id = isNaN(+id) ? id : +id\r\n node.title = data._meta?.title ?? node.title\r\n app.graph.add(node)\r\n }\r\n\r\n this.changeWorkflow(() => {\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = app.graph.getNodeById(Number.parseInt(id))\r\n for (const input in data.inputs ?? {}) {\r\n const value = data.inputs[input]\r\n if (value instanceof Array) {\r\n const [fromId, fromSlot] = value\r\n const fromNode = app.graph.getNodeById(fromId)\r\n let toSlot = node.inputs?.findIndex((inp) => inp.name === input)\r\n if (toSlot == null || toSlot === -1) {\r\n try {\r\n // Target has no matching input, most likely a converted widget\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n // @ts-expect-error\r\n if (widget && node.convertWidgetToInput?.(widget)) {\r\n toSlot = node.inputs?.length - 1\r\n }\r\n } catch (error) {}\r\n }\r\n if (toSlot != null || toSlot !== -1) {\r\n fromNode.connect(fromSlot, node, toSlot)\r\n }\r\n } else {\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n if (widget) {\r\n widget.value = value\r\n // @ts-expect-error\r\n widget.callback?.(value)\r\n }\r\n }\r\n }\r\n }\r\n app.graph.arrange()\r\n }, fileName)\r\n\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = app.graph.getNodeById(Number.parseInt(id))\r\n for (const input in data.inputs ?? {}) {\r\n const value = data.inputs[input]\r\n if (value instanceof Array) {\r\n const [fromId, fromSlot] = value\r\n const fromNode = app.graph.getNodeById(fromId)\r\n let toSlot = node.inputs?.findIndex((inp) => inp.name === input)\r\n if (toSlot == null || toSlot === -1) {\r\n try {\r\n // Target has no matching input, most likely a converted widget\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n // @ts-expect-error\r\n if (widget && node.convertWidgetToInput?.(widget)) {\r\n toSlot = node.inputs?.length - 1\r\n }\r\n } catch (error) {}\r\n }\r\n if (toSlot != null || toSlot !== -1) {\r\n fromNode.connect(fromSlot, node, toSlot)\r\n }\r\n } else {\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n if (widget) {\r\n widget.value = value\r\n // @ts-expect-error\r\n widget.callback?.(value)\r\n }\r\n }\r\n }\r\n }\r\n\r\n app.graph.arrange()\r\n }\r\n\r\n /**\r\n * Registers a Comfy web extension with the app\r\n * @param {ComfyExtension} extension\r\n */\r\n registerExtension(extension) {\r\n if (!extension.name) {\r\n throw new Error(\"Extensions must have a 'name' property.\")\r\n }\r\n if (this.extensions.find((ext) => ext.name === extension.name)) {\r\n throw new Error(`Extension named '${extension.name}' already registered.`)\r\n }\r\n this.extensions.push(extension)\r\n }\r\n\r\n /**\r\n * Refresh combo list on whole nodes\r\n */\r\n async refreshComboInNodes() {\r\n const requestToastMessage: ToastMessageOptions = {\r\n severity: 'info',\r\n summary: 'Update',\r\n detail: 'Update requested'\r\n }\r\n if (this.vueAppReady) useToastStore().add(requestToastMessage)\r\n\r\n const defs = await api.getNodeDefs()\r\n\r\n for (const nodeId in defs) {\r\n this.registerNodeDef(nodeId, defs[nodeId])\r\n }\r\n // @ts-expect-error\r\n for (let nodeNum in this.graph._nodes) {\r\n // @ts-expect-error\r\n const node = this.graph._nodes[nodeNum]\r\n const def = defs[node.type]\r\n // @ts-expect-error\r\n // Allow primitive nodes to handle refresh\r\n node.refreshComboInNode?.(defs)\r\n\r\n if (!def) continue\r\n\r\n for (const widgetNum in node.widgets) {\r\n const widget = node.widgets[widgetNum]\r\n if (\r\n widget.type == 'combo' &&\r\n def['input']['required'][widget.name] !== undefined\r\n ) {\r\n widget.options.values = def['input']['required'][widget.name][0]\r\n\r\n if (\r\n widget.name != 'image' &&\r\n !widget.options.values.includes(widget.value)\r\n ) {\r\n widget.value = widget.options.values[0]\r\n // @ts-expect-error\r\n widget.callback(widget.value)\r\n }\r\n }\r\n }\r\n }\r\n\r\n await this.#invokeExtensionsAsync('refreshComboInNodes', defs)\r\n\r\n if (this.vueAppReady) {\r\n this.updateVueAppNodeDefs(defs)\r\n useToastStore().remove(requestToastMessage)\r\n useToastStore().add({\r\n severity: 'success',\r\n summary: 'Updated',\r\n detail: 'Node definitions updated',\r\n life: 1000\r\n })\r\n }\r\n }\r\n\r\n resetView() {\r\n app.canvas.ds.scale = 1\r\n app.canvas.ds.offset = [0, 0]\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n\r\n /**\r\n * Clean current state\r\n */\r\n clean() {\r\n this.nodeOutputs = {}\r\n this.nodePreviewImages = {}\r\n this.lastNodeErrors = null\r\n this.lastExecutionError = null\r\n this.runningNodeId = null\r\n }\r\n\r\n addNodeOnGraph(\r\n nodeDef: ComfyNodeDef | ComfyNodeDefImpl,\r\n options: Record = {}\r\n ): LGraphNode {\r\n const node = LiteGraph.createNode(\r\n nodeDef.name,\r\n nodeDef.display_name,\r\n options\r\n )\r\n this.graph.add(node)\r\n return node\r\n }\r\n\r\n clientPosToCanvasPos(pos: Vector2): Vector2 {\r\n const rect = this.canvasContainer.getBoundingClientRect()\r\n const containerOffsets = [rect.left, rect.top]\r\n return _.zip(pos, this.canvas.ds.offset, containerOffsets).map(\r\n ([p, o1, o2]) => (p - o2) / this.canvas.ds.scale - o1\r\n ) as Vector2\r\n }\r\n\r\n getCanvasCenter(): Vector2 {\r\n const dpi = Math.max(window.devicePixelRatio ?? 1, 1)\r\n const [x, y, w, h] = app.canvas.ds.visible_area\r\n return [x + w / dpi / 2, y + h / dpi / 2]\r\n }\r\n}\r\n\r\nexport const app = new ComfyApp()\r\n","export enum LinkReleaseTriggerMode {\r\n ALWAYS = 'always',\r\n HOLD_SHIFT = 'hold shift',\r\n NOT_HOLD_SHIFT = 'NOT hold shift'\r\n}\r\n","/**\r\n * TODO: Migrate scripts/ui/settings.ts here\r\n *\r\n * Currently the reactive settings act as a proxy of the legacy settings.\r\n * Every time a setting is changed, the settingStore dispatch the change to the\r\n * legacy settings. Every time the legacy settings are changed, the legacy\r\n * settings directly updates the settingStore.settingValues.\r\n */\r\n\r\nimport { app } from '@/scripts/app'\r\nimport { ComfySettingsDialog } from '@/scripts/ui/settings'\r\nimport { Settings } from '@/types/apiTypes'\r\nimport { LinkReleaseTriggerMode } from '@/types/searchBoxTypes'\r\nimport { SettingParams } from '@/types/settingTypes'\r\nimport { buildTree } from '@/utils/treeUtil'\r\nimport { defineStore } from 'pinia'\r\nimport type { TreeNode } from 'primevue/treenode'\r\n\r\nexport interface SettingTreeNode extends TreeNode {\r\n data?: SettingParams\r\n}\r\n\r\ninterface State {\r\n settingValues: Record\r\n settings: Record\r\n}\r\n\r\nexport const useSettingStore = defineStore('setting', {\r\n state: (): State => ({\r\n settingValues: {},\r\n settings: {}\r\n }),\r\n getters: {\r\n settingTree(): SettingTreeNode {\r\n const root = buildTree(\r\n Object.values(this.settings),\r\n (setting: SettingParams) => setting.category || setting.id.split('.')\r\n )\r\n\r\n const floatingSettings = root.children.filter((node) => node.leaf)\r\n if (floatingSettings.length) {\r\n root.children = root.children.filter((node) => !node.leaf)\r\n root.children.push({\r\n key: 'Other',\r\n label: 'Other',\r\n leaf: false,\r\n children: floatingSettings\r\n })\r\n }\r\n\r\n return root\r\n }\r\n },\r\n actions: {\r\n addSettings(settings: ComfySettingsDialog) {\r\n for (const id in settings.settingsLookup) {\r\n const value = settings.getSettingValue(id)\r\n this.settingValues[id] = value\r\n }\r\n this.settings = settings.settingsParamLookup\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Validation.Workflows',\r\n name: 'Validate workflows',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl',\r\n category: ['Comfy', 'Node Search Box', 'Implementation'],\r\n experimental: true,\r\n name: 'Node search box implementation',\r\n type: 'combo',\r\n options: ['default', 'litegraph (legacy)'],\r\n defaultValue: 'default'\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl.LinkReleaseTrigger',\r\n category: ['Comfy', 'Node Search Box', 'LinkReleaseTrigger'],\r\n name: 'Trigger on link release',\r\n tooltip: 'Only applies to the default implementation',\r\n type: 'combo',\r\n options: Object.values(LinkReleaseTriggerMode),\r\n defaultValue: LinkReleaseTriggerMode.ALWAYS\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl.NodePreview',\r\n category: ['Comfy', 'Node Search Box', 'NodePreview'],\r\n name: 'Node preview',\r\n tooltip: 'Only applies to the default implementation',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl.ShowCategory',\r\n category: ['Comfy', 'Node Search Box', 'ShowCategory'],\r\n name: 'Show node category in search results',\r\n tooltip: 'Only applies to the default implementation',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Sidebar.Location',\r\n category: ['Comfy', 'Sidebar', 'Location'],\r\n name: 'Sidebar location',\r\n type: 'combo',\r\n options: ['left', 'right'],\r\n defaultValue: 'left'\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Sidebar.Size',\r\n category: ['Comfy', 'Sidebar', 'Size'],\r\n name: 'Sidebar size',\r\n type: 'combo',\r\n options: ['normal', 'small'],\r\n defaultValue: window.innerWidth < 1600 ? 'small' : 'normal'\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.TextareaWidget.FontSize',\r\n category: ['Comfy', 'Node Widget', 'TextareaWidget', 'FontSize'],\r\n name: 'Textarea widget font size',\r\n type: 'slider',\r\n defaultValue: 10,\r\n attrs: {\r\n min: 8,\r\n max: 24\r\n }\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Workflow.SortNodeIdOnSave',\r\n name: 'Sort node IDs when saving workflow',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Graph.CanvasInfo',\r\n name: 'Show canvas info (fps, etc.)',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Node.ShowDeprecated',\r\n name: 'Show deprecated nodes in search',\r\n tooltip:\r\n 'Deprecated nodes are hidden by default in the UI, but remain functional in existing workflows that use them.',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Node.ShowExperimental',\r\n name: 'Show experimental nodes in search',\r\n tooltip:\r\n 'Experimental nodes are marked as such in the UI and may be subject to significant changes or removal in future versions. Use with caution in production workflows',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n },\r\n\r\n set(key: K, value: Settings[K]) {\r\n this.settingValues[key] = value\r\n app.ui.settings.setSettingValue(key, value)\r\n },\r\n\r\n get(key: K): Settings[K] {\r\n return (\r\n this.settingValues[key] ?? app.ui.settings.getSettingDefaultValue(key)\r\n )\r\n }\r\n }\r\n})\r\n","\r\n\r\n\r\n","\r\n\r\n\r\n","\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-splitter {\\n display: flex;\\n flex-wrap: nowrap;\\n border: 1px solid \".concat(dt('splitter.border.color'), \";\\n background: \").concat(dt('splitter.background'), \";\\n border-radius: \").concat(dt('border.radius.md'), \";\\n color: \").concat(dt('splitter.color'), \";\\n}\\n\\n.p-splitter-vertical {\\n flex-direction: column;\\n}\\n\\n.p-splitter-gutter {\\n flex-grow: 0;\\n flex-shrink: 0;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n z-index: 1;\\n background: \").concat(dt('splitter.gutter.background'), \";\\n}\\n\\n.p-splitter-gutter-handle {\\n border-radius: \").concat(dt('splitter.handle.border.radius'), \";\\n background: \").concat(dt('splitter.handle.background'), \";\\n transition: outline-color \").concat(dt('splitter.transition.duration'), \", box-shadow \").concat(dt('splitter.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-splitter-gutter-handle:focus-visible {\\n box-shadow: \").concat(dt('splitter.handle.focus.ring.shadow'), \";\\n outline: \").concat(dt('splitter.handle.focus.ring.width'), \" \").concat(dt('splitter.handle.focus.ring.style'), \" \").concat(dt('splitter.handle.focus.ring.color'), \";\\n outline-offset: \").concat(dt('splitter.handle.focus.ring.offset'), \";\\n}\\n\\n.p-splitter-horizontal.p-splitter-resizing {\\n cursor: col-resize;\\n user-select: none;\\n}\\n\\n.p-splitter-vertical.p-splitter-resizing {\\n cursor: row-resize;\\n user-select: none;\\n}\\n\\n.p-splitter-horizontal > .p-splitter-gutter > .p-splitter-gutter-handle {\\n height: \").concat(dt('splitter.handle.size'), \";\\n width: 100%;\\n}\\n\\n.p-splitter-vertical > .p-splitter-gutter > .p-splitter-gutter-handle {\\n width: \").concat(dt('splitter.handle.size'), \";\\n height: 100%;\\n}\\n\\n.p-splitter-horizontal > .p-splitter-gutter {\\n cursor: col-resize;\\n}\\n\\n.p-splitter-vertical > .p-splitter-gutter {\\n cursor: row-resize;\\n}\\n\\n.p-splitterpanel {\\n flex-grow: 1;\\n overflow: hidden;\\n}\\n\\n.p-splitterpanel-nested {\\n display: flex;\\n}\\n\\n.p-splitterpanel .p-splitter {\\n flex-grow: 1;\\n border: 0 none;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-splitter p-component', 'p-splitter-' + props.layout];\n },\n gutter: 'p-splitter-gutter',\n gutterHandle: 'p-splitter-gutter-handle'\n};\nvar inlineStyles = {\n root: function root(_ref3) {\n var props = _ref3.props;\n return [{\n display: 'flex',\n 'flex-wrap': 'nowrap'\n }, props.layout === 'vertical' ? {\n 'flex-direction': 'column'\n } : ''];\n }\n};\nvar SplitterStyle = BaseStyle.extend({\n name: 'splitter',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { SplitterStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getVNodeProp } from '@primevue/core/utils';\nimport { getWidth, getHeight, getOuterWidth, getOuterHeight } from '@primeuix/utils/dom';\nimport { isArray } from '@primeuix/utils/object';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SplitterStyle from 'primevue/splitter/style';\nimport { openBlock, createElementBlock, mergeProps, Fragment, renderList, createBlock, resolveDynamicComponent, createElementVNode, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseSplitter',\n \"extends\": BaseComponent,\n props: {\n layout: {\n type: String,\n \"default\": 'horizontal'\n },\n gutterSize: {\n type: Number,\n \"default\": 4\n },\n stateKey: {\n type: String,\n \"default\": null\n },\n stateStorage: {\n type: String,\n \"default\": 'session'\n },\n step: {\n type: Number,\n \"default\": 5\n }\n },\n style: SplitterStyle,\n provide: function provide() {\n return {\n $pcSplitter: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Splitter',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['resizestart', 'resizeend', 'resize'],\n dragging: false,\n mouseMoveListener: null,\n mouseUpListener: null,\n touchMoveListener: null,\n touchEndListener: null,\n size: null,\n gutterElement: null,\n startPos: null,\n prevPanelElement: null,\n nextPanelElement: null,\n nextPanelSize: null,\n prevPanelSize: null,\n panelSizes: null,\n prevPanelIndex: null,\n timer: null,\n data: function data() {\n return {\n prevSize: null\n };\n },\n mounted: function mounted() {\n var _this = this;\n if (this.panels && this.panels.length) {\n var initialized = false;\n if (this.isStateful()) {\n initialized = this.restoreState();\n }\n if (!initialized) {\n var children = _toConsumableArray(this.$el.children).filter(function (child) {\n return child.getAttribute('data-pc-name') === 'splitterpanel';\n });\n var _panelSizes = [];\n this.panels.map(function (panel, i) {\n var panelInitialSize = panel.props && panel.props.size ? panel.props.size : null;\n var panelSize = panelInitialSize || 100 / _this.panels.length;\n _panelSizes[i] = panelSize;\n children[i].style.flexBasis = 'calc(' + panelSize + '% - ' + (_this.panels.length - 1) * _this.gutterSize + 'px)';\n });\n this.panelSizes = _panelSizes;\n this.prevSize = parseFloat(_panelSizes[0]).toFixed(4);\n }\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.clear();\n this.unbindMouseListeners();\n },\n methods: {\n isSplitterPanel: function isSplitterPanel(child) {\n return child.type.name === 'SplitterPanel';\n },\n onResizeStart: function onResizeStart(event, index, isKeyDown) {\n this.gutterElement = event.currentTarget || event.target.parentElement;\n this.size = this.horizontal ? getWidth(this.$el) : getHeight(this.$el);\n if (!isKeyDown) {\n this.dragging = true;\n this.startPos = this.layout === 'horizontal' ? event.pageX || event.changedTouches[0].pageX : event.pageY || event.changedTouches[0].pageY;\n }\n this.prevPanelElement = this.gutterElement.previousElementSibling;\n this.nextPanelElement = this.gutterElement.nextElementSibling;\n if (isKeyDown) {\n this.prevPanelSize = this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true);\n this.nextPanelSize = this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true);\n } else {\n this.prevPanelSize = 100 * (this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true)) / this.size;\n this.nextPanelSize = 100 * (this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true)) / this.size;\n }\n this.prevPanelIndex = index;\n this.$emit('resizestart', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n this.$refs.gutter[index].setAttribute('data-p-gutter-resizing', true);\n this.$el.setAttribute('data-p-resizing', true);\n },\n onResize: function onResize(event, step, isKeyDown) {\n var newPos, newPrevPanelSize, newNextPanelSize;\n if (isKeyDown) {\n if (this.horizontal) {\n newPrevPanelSize = 100 * (this.prevPanelSize + step) / this.size;\n newNextPanelSize = 100 * (this.nextPanelSize - step) / this.size;\n } else {\n newPrevPanelSize = 100 * (this.prevPanelSize - step) / this.size;\n newNextPanelSize = 100 * (this.nextPanelSize + step) / this.size;\n }\n } else {\n if (this.horizontal) newPos = event.pageX * 100 / this.size - this.startPos * 100 / this.size;else newPos = event.pageY * 100 / this.size - this.startPos * 100 / this.size;\n newPrevPanelSize = this.prevPanelSize + newPos;\n newNextPanelSize = this.nextPanelSize - newPos;\n }\n if (this.validateResize(newPrevPanelSize, newNextPanelSize)) {\n this.prevPanelElement.style.flexBasis = 'calc(' + newPrevPanelSize + '% - ' + (this.panels.length - 1) * this.gutterSize + 'px)';\n this.nextPanelElement.style.flexBasis = 'calc(' + newNextPanelSize + '% - ' + (this.panels.length - 1) * this.gutterSize + 'px)';\n this.panelSizes[this.prevPanelIndex] = newPrevPanelSize;\n this.panelSizes[this.prevPanelIndex + 1] = newNextPanelSize;\n this.prevSize = parseFloat(newPrevPanelSize).toFixed(4);\n }\n this.$emit('resize', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n },\n onResizeEnd: function onResizeEnd(event) {\n if (this.isStateful()) {\n this.saveState();\n }\n this.$emit('resizeend', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n this.$refs.gutter.forEach(function (gutter) {\n return gutter.setAttribute('data-p-gutter-resizing', false);\n });\n this.$el.setAttribute('data-p-resizing', false);\n this.clear();\n },\n repeat: function repeat(event, index, step) {\n this.onResizeStart(event, index, true);\n this.onResize(event, step, true);\n },\n setTimer: function setTimer(event, index, step) {\n var _this2 = this;\n if (!this.timer) {\n this.timer = setInterval(function () {\n _this2.repeat(event, index, step);\n }, 40);\n }\n },\n clearTimer: function clearTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n },\n onGutterKeyUp: function onGutterKeyUp() {\n this.clearTimer();\n this.onResizeEnd();\n },\n onGutterKeyDown: function onGutterKeyDown(event, index) {\n switch (event.code) {\n case 'ArrowLeft':\n {\n if (this.layout === 'horizontal') {\n this.setTimer(event, index, this.step * -1);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowRight':\n {\n if (this.layout === 'horizontal') {\n this.setTimer(event, index, this.step);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowDown':\n {\n if (this.layout === 'vertical') {\n this.setTimer(event, index, this.step * -1);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowUp':\n {\n if (this.layout === 'vertical') {\n this.setTimer(event, index, this.step);\n }\n event.preventDefault();\n break;\n }\n }\n },\n onGutterMouseDown: function onGutterMouseDown(event, index) {\n this.onResizeStart(event, index);\n this.bindMouseListeners();\n },\n onGutterTouchStart: function onGutterTouchStart(event, index) {\n this.onResizeStart(event, index);\n this.bindTouchListeners();\n event.preventDefault();\n },\n onGutterTouchMove: function onGutterTouchMove(event) {\n this.onResize(event);\n event.preventDefault();\n },\n onGutterTouchEnd: function onGutterTouchEnd(event) {\n this.onResizeEnd(event);\n this.unbindTouchListeners();\n event.preventDefault();\n },\n bindMouseListeners: function bindMouseListeners() {\n var _this3 = this;\n if (!this.mouseMoveListener) {\n this.mouseMoveListener = function (event) {\n return _this3.onResize(event);\n };\n document.addEventListener('mousemove', this.mouseMoveListener);\n }\n if (!this.mouseUpListener) {\n this.mouseUpListener = function (event) {\n _this3.onResizeEnd(event);\n _this3.unbindMouseListeners();\n };\n document.addEventListener('mouseup', this.mouseUpListener);\n }\n },\n bindTouchListeners: function bindTouchListeners() {\n var _this4 = this;\n if (!this.touchMoveListener) {\n this.touchMoveListener = function (event) {\n return _this4.onResize(event.changedTouches[0]);\n };\n document.addEventListener('touchmove', this.touchMoveListener);\n }\n if (!this.touchEndListener) {\n this.touchEndListener = function (event) {\n _this4.resizeEnd(event);\n _this4.unbindTouchListeners();\n };\n document.addEventListener('touchend', this.touchEndListener);\n }\n },\n validateResize: function validateResize(newPrevPanelSize, newNextPanelSize) {\n if (newPrevPanelSize > 100 || newPrevPanelSize < 0) return false;\n if (newNextPanelSize > 100 || newNextPanelSize < 0) return false;\n var prevPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex], 'minSize');\n if (this.panels[this.prevPanelIndex].props && prevPanelMinSize && prevPanelMinSize > newPrevPanelSize) {\n return false;\n }\n var newPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex + 1], 'minSize');\n if (this.panels[this.prevPanelIndex + 1].props && newPanelMinSize && newPanelMinSize > newNextPanelSize) {\n return false;\n }\n return true;\n },\n unbindMouseListeners: function unbindMouseListeners() {\n if (this.mouseMoveListener) {\n document.removeEventListener('mousemove', this.mouseMoveListener);\n this.mouseMoveListener = null;\n }\n if (this.mouseUpListener) {\n document.removeEventListener('mouseup', this.mouseUpListener);\n this.mouseUpListener = null;\n }\n },\n unbindTouchListeners: function unbindTouchListeners() {\n if (this.touchMoveListener) {\n document.removeEventListener('touchmove', this.touchMoveListener);\n this.touchMoveListener = null;\n }\n if (this.touchEndListener) {\n document.removeEventListener('touchend', this.touchEndListener);\n this.touchEndListener = null;\n }\n },\n clear: function clear() {\n this.dragging = false;\n this.size = null;\n this.startPos = null;\n this.prevPanelElement = null;\n this.nextPanelElement = null;\n this.prevPanelSize = null;\n this.nextPanelSize = null;\n this.gutterElement = null;\n this.prevPanelIndex = null;\n },\n isStateful: function isStateful() {\n return this.stateKey != null;\n },\n getStorage: function getStorage() {\n switch (this.stateStorage) {\n case 'local':\n return window.localStorage;\n case 'session':\n return window.sessionStorage;\n default:\n throw new Error(this.stateStorage + ' is not a valid value for the state storage, supported values are \"local\" and \"session\".');\n }\n },\n saveState: function saveState() {\n if (isArray(this.panelSizes)) {\n this.getStorage().setItem(this.stateKey, JSON.stringify(this.panelSizes));\n }\n },\n restoreState: function restoreState() {\n var _this5 = this;\n var storage = this.getStorage();\n var stateString = storage.getItem(this.stateKey);\n if (stateString) {\n this.panelSizes = JSON.parse(stateString);\n var children = _toConsumableArray(this.$el.children).filter(function (child) {\n return child.getAttribute('data-pc-name') === 'splitterpanel';\n });\n children.forEach(function (child, i) {\n child.style.flexBasis = 'calc(' + _this5.panelSizes[i] + '% - ' + (_this5.panels.length - 1) * _this5.gutterSize + 'px)';\n });\n return true;\n }\n return false;\n }\n },\n computed: {\n panels: function panels() {\n var _this6 = this;\n var panels = [];\n this.$slots[\"default\"]().forEach(function (child) {\n if (_this6.isSplitterPanel(child)) {\n panels.push(child);\n } else if (child.children instanceof Array) {\n child.children.forEach(function (nestedChild) {\n if (_this6.isSplitterPanel(nestedChild)) {\n panels.push(nestedChild);\n }\n });\n }\n });\n return panels;\n },\n gutterStyle: function gutterStyle() {\n if (this.horizontal) return {\n width: this.gutterSize + 'px'\n };else return {\n height: this.gutterSize + 'px'\n };\n },\n horizontal: function horizontal() {\n return this.layout === 'horizontal';\n },\n getPTOptions: function getPTOptions() {\n var _this$$parentInstance;\n return {\n context: {\n nested: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.nestedState\n }\n };\n }\n }\n};\n\nvar _hoisted_1 = [\"onMousedown\", \"onTouchstart\", \"onTouchmove\", \"onTouchend\"];\nvar _hoisted_2 = [\"aria-orientation\", \"aria-valuenow\", \"onKeydown\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n \"data-p-resizing\": false\n }, _ctx.ptmi('root', $options.getPTOptions)), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.panels, function (panel, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: i\n }, [(openBlock(), createBlock(resolveDynamicComponent(panel), {\n tabindex: \"-1\"\n })), i !== $options.panels.length - 1 ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref_for: true,\n ref: \"gutter\",\n \"class\": _ctx.cx('gutter'),\n role: \"separator\",\n tabindex: \"-1\",\n onMousedown: function onMousedown($event) {\n return $options.onGutterMouseDown($event, i);\n },\n onTouchstart: function onTouchstart($event) {\n return $options.onGutterTouchStart($event, i);\n },\n onTouchmove: function onTouchmove($event) {\n return $options.onGutterTouchMove($event, i);\n },\n onTouchend: function onTouchend($event) {\n return $options.onGutterTouchEnd($event, i);\n },\n \"data-p-gutter-resizing\": false\n }, _ctx.ptm('gutter')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('gutterHandle'),\n tabindex: \"0\",\n style: [$options.gutterStyle],\n \"aria-orientation\": _ctx.layout,\n \"aria-valuenow\": $data.prevSize,\n onKeyup: _cache[0] || (_cache[0] = function () {\n return $options.onGutterKeyUp && $options.onGutterKeyUp.apply($options, arguments);\n }),\n onKeydown: function onKeydown($event) {\n return $options.onGutterKeyDown($event, i);\n },\n ref_for: true\n }, _ctx.ptm('gutterHandle')), null, 16, _hoisted_2)], 16, _hoisted_1)) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: function root(_ref) {\n var instance = _ref.instance;\n return ['p-splitterpanel', {\n 'p-splitterpanel-nested': instance.isNested\n }];\n }\n};\nvar SplitterPanelStyle = BaseStyle.extend({\n name: 'splitterpanel',\n classes: classes\n});\n\nexport { SplitterPanelStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport SplitterPanelStyle from 'primevue/splitterpanel/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseSplitterPanel',\n \"extends\": BaseComponent,\n props: {\n size: {\n type: Number,\n \"default\": null\n },\n minSize: {\n type: Number,\n \"default\": null\n }\n },\n style: SplitterPanelStyle,\n provide: function provide() {\n return {\n $pcSplitterPanel: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'SplitterPanel',\n \"extends\": script$1,\n inheritAttrs: false,\n data: function data() {\n return {\n nestedState: null\n };\n },\n computed: {\n isNested: function isNested() {\n var _this = this;\n return this.$slots[\"default\"]().some(function (child) {\n _this.nestedState = child.type.name === 'Splitter' ? true : null;\n return _this.nestedState;\n });\n },\n getPTOptions: function getPTOptions() {\n return {\n context: {\n nested: this.isNested\n }\n };\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root', $options.getPTOptions)), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'TimesCircleIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M7 14C5.61553 14 4.26215 13.5895 3.11101 12.8203C1.95987 12.0511 1.06266 10.9579 0.532846 9.67879C0.00303296 8.3997 -0.13559 6.99224 0.134506 5.63437C0.404603 4.2765 1.07129 3.02922 2.05026 2.05026C3.02922 1.07129 4.2765 0.404603 5.63437 0.134506C6.99224 -0.13559 8.3997 0.00303296 9.67879 0.532846C10.9579 1.06266 12.0511 1.95987 12.8203 3.11101C13.5895 4.26215 14 5.61553 14 7C14 8.85652 13.2625 10.637 11.9497 11.9497C10.637 13.2625 8.85652 14 7 14ZM7 1.16667C5.84628 1.16667 4.71846 1.50879 3.75918 2.14976C2.79989 2.79074 2.05222 3.70178 1.61071 4.76768C1.16919 5.83358 1.05367 7.00647 1.27876 8.13803C1.50384 9.26958 2.05941 10.309 2.87521 11.1248C3.69102 11.9406 4.73042 12.4962 5.86198 12.7212C6.99353 12.9463 8.16642 12.8308 9.23232 12.3893C10.2982 11.9478 11.2093 11.2001 11.8502 10.2408C12.4912 9.28154 12.8333 8.15373 12.8333 7C12.8333 5.45291 12.2188 3.96918 11.1248 2.87521C10.0308 1.78125 8.5471 1.16667 7 1.16667ZM4.66662 9.91668C4.58998 9.91704 4.51404 9.90209 4.44325 9.87271C4.37246 9.84333 4.30826 9.8001 4.2544 9.74557C4.14516 9.6362 4.0838 9.48793 4.0838 9.33335C4.0838 9.17876 4.14516 9.0305 4.2544 8.92113L6.17553 7L4.25443 5.07891C4.15139 4.96832 4.09529 4.82207 4.09796 4.67094C4.10063 4.51982 4.16185 4.37563 4.26872 4.26876C4.3756 4.16188 4.51979 4.10066 4.67091 4.09799C4.82204 4.09532 4.96829 4.15142 5.07887 4.25446L6.99997 6.17556L8.92106 4.25446C9.03164 4.15142 9.1779 4.09532 9.32903 4.09799C9.48015 4.10066 9.62434 4.16188 9.73121 4.26876C9.83809 4.37563 9.89931 4.51982 9.90198 4.67094C9.90464 4.82207 9.84855 4.96832 9.74551 5.07891L7.82441 7L9.74554 8.92113C9.85478 9.0305 9.91614 9.17876 9.91614 9.33335C9.91614 9.48793 9.85478 9.6362 9.74554 9.74557C9.69168 9.8001 9.62748 9.84333 9.55669 9.87271C9.4859 9.90209 9.40996 9.91704 9.33332 9.91668C9.25668 9.91704 9.18073 9.90209 9.10995 9.87271C9.03916 9.84333 8.97495 9.8001 8.9211 9.74557L6.99997 7.82444L5.07884 9.74557C5.02499 9.8001 4.96078 9.84333 4.88999 9.87271C4.81921 9.90209 4.74326 9.91704 4.66662 9.91668Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-chip {\\n display: inline-flex;\\n align-items: center;\\n background: \".concat(dt('chip.background'), \";\\n color: \").concat(dt('chip.color'), \";\\n border-radius: \").concat(dt('chip.border.radius'), \";\\n padding: \").concat(dt('chip.padding.y'), \" \").concat(dt('chip.padding.x'), \";\\n gap: \").concat(dt('chip.gap'), \";\\n}\\n\\n.p-chip-icon {\\n color: \").concat(dt('chip.icon.color'), \";\\n font-size: \").concat(dt('chip.icon.font.size'), \";\\n width: \").concat(dt('chip.icon.size'), \";\\n height: \").concat(dt('chip.icon.size'), \";\\n}\\n\\n.p-chip-image {\\n border-radius: 50%;\\n width: \").concat(dt('chip.image.width'), \";\\n height: \").concat(dt('chip.image.height'), \";\\n margin-left: calc(-1 * \").concat(dt('chip.padding.y'), \");\\n}\\n\\n.p-chip:has(.p-chip-remove-icon) {\\n padding-right: \").concat(dt('chip.padding.y'), \";\\n}\\n\\n.p-chip:has(.p-chip-image) {\\n padding-top: calc(\").concat(dt('chip.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('chip.padding.y'), \" / 2);\\n}\\n\\n.p-chip-remove-icon {\\n cursor: pointer;\\n font-size: \").concat(dt('chip.remove.icon.size'), \";\\n width: \").concat(dt('chip.remove.icon.size'), \";\\n height: \").concat(dt('chip.remove.icon.size'), \";\\n color: \").concat(dt('chip.remove.icon.color'), \";\\n border-radius: 50%;\\n transition: outline-color \").concat(dt('chip.transition.duration'), \", box-shadow \").concat(dt('chip.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-chip-remove-icon:focus-visible {\\n box-shadow: \").concat(dt('chip.remove.icon.focus.ring.shadow'), \";\\n outline: \").concat(dt('chip.remove.icon.focus.ring.width'), \" \").concat(dt('chip.remove.icon.focus.ring.style'), \" \").concat(dt('chip.remove.icon.focus.ring.color'), \";\\n outline-offset: \").concat(dt('chip.remove.icon.focus.ring.offset'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-chip p-component',\n image: 'p-chip-image',\n icon: 'p-chip-icon',\n label: 'p-chip-label',\n removeIcon: 'p-chip-remove-icon'\n};\nvar ChipStyle = BaseStyle.extend({\n name: 'chip',\n theme: theme,\n classes: classes\n});\n\nexport { ChipStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import TimesCircleIcon from '@primevue/icons/timescircle';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ChipStyle from 'primevue/chip/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createBlock, resolveDynamicComponent, createCommentVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseChip',\n \"extends\": BaseComponent,\n props: {\n label: {\n type: String,\n \"default\": null\n },\n icon: {\n type: String,\n \"default\": null\n },\n image: {\n type: String,\n \"default\": null\n },\n removable: {\n type: Boolean,\n \"default\": false\n },\n removeIcon: {\n type: String,\n \"default\": undefined\n }\n },\n style: ChipStyle,\n provide: function provide() {\n return {\n $pcChip: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Chip',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['remove'],\n data: function data() {\n return {\n visible: true\n };\n },\n methods: {\n onKeydown: function onKeydown(event) {\n if (event.key === 'Enter' || event.key === 'Backspace') {\n this.close(event);\n }\n },\n close: function close(event) {\n this.visible = false;\n this.$emit('remove', event);\n }\n },\n components: {\n TimesCircleIcon: TimesCircleIcon\n }\n};\n\nvar _hoisted_1 = [\"aria-label\"];\nvar _hoisted_2 = [\"src\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return $data.visible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('root'),\n \"aria-label\": _ctx.label\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\", {}, function () {\n return [_ctx.image ? (openBlock(), createElementBlock(\"img\", mergeProps({\n key: 0,\n src: _ctx.image\n }, _ctx.ptm('image'), {\n \"class\": _ctx.cx('image')\n }), null, 16, _hoisted_2)) : _ctx.$slots.icon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.icon), mergeProps({\n key: 1,\n \"class\": _ctx.cx('icon')\n }, _ctx.ptm('icon')), null, 16, [\"class\"])) : _ctx.icon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": [_ctx.cx('icon'), _ctx.icon]\n }, _ctx.ptm('icon')), null, 16)) : createCommentVNode(\"\", true), _ctx.label ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 3,\n \"class\": _ctx.cx('label')\n }, _ctx.ptm('label')), toDisplayString(_ctx.label), 17)) : createCommentVNode(\"\", true)];\n }), _ctx.removable ? renderSlot(_ctx.$slots, \"removeicon\", {\n key: 0,\n removeCallback: $options.close,\n keydownCallback: $options.onKeydown\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.removeIcon ? 'span' : 'TimesCircleIcon'), mergeProps({\n tabindex: \"0\",\n \"class\": [_ctx.cx('removeIcon'), _ctx.removeIcon],\n onClick: $options.close,\n onKeydown: $options.onKeydown\n }, _ctx.ptm('removeIcon')), null, 16, [\"class\", \"onClick\", \"onKeydown\"]))];\n }) : createCommentVNode(\"\", true)], 16, _hoisted_1)) : createCommentVNode(\"\", true);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { isNotEmpty } from '@primeuix/utils/object';\nimport BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-autocomplete {\\n display: inline-flex;\\n}\\n\\n.p-autocomplete-loader {\\n position: absolute;\\n top: 50%;\\n margin-top: -0.5rem;\\n right: \".concat(dt('autocomplete.padding.x'), \";\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-loader {\\n right: calc(\").concat(dt('autocomplete.dropdown.width'), \" + \").concat(dt('autocomplete.padding.x'), \");\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input {\\n flex: 1 1 auto;\\n width: 1%;\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input,\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input-multiple {\\n border-top-right-radius: 0;\\n border-bottom-right-radius: 0;\\n}\\n\\n.p-autocomplete-dropdown {\\n cursor: pointer;\\n display: inline-flex;\\n cursor: pointer;\\n user-select: none;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n width: \").concat(dt('autocomplete.dropdown.width'), \";\\n border-top-right-radius: \").concat(dt('autocomplete.dropdown.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('autocomplete.dropdown.border.radius'), \";\\n background: \").concat(dt('autocomplete.dropdown.background'), \";\\n border: 1px solid \").concat(dt('autocomplete.dropdown.border.color'), \";\\n border-left: 0 none;\\n color: \").concat(dt('autocomplete.dropdown.color'), \";\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \", outline-color \").concat(dt('autocomplete.transition.duration'), \", box-shadow \").concat(dt('autocomplete.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-autocomplete-dropdown:not(:disabled):hover {\\n background: \").concat(dt('autocomplete.dropdown.hover.background'), \";\\n border-color: \").concat(dt('autocomplete.dropdown.hover.border.color'), \";\\n color: \").concat(dt('autocomplete.dropdown.hover.color'), \";\\n}\\n\\n.p-autocomplete-dropdown:not(:disabled):active {\\n background: \").concat(dt('autocomplete.dropdown.active.background'), \";\\n border-color: \").concat(dt('autocomplete.dropdown.active.border.color'), \";\\n color: \").concat(dt('autocomplete.dropdown.active.color'), \";\\n}\\n\\n.p-autocomplete-dropdown:focus-visible {\\n box-shadow: \").concat(dt('autocomplete.dropdown.focus.ring.shadow'), \";\\n outline: \").concat(dt('autocomplete.dropdown.focus.ring.width'), \" \").concat(dt('autocomplete.dropdown.focus.ring.style'), \" \").concat(dt('autocomplete.dropdown.focus.ring.color'), \";\\n outline-offset: \").concat(dt('autocomplete.dropdown.focus.ring.offset'), \";\\n}\\n\\n.p-autocomplete .p-autocomplete-overlay {\\n min-width: 100%;\\n}\\n\\n.p-autocomplete-overlay {\\n position: absolute;\\n overflow: auto;\\n top: 0;\\n left: 0;\\n background: \").concat(dt('autocomplete.overlay.background'), \";\\n color: \").concat(dt('autocomplete.overlay.color'), \";\\n border: 1px solid \").concat(dt('autocomplete.overlay.border.color'), \";\\n border-radius: \").concat(dt('autocomplete.overlay.border.radius'), \";\\n box-shadow: \").concat(dt('autocomplete.overlay.shadow'), \";\\n}\\n\\n.p-autocomplete-list {\\n margin: 0;\\n padding: 0;\\n list-style-type: none;\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('autocomplete.list.gap'), \";\\n padding: \").concat(dt('autocomplete.list.padding'), \";\\n}\\n\\n.p-autocomplete-option {\\n cursor: pointer;\\n white-space: nowrap;\\n position: relative;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n padding: \").concat(dt('autocomplete.option.padding'), \";\\n border: 0 none;\\n color: \").concat(dt('autocomplete.option.color'), \";\\n background: transparent;\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \";\\n border-radius: \").concat(dt('autocomplete.option.border.radius'), \";\\n}\\n\\n.p-autocomplete-option:not(.p-autocomplete-option-selected):not(.p-disabled).p-focus {\\n background: \").concat(dt('autocomplete.option.focus.background'), \";\\n color: \").concat(dt('autocomplete.option.focus.color'), \";\\n}\\n\\n.p-autocomplete-option-selected {\\n background: \").concat(dt('autocomplete.option.selected.background'), \";\\n color: \").concat(dt('autocomplete.option.selected.color'), \";\\n}\\n\\n.p-autocomplete-option-selected.p-focus {\\n background: \").concat(dt('autocomplete.option.selected.focus.background'), \";\\n color: \").concat(dt('autocomplete.option.selected.focus.color'), \";\\n}\\n\\n.p-autocomplete-option-group {\\n margin: 0;\\n padding: \").concat(dt('autocomplete.option.group.padding'), \";\\n color: \").concat(dt('autocomplete.option.group.color'), \";\\n background: \").concat(dt('autocomplete.option.group.background'), \";\\n font-weight: \").concat(dt('autocomplete.option.group.font.weight'), \";\\n}\\n\\n.p-autocomplete-input-multiple {\\n margin: 0;\\n list-style-type: none;\\n cursor: text;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n flex-wrap: wrap;\\n padding: calc(\").concat(dt('autocomplete.padding.y'), \" / 2) \").concat(dt('autocomplete.padding.x'), \";\\n gap: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n color: \").concat(dt('autocomplete.color'), \";\\n background: \").concat(dt('autocomplete.background'), \";\\n border: 1px solid \").concat(dt('autocomplete.border.color'), \";\\n border-radius: \").concat(dt('autocomplete.border.radius'), \";\\n width: 100%;\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \", outline-color \").concat(dt('autocomplete.transition.duration'), \", box-shadow \").concat(dt('autocomplete.transition.duration'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('autocomplete.shadow'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled):hover .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.hover.border.color'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled).p-focus .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.focus.border.color'), \";\\n box-shadow: \").concat(dt('autocomplete.focus.ring.shadow'), \";\\n outline: \").concat(dt('autocomplete.focus.ring.width'), \" \").concat(dt('autocomplete.focus.ring.style'), \" \").concat(dt('autocomplete.focus.ring.color'), \";\\n outline-offset: \").concat(dt('autocomplete.focus.ring.offset'), \";\\n}\\n\\n.p-autocomplete.p-invalid .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.invalid.border.color'), \";\\n}\\n\\n.p-variant-filled.p-autocomplete-input-multiple {\\n background: \").concat(dt('autocomplete.filled.background'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled).p-focus .p-variant-filled.p-autocomplete-input-multiple {\\n background: \").concat(dt('autocomplete.filled.focus.background'), \";\\n}\\n\\n.p-autocomplete.p-disabled .p-autocomplete-input-multiple {\\n opacity: 1;\\n background: \").concat(dt('autocomplete.disabled.background'), \";\\n color: \").concat(dt('autocomplete.disabled.color'), \";\\n}\\n\\n.p-autocomplete-chip.p-chip {\\n padding-top: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n border-radius: \").concat(dt('autocomplete.chip.border.radius'), \";\\n}\\n\\n.p-autocomplete-input-multiple:has(.p-autocomplete-chip) {\\n padding-left: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-right: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n}\\n\\n.p-autocomplete-chip-item.p-focus .p-autocomplete-chip {\\n background: \").concat(dt('inputchips.chip.focus.background'), \";\\n color: \").concat(dt('inputchips.chip.focus.color'), \";\\n}\\n\\n.p-autocomplete-input-chip {\\n flex: 1 1 auto;\\n display: inline-flex;\\n padding-top: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n}\\n\\n.p-autocomplete-input-chip input {\\n border: 0 none;\\n outline: 0 none;\\n background: transparent;\\n margin: 0;\\n padding: 0;\\n box-shadow: none;\\n border-radius: 0;\\n width: 100%;\\n font-family: inherit;\\n font-feature-settings: inherit;\\n font-size: 1rem;\\n color: inherit;\\n}\\n\\n.p-autocomplete-input-chip input::placeholder {\\n color: \").concat(dt('autocomplete.placeholder.color'), \";\\n}\\n\\n.p-autocomplete-empty-message {\\n padding: \").concat(dt('autocomplete.empty.message.padding'), \";\\n}\\n\\n.p-autocomplete-fluid {\\n display: flex;\\n}\\n\\n.p-autocomplete-fluid:has(.p-autocomplete-dropdown) .p-autocomplete-input {\\n width: 1%;\\n}\\n\");\n};\nvar inlineStyles = {\n root: {\n position: 'relative'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-autocomplete p-component p-inputwrapper', {\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-focus': instance.focused,\n 'p-inputwrapper-filled': props.modelValue || isNotEmpty(instance.inputValue),\n 'p-inputwrapper-focus': instance.focused,\n 'p-autocomplete-open': instance.overlayVisible,\n 'p-autocomplete-fluid': props.fluid\n }];\n },\n pcInput: 'p-autocomplete-input',\n inputMultiple: function inputMultiple(_ref3) {\n var props = _ref3.props,\n instance = _ref3.instance;\n return ['p-autocomplete-input-multiple', {\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled'\n }];\n },\n chipItem: function chipItem(_ref4) {\n var instance = _ref4.instance,\n i = _ref4.i;\n return ['p-autocomplete-chip-item', {\n 'p-focus': instance.focusedMultipleOptionIndex === i\n }];\n },\n pcChip: 'p-autocomplete-chip',\n chipIcon: 'p-autocomplete-chip-icon',\n inputChip: 'p-autocomplete-input-chip',\n loader: 'p-autocomplete-loader',\n dropdown: 'p-autocomplete-dropdown',\n overlay: 'p-autocomplete-overlay p-component',\n list: 'p-autocomplete-list',\n optionGroup: 'p-autocomplete-option-group',\n option: function option(_ref5) {\n var instance = _ref5.instance,\n _option = _ref5.option,\n i = _ref5.i,\n getItemOptions = _ref5.getItemOptions;\n return ['p-autocomplete-option', {\n 'p-autocomplete-option-selected': instance.isSelected(_option),\n 'p-focus': instance.focusedOptionIndex === instance.getOptionIndex(i, getItemOptions),\n 'p-disabled': instance.isOptionDisabled(_option)\n }];\n },\n emptyMessage: 'p-autocomplete-empty-message'\n};\nvar AutoCompleteStyle = BaseStyle.extend({\n name: 'autocomplete',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { AutoCompleteStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { focus, addStyle, relativePosition, getOuterWidth, absolutePosition, isTouchDevice, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isEmpty, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport Chip from 'primevue/chip';\nimport InputText from 'primevue/inputtext';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport AutoCompleteStyle from 'primevue/autocomplete/style';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, createBlock, normalizeClass, normalizeStyle, createCommentVNode, Fragment, renderList, renderSlot, createVNode, withCtx, createElementVNode, resolveDynamicComponent, toDisplayString, Transition, createSlots, createTextVNode, withDirectives } from 'vue';\n\nvar script$1 = {\n name: 'BaseAutoComplete',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n suggestions: {\n type: Array,\n \"default\": null\n },\n optionLabel: null,\n optionDisabled: null,\n optionGroupLabel: null,\n optionGroupChildren: null,\n scrollHeight: {\n type: String,\n \"default\": '14rem'\n },\n dropdown: {\n type: Boolean,\n \"default\": false\n },\n dropdownMode: {\n type: String,\n \"default\": 'blank'\n },\n multiple: {\n type: Boolean,\n \"default\": false\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n placeholder: {\n type: String,\n \"default\": null\n },\n dataKey: {\n type: String,\n \"default\": null\n },\n minLength: {\n type: Number,\n \"default\": 1\n },\n delay: {\n type: Number,\n \"default\": 300\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n forceSelection: {\n type: Boolean,\n \"default\": false\n },\n completeOnFocus: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n panelStyle: {\n type: Object,\n \"default\": null\n },\n panelClass: {\n type: [String, Object],\n \"default\": null\n },\n overlayStyle: {\n type: Object,\n \"default\": null\n },\n overlayClass: {\n type: [String, Object],\n \"default\": null\n },\n dropdownIcon: {\n type: String,\n \"default\": null\n },\n dropdownClass: {\n type: [String, Object],\n \"default\": null\n },\n loader: {\n type: String,\n \"default\": null\n },\n loadingIcon: {\n type: String,\n \"default\": null\n },\n removeTokenIcon: {\n type: String,\n \"default\": null\n },\n chipIcon: {\n type: String,\n \"default\": null\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n autoOptionFocus: {\n type: Boolean,\n \"default\": false\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n focusOnHover: {\n type: Boolean,\n \"default\": true\n },\n searchLocale: {\n type: String,\n \"default\": undefined\n },\n searchMessage: {\n type: String,\n \"default\": null\n },\n selectionMessage: {\n type: String,\n \"default\": null\n },\n emptySelectionMessage: {\n type: String,\n \"default\": null\n },\n emptySearchMessage: {\n type: String,\n \"default\": null\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n typeahead: {\n type: Boolean,\n \"default\": true\n },\n ariaLabel: {\n type: String,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n fluid: {\n type: Boolean,\n \"default\": false\n }\n },\n style: AutoCompleteStyle,\n provide: function provide() {\n return {\n $pcAutoComplete: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof$1(o) { \"@babel/helpers - typeof\"; return _typeof$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$1(o); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'AutoComplete',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'item-select', 'item-unselect', 'option-select', 'option-unselect', 'dropdown-click', 'clear', 'complete', 'before-show', 'before-hide', 'show', 'hide'],\n outsideClickListener: null,\n resizeListener: null,\n scrollHandler: null,\n overlay: null,\n virtualScroller: null,\n searchTimeout: null,\n dirty: false,\n data: function data() {\n return {\n id: this.$attrs.id,\n clicked: false,\n focused: false,\n focusedOptionIndex: -1,\n focusedMultipleOptionIndex: -1,\n overlayVisible: false,\n searching: false\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n suggestions: function suggestions() {\n if (this.searching) {\n this.show();\n this.focusedOptionIndex = this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n this.searching = false;\n }\n this.autoUpdateModel();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n this.autoUpdateModel();\n },\n updated: function updated() {\n if (this.overlayVisible) {\n this.alignOverlay();\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindOutsideClickListener();\n this.unbindResizeListener();\n if (this.scrollHandler) {\n this.scrollHandler.destroy();\n this.scrollHandler = null;\n }\n if (this.overlay) {\n ZIndex.clear(this.overlay);\n this.overlay = null;\n }\n },\n methods: {\n getOptionIndex: function getOptionIndex(index, fn) {\n return this.virtualScrollerDisabled ? index : fn && fn(index)['index'];\n },\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return option; // TODO: The 'optionValue' properties can be added.\n },\n getOptionRenderKey: function getOptionRenderKey(option, index) {\n return (this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option)) + '_' + index;\n },\n getPTOptions: function getPTOptions(option, itemOptions, index, key) {\n return this.ptm(key, {\n context: {\n selected: this.isSelected(option),\n focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),\n disabled: this.isOptionDisabled(option)\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n isOptionGroup: function isOptionGroup(option) {\n return this.optionGroupLabel && option.optionGroup && option.group;\n },\n getOptionGroupLabel: function getOptionGroupLabel(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupLabel);\n },\n getOptionGroupChildren: function getOptionGroupChildren(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupChildren);\n },\n getAriaPosInset: function getAriaPosInset(index) {\n var _this = this;\n return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function (option) {\n return _this.isOptionGroup(option);\n }).length : index) + 1;\n },\n show: function show(isFocus) {\n this.$emit('before-show');\n this.dirty = true;\n this.overlayVisible = true;\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n isFocus && focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n },\n hide: function hide(isFocus) {\n var _this2 = this;\n var _hide = function _hide() {\n _this2.$emit('before-hide');\n _this2.dirty = isFocus;\n _this2.overlayVisible = false;\n _this2.clicked = false;\n _this2.focusedOptionIndex = -1;\n isFocus && focus(_this2.multiple ? _this2.$refs.focusInput : _this2.$refs.focusInput.$el);\n };\n setTimeout(function () {\n _hide();\n }, 0); // For ScreenReaders\n },\n onFocus: function onFocus(event) {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n if (!this.dirty && this.completeOnFocus) {\n this.search(event, event.target.value, 'focus');\n }\n this.dirty = true;\n this.focused = true;\n if (this.overlayVisible) {\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n this.scrollInView(this.focusedOptionIndex);\n }\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.dirty = false;\n this.focused = false;\n this.focusedOptionIndex = -1;\n this.$emit('blur', event);\n },\n onKeyDown: function onKeyDown(event) {\n if (this.disabled) {\n event.preventDefault();\n return;\n }\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event);\n break;\n case 'ArrowLeft':\n this.onArrowLeftKey(event);\n break;\n case 'ArrowRight':\n this.onArrowRightKey(event);\n break;\n case 'Home':\n this.onHomeKey(event);\n break;\n case 'End':\n this.onEndKey(event);\n break;\n case 'PageDown':\n this.onPageDownKey(event);\n break;\n case 'PageUp':\n this.onPageUpKey(event);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event);\n break;\n case 'Backspace':\n this.onBackspaceKey(event);\n break;\n }\n this.clicked = false;\n },\n onInput: function onInput(event) {\n var _this3 = this;\n if (this.typeahead) {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n var query = event.target.value;\n if (!this.multiple) {\n this.updateModel(event, query);\n }\n if (query.length === 0) {\n this.hide();\n this.$emit('clear');\n } else {\n if (query.length >= this.minLength) {\n this.focusedOptionIndex = -1;\n this.searchTimeout = setTimeout(function () {\n _this3.search(event, query, 'input');\n }, this.delay);\n } else {\n this.hide();\n }\n }\n }\n },\n onChange: function onChange(event) {\n var _this4 = this;\n if (this.forceSelection) {\n var valid = false;\n\n // when forceSelection is on, prevent called twice onOptionSelect()\n if (this.visibleOptions && !this.multiple) {\n var value = this.multiple ? this.$refs.focusInput.value : this.$refs.focusInput.$el.value;\n var matchedValue = this.visibleOptions.find(function (option) {\n return _this4.isOptionMatched(option, value || '');\n });\n if (matchedValue !== undefined) {\n valid = true;\n !this.isSelected(matchedValue) && this.onOptionSelect(event, matchedValue);\n }\n }\n if (!valid) {\n if (this.multiple) this.$refs.focusInput.value = '';else this.$refs.focusInput.$el.value = '';\n this.$emit('clear');\n !this.multiple && this.updateModel(event, null);\n }\n }\n },\n onMultipleContainerFocus: function onMultipleContainerFocus() {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n this.focused = true;\n },\n onMultipleContainerBlur: function onMultipleContainerBlur() {\n this.focusedMultipleOptionIndex = -1;\n this.focused = false;\n },\n onMultipleContainerKeyDown: function onMultipleContainerKeyDown(event) {\n if (this.disabled) {\n event.preventDefault();\n return;\n }\n switch (event.code) {\n case 'ArrowLeft':\n this.onArrowLeftKeyOnMultiple(event);\n break;\n case 'ArrowRight':\n this.onArrowRightKeyOnMultiple(event);\n break;\n case 'Backspace':\n this.onBackspaceKeyOnMultiple(event);\n break;\n }\n },\n onContainerClick: function onContainerClick(event) {\n this.clicked = true;\n if (this.disabled || this.searching || this.loading || this.isInputClicked(event) || this.isDropdownClicked(event)) {\n return;\n }\n if (!this.overlay || !this.overlay.contains(event.target)) {\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n }\n },\n onDropdownClick: function onDropdownClick(event) {\n var query = undefined;\n if (this.overlayVisible) {\n this.hide(true);\n } else {\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n query = this.$refs.focusInput.$el.value;\n if (this.dropdownMode === 'blank') this.search(event, '', 'dropdown');else if (this.dropdownMode === 'current') this.search(event, query, 'dropdown');\n }\n this.$emit('dropdown-click', {\n originalEvent: event,\n query: query\n });\n },\n onOptionSelect: function onOptionSelect(event, option) {\n var isHide = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var value = this.getOptionValue(option);\n if (this.multiple) {\n this.$refs.focusInput.value = '';\n if (!this.isSelected(option)) {\n this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [value]));\n }\n } else {\n this.updateModel(event, value);\n }\n this.$emit('item-select', {\n originalEvent: event,\n value: option\n });\n this.$emit('option-select', {\n originalEvent: event,\n value: option\n });\n isHide && this.hide(true);\n },\n onOptionMouseMove: function onOptionMouseMove(event, index) {\n if (this.focusOnHover) {\n this.changeFocusedOptionIndex(event, index);\n }\n },\n onOverlayClick: function onOverlayClick(event) {\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.$el\n });\n },\n onOverlayKeyDown: function onOverlayKeyDown(event) {\n switch (event.code) {\n case 'Escape':\n this.onEscapeKey(event);\n break;\n }\n },\n onArrowDownKey: function onArrowDownKey(event) {\n if (!this.overlayVisible) {\n return;\n }\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findFirstOptionIndex() : this.findFirstFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event) {\n if (!this.overlayVisible) {\n return;\n }\n if (event.altKey) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n event.preventDefault();\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findLastOptionIndex() : this.findLastFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n }\n },\n onArrowLeftKey: function onArrowLeftKey(event) {\n var target = event.currentTarget;\n this.focusedOptionIndex = -1;\n if (this.multiple) {\n if (isEmpty(target.value) && this.hasSelectedOption) {\n focus(this.$refs.multiContainer);\n this.focusedMultipleOptionIndex = this.modelValue.length;\n } else {\n event.stopPropagation(); // To prevent onArrowLeftKeyOnMultiple method\n }\n }\n },\n onArrowRightKey: function onArrowRightKey(event) {\n this.focusedOptionIndex = -1;\n this.multiple && event.stopPropagation(); // To prevent onArrowRightKeyOnMultiple method\n },\n onHomeKey: function onHomeKey(event) {\n var currentTarget = event.currentTarget;\n var len = currentTarget.value.length;\n currentTarget.setSelectionRange(0, event.shiftKey ? len : 0);\n this.focusedOptionIndex = -1;\n event.preventDefault();\n },\n onEndKey: function onEndKey(event) {\n var currentTarget = event.currentTarget;\n var len = currentTarget.value.length;\n currentTarget.setSelectionRange(event.shiftKey ? 0 : len, len);\n this.focusedOptionIndex = -1;\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView(0);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView(this.visibleOptions.length - 1);\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event) {\n if (!this.typeahead) {\n if (this.multiple) {\n this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [event.target.value]));\n this.$refs.focusInput.value = '';\n }\n } else {\n if (!this.overlayVisible) {\n this.focusedOptionIndex = -1; // reset\n this.onArrowDownKey(event);\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.hide();\n }\n }\n },\n onEscapeKey: function onEscapeKey(event) {\n this.overlayVisible && this.hide(true);\n event.preventDefault();\n },\n onTabKey: function onTabKey(event) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n },\n onBackspaceKey: function onBackspaceKey(event) {\n if (this.multiple) {\n if (isNotEmpty(this.modelValue) && !this.$refs.focusInput.value) {\n var removedValue = this.modelValue[this.modelValue.length - 1];\n var newValue = this.modelValue.slice(0, -1);\n this.$emit('update:modelValue', newValue);\n this.$emit('item-unselect', {\n originalEvent: event,\n value: removedValue\n });\n this.$emit('option-unselect', {\n originalEvent: event,\n value: removedValue\n });\n }\n event.stopPropagation(); // To prevent onBackspaceKeyOnMultiple method\n }\n },\n onArrowLeftKeyOnMultiple: function onArrowLeftKeyOnMultiple() {\n this.focusedMultipleOptionIndex = this.focusedMultipleOptionIndex < 1 ? 0 : this.focusedMultipleOptionIndex - 1;\n },\n onArrowRightKeyOnMultiple: function onArrowRightKeyOnMultiple() {\n this.focusedMultipleOptionIndex++;\n if (this.focusedMultipleOptionIndex > this.modelValue.length - 1) {\n this.focusedMultipleOptionIndex = -1;\n focus(this.$refs.focusInput);\n }\n },\n onBackspaceKeyOnMultiple: function onBackspaceKeyOnMultiple(event) {\n if (this.focusedMultipleOptionIndex !== -1) {\n this.removeOption(event, this.focusedMultipleOptionIndex);\n }\n },\n onOverlayEnter: function onOverlayEnter(el) {\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n addStyle(el, {\n position: 'absolute',\n top: '0',\n left: '0'\n });\n this.alignOverlay();\n },\n onOverlayAfterEnter: function onOverlayAfterEnter() {\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n this.$emit('show');\n },\n onOverlayLeave: function onOverlayLeave() {\n this.unbindOutsideClickListener();\n this.unbindScrollListener();\n this.unbindResizeListener();\n this.$emit('hide');\n this.overlay = null;\n },\n onOverlayAfterLeave: function onOverlayAfterLeave(el) {\n ZIndex.clear(el);\n },\n alignOverlay: function alignOverlay() {\n var target = this.multiple ? this.$refs.multiContainer : this.$refs.focusInput.$el;\n if (this.appendTo === 'self') {\n relativePosition(this.overlay, target);\n } else {\n this.overlay.style.minWidth = getOuterWidth(target) + 'px';\n absolutePosition(this.overlay, target);\n }\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this5 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this5.overlayVisible && _this5.overlay && _this5.isOutsideClicked(event)) {\n _this5.hide();\n }\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this6 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.container, function () {\n if (_this6.overlayVisible) {\n _this6.hide();\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this7 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this7.overlayVisible && !isTouchDevice()) {\n _this7.hide();\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n },\n isOutsideClicked: function isOutsideClicked(event) {\n return !this.overlay.contains(event.target) && !this.isInputClicked(event) && !this.isDropdownClicked(event);\n },\n isInputClicked: function isInputClicked(event) {\n if (this.multiple) return event.target === this.$refs.multiContainer || this.$refs.multiContainer.contains(event.target);else return event.target === this.$refs.focusInput.$el;\n },\n isDropdownClicked: function isDropdownClicked(event) {\n return this.$refs.dropdownButton ? event.target === this.$refs.dropdownButton || this.$refs.dropdownButton.contains(event.target) : false;\n },\n isOptionMatched: function isOptionMatched(option, value) {\n var _this$getOptionLabel;\n return this.isValidOption(option) && ((_this$getOptionLabel = this.getOptionLabel(option)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.searchLocale)) === value.toLocaleLowerCase(this.searchLocale);\n },\n isValidOption: function isValidOption(option) {\n return isNotEmpty(option) && !(this.isOptionDisabled(option) || this.isOptionGroup(option));\n },\n isValidSelectedOption: function isValidSelectedOption(option) {\n return this.isValidOption(option) && this.isSelected(option);\n },\n isEquals: function isEquals(value1, value2) {\n return equals(value1, value2, this.equalityKey);\n },\n isSelected: function isSelected(option) {\n var _this8 = this;\n var optionValue = this.getOptionValue(option);\n return this.multiple ? (this.modelValue || []).some(function (value) {\n return _this8.isEquals(value, optionValue);\n }) : this.isEquals(this.modelValue, this.getOptionValue(option));\n },\n findFirstOptionIndex: function findFirstOptionIndex() {\n var _this9 = this;\n return this.visibleOptions.findIndex(function (option) {\n return _this9.isValidOption(option);\n });\n },\n findLastOptionIndex: function findLastOptionIndex() {\n var _this10 = this;\n return findLastIndex(this.visibleOptions, function (option) {\n return _this10.isValidOption(option);\n });\n },\n findNextOptionIndex: function findNextOptionIndex(index) {\n var _this11 = this;\n var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this11.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;\n },\n findPrevOptionIndex: function findPrevOptionIndex(index) {\n var _this12 = this;\n var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this12.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findSelectedOptionIndex: function findSelectedOptionIndex() {\n var _this13 = this;\n return this.hasSelectedOption ? this.visibleOptions.findIndex(function (option) {\n return _this13.isValidSelectedOption(option);\n }) : -1;\n },\n findFirstFocusedOptionIndex: function findFirstFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;\n },\n findLastFocusedOptionIndex: function findLastFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;\n },\n search: function search(event, query, source) {\n //allow empty string but not undefined or null\n if (query === undefined || query === null) {\n return;\n }\n\n //do not search blank values on input change\n if (source === 'input' && query.trim().length === 0) {\n return;\n }\n this.searching = true;\n this.$emit('complete', {\n originalEvent: event,\n query: query\n });\n },\n removeOption: function removeOption(event, index) {\n var _this14 = this;\n var removedOption = this.modelValue[index];\n var value = this.modelValue.filter(function (_, i) {\n return i !== index;\n }).map(function (option) {\n return _this14.getOptionValue(option);\n });\n this.updateModel(event, value);\n this.$emit('item-unselect', {\n originalEvent: event,\n value: removedOption\n });\n this.$emit('option-unselect', {\n originalEvent: event,\n value: removedOption\n });\n this.dirty = true;\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n },\n changeFocusedOptionIndex: function changeFocusedOptionIndex(event, index) {\n if (this.focusedOptionIndex !== index) {\n this.focusedOptionIndex = index;\n this.scrollInView();\n if (this.selectOnFocus) {\n this.onOptionSelect(event, this.visibleOptions[index], false);\n }\n }\n },\n scrollInView: function scrollInView() {\n var _this15 = this;\n var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n this.$nextTick(function () {\n var id = index !== -1 ? \"\".concat(_this15.id, \"_\").concat(index) : _this15.focusedOptionId;\n var element = findSingle(_this15.list, \"li[id=\\\"\".concat(id, \"\\\"]\"));\n if (element) {\n element.scrollIntoView && element.scrollIntoView({\n block: 'nearest',\n inline: 'start'\n });\n } else if (!_this15.virtualScrollerDisabled) {\n _this15.virtualScroller && _this15.virtualScroller.scrollToIndex(index !== -1 ? index : _this15.focusedOptionIndex);\n }\n });\n },\n autoUpdateModel: function autoUpdateModel() {\n if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption) {\n this.focusedOptionIndex = this.findFirstFocusedOptionIndex();\n this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex], false);\n }\n },\n updateModel: function updateModel(event, value) {\n this.$emit('update:modelValue', value);\n this.$emit('change', {\n originalEvent: event,\n value: value\n });\n },\n flatOptions: function flatOptions(options) {\n var _this16 = this;\n return (options || []).reduce(function (result, option, index) {\n result.push({\n optionGroup: option,\n group: true,\n index: index\n });\n var optionGroupChildren = _this16.getOptionGroupChildren(option);\n optionGroupChildren && optionGroupChildren.forEach(function (o) {\n return result.push(o);\n });\n return result;\n }, []);\n },\n overlayRef: function overlayRef(el) {\n this.overlay = el;\n },\n listRef: function listRef(el, contentRef) {\n this.list = el;\n contentRef && contentRef(el); // For VirtualScroller\n },\n virtualScrollerRef: function virtualScrollerRef(el) {\n this.virtualScroller = el;\n }\n },\n computed: {\n visibleOptions: function visibleOptions() {\n return this.optionGroupLabel ? this.flatOptions(this.suggestions) : this.suggestions || [];\n },\n inputValue: function inputValue() {\n if (isNotEmpty(this.modelValue)) {\n if (_typeof$1(this.modelValue) === 'object') {\n var label = this.getOptionLabel(this.modelValue);\n return label != null ? label : this.modelValue;\n } else {\n return this.modelValue;\n }\n } else {\n return '';\n }\n },\n hasSelectedOption: function hasSelectedOption() {\n return isNotEmpty(this.modelValue);\n },\n equalityKey: function equalityKey() {\n return this.dataKey; // TODO: The 'optionValue' properties can be added.\n },\n searchResultMessageText: function searchResultMessageText() {\n return isNotEmpty(this.visibleOptions) && this.overlayVisible ? this.searchMessageText.replaceAll('{0}', this.visibleOptions.length) : this.emptySearchMessageText;\n },\n searchMessageText: function searchMessageText() {\n return this.searchMessage || this.$primevue.config.locale.searchMessage || '';\n },\n emptySearchMessageText: function emptySearchMessageText() {\n return this.emptySearchMessage || this.$primevue.config.locale.emptySearchMessage || '';\n },\n selectionMessageText: function selectionMessageText() {\n return this.selectionMessage || this.$primevue.config.locale.selectionMessage || '';\n },\n emptySelectionMessageText: function emptySelectionMessageText() {\n return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || '';\n },\n selectedMessageText: function selectedMessageText() {\n return this.hasSelectedOption ? this.selectionMessageText.replaceAll('{0}', this.multiple ? this.modelValue.length : '1') : this.emptySelectionMessageText;\n },\n listAriaLabel: function listAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.listLabel : undefined;\n },\n focusedOptionId: function focusedOptionId() {\n return this.focusedOptionIndex !== -1 ? \"\".concat(this.id, \"_\").concat(this.focusedOptionIndex) : null;\n },\n focusedMultipleOptionId: function focusedMultipleOptionId() {\n return this.focusedMultipleOptionIndex !== -1 ? \"\".concat(this.id, \"_multiple_option_\").concat(this.focusedMultipleOptionIndex) : null;\n },\n ariaSetSize: function ariaSetSize() {\n var _this17 = this;\n return this.visibleOptions.filter(function (option) {\n return !_this17.isOptionGroup(option);\n }).length;\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n },\n panelId: function panelId() {\n return this.id + '_panel';\n }\n },\n components: {\n InputText: InputText,\n VirtualScroller: VirtualScroller,\n Portal: Portal,\n ChevronDownIcon: ChevronDownIcon,\n SpinnerIcon: SpinnerIcon,\n Chip: Chip\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"aria-activedescendant\"];\nvar _hoisted_2 = [\"id\", \"aria-label\", \"aria-setsize\", \"aria-posinset\"];\nvar _hoisted_3 = [\"id\", \"placeholder\", \"tabindex\", \"disabled\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-invalid\"];\nvar _hoisted_4 = [\"disabled\", \"aria-expanded\", \"aria-controls\"];\nvar _hoisted_5 = [\"id\"];\nvar _hoisted_6 = [\"id\", \"aria-label\"];\nvar _hoisted_7 = [\"id\"];\nvar _hoisted_8 = [\"id\", \"aria-label\", \"aria-selected\", \"aria-disabled\", \"aria-setsize\", \"aria-posinset\", \"onClick\", \"onMousemove\", \"data-p-selected\", \"data-p-focus\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_Chip = resolveComponent(\"Chip\");\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_VirtualScroller = resolveComponent(\"VirtualScroller\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n onClick: _cache[11] || (_cache[11] = function () {\n return $options.onContainerClick && $options.onContainerClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [!_ctx.multiple ? (openBlock(), createBlock(_component_InputText, {\n key: 0,\n ref: \"focusInput\",\n id: _ctx.inputId,\n type: \"text\",\n \"class\": normalizeClass([_ctx.cx('pcInput'), _ctx.inputClass]),\n style: normalizeStyle(_ctx.inputStyle),\n value: $options.inputValue,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n invalid: _ctx.invalid,\n variant: _ctx.variant,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-autocomplete\": \"list\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $options.panelId,\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n onFocus: $options.onFocus,\n onBlur: $options.onBlur,\n onKeydown: $options.onKeyDown,\n onInput: $options.onInput,\n onChange: $options.onChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcInput')\n }, null, 8, [\"id\", \"class\", \"style\", \"value\", \"placeholder\", \"tabindex\", \"disabled\", \"invalid\", \"variant\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"onFocus\", \"onBlur\", \"onKeydown\", \"onInput\", \"onChange\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), _ctx.multiple ? (openBlock(), createElementBlock(\"ul\", mergeProps({\n key: 1,\n ref: \"multiContainer\",\n \"class\": _ctx.cx('inputMultiple'),\n tabindex: \"-1\",\n role: \"listbox\",\n \"aria-orientation\": \"horizontal\",\n \"aria-activedescendant\": $data.focused ? $options.focusedMultipleOptionId : undefined,\n onFocus: _cache[5] || (_cache[5] = function () {\n return $options.onMultipleContainerFocus && $options.onMultipleContainerFocus.apply($options, arguments);\n }),\n onBlur: _cache[6] || (_cache[6] = function () {\n return $options.onMultipleContainerBlur && $options.onMultipleContainerBlur.apply($options, arguments);\n }),\n onKeydown: _cache[7] || (_cache[7] = function () {\n return $options.onMultipleContainerKeyDown && $options.onMultipleContainerKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('inputMultiple')), [(openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.modelValue, function (option, i) {\n return openBlock(), createElementBlock(\"li\", mergeProps({\n key: \"\".concat(i, \"_\").concat($options.getOptionLabel(option)),\n id: $data.id + '_multiple_option_' + i,\n \"class\": _ctx.cx('chipItem', {\n i: i\n }),\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": true,\n \"aria-setsize\": _ctx.modelValue.length,\n \"aria-posinset\": i + 1,\n ref_for: true\n }, _ctx.ptm('chipItem')), [renderSlot(_ctx.$slots, \"chip\", mergeProps({\n \"class\": _ctx.cx('pcChip'),\n value: option,\n index: i,\n removeCallback: function removeCallback(event) {\n return $options.removeOption(event, i);\n },\n ref_for: true\n }, _ctx.ptm('pcChip')), function () {\n return [createVNode(_component_Chip, {\n \"class\": normalizeClass(_ctx.cx('pcChip')),\n label: $options.getOptionLabel(option),\n removeIcon: _ctx.chipIcon || _ctx.removeTokenIcon,\n removable: \"\",\n unstyled: _ctx.unstyled,\n onRemove: function onRemove($event) {\n return $options.removeOption($event, i);\n },\n pt: _ctx.ptm('pcChip')\n }, {\n removeicon: withCtx(function () {\n return [renderSlot(_ctx.$slots, _ctx.$slots.chipicon ? 'chipicon' : 'removetokenicon', {\n \"class\": normalizeClass(_ctx.cx('chipIcon')),\n index: i,\n removeCallback: function removeCallback(event) {\n return $options.removeOption(event, i);\n }\n })];\n }),\n _: 2\n }, 1032, [\"class\", \"label\", \"removeIcon\", \"unstyled\", \"onRemove\", \"pt\"])];\n })], 16, _hoisted_2);\n }), 128)), createElementVNode(\"li\", mergeProps({\n \"class\": _ctx.cx('inputChip'),\n role: \"option\"\n }, _ctx.ptm('inputChip')), [createElementVNode(\"input\", mergeProps({\n ref: \"focusInput\",\n id: _ctx.inputId,\n type: \"text\",\n style: _ctx.inputStyle,\n \"class\": _ctx.inputClass,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-autocomplete\": \"list\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[2] || (_cache[2] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n onInput: _cache[3] || (_cache[3] = function () {\n return $options.onInput && $options.onInput.apply($options, arguments);\n }),\n onChange: _cache[4] || (_cache[4] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, _ctx.ptm('input')), null, 16, _hoisted_3)], 16)], 16, _hoisted_1)) : createCommentVNode(\"\", true), $data.searching || _ctx.loading ? renderSlot(_ctx.$slots, _ctx.$slots.loader ? 'loader' : 'loadingicon', {\n key: 2,\n \"class\": normalizeClass(_ctx.cx('loader'))\n }, function () {\n return [_ctx.loader || _ctx.loadingIcon ? (openBlock(), createElementBlock(\"i\", mergeProps({\n key: 0,\n \"class\": ['pi-spin', _ctx.cx('loader'), _ctx.loader, _ctx.loadingIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loader')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('loader'),\n spin: \"\",\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loader')), null, 16, [\"class\"]))];\n }) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, _ctx.$slots.dropdown ? 'dropdown' : 'dropdownbutton', {\n toggleCallback: function toggleCallback(event) {\n return $options.onDropdownClick(event);\n }\n }, function () {\n return [_ctx.dropdown ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n ref: \"dropdownButton\",\n type: \"button\",\n \"class\": [_ctx.cx('dropdown'), _ctx.dropdownClass],\n disabled: _ctx.disabled,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $options.panelId,\n onClick: _cache[8] || (_cache[8] = function () {\n return $options.onDropdownClick && $options.onDropdownClick.apply($options, arguments);\n })\n }, _ctx.ptm('dropdown')), [renderSlot(_ctx.$slots, \"dropdownicon\", {\n \"class\": normalizeClass(_ctx.dropdownIcon)\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.dropdownIcon ? 'span' : 'ChevronDownIcon'), mergeProps({\n \"class\": _ctx.dropdownIcon\n }, _ctx.ptm('dropdownIcon')), null, 16, [\"class\"]))];\n })], 16, _hoisted_4)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSearchResult'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.searchResultMessageText), 17), createVNode(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-connected-overlay\",\n onEnter: $options.onOverlayEnter,\n onAfterEnter: $options.onOverlayAfterEnter,\n onLeave: $options.onOverlayLeave,\n onAfterLeave: $options.onOverlayAfterLeave\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [$data.overlayVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.overlayRef,\n id: $options.panelId,\n \"class\": [_ctx.cx('overlay'), _ctx.panelClass, _ctx.overlayClass],\n style: _objectSpread(_objectSpread(_objectSpread({}, _ctx.panelStyle), _ctx.overlayStyle), {}, {\n 'max-height': $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }),\n onClick: _cache[9] || (_cache[9] = function () {\n return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);\n }),\n onKeydown: _cache[10] || (_cache[10] = function () {\n return $options.onOverlayKeyDown && $options.onOverlayKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('overlay')), [renderSlot(_ctx.$slots, \"header\", {\n value: _ctx.modelValue,\n suggestions: $options.visibleOptions\n }), createVNode(_component_VirtualScroller, mergeProps({\n ref: $options.virtualScrollerRef\n }, _ctx.virtualScrollerOptions, {\n style: {\n height: _ctx.scrollHeight\n },\n items: $options.visibleOptions,\n tabindex: -1,\n disabled: $options.virtualScrollerDisabled,\n pt: _ctx.ptm('virtualScroller')\n }), createSlots({\n content: withCtx(function (_ref) {\n var styleClass = _ref.styleClass,\n contentRef = _ref.contentRef,\n items = _ref.items,\n getItemOptions = _ref.getItemOptions,\n contentStyle = _ref.contentStyle,\n itemSize = _ref.itemSize;\n return [createElementVNode(\"ul\", mergeProps({\n ref: function ref(el) {\n return $options.listRef(el, contentRef);\n },\n id: $data.id + '_list',\n \"class\": [_ctx.cx('list'), styleClass],\n style: contentStyle,\n role: \"listbox\",\n \"aria-label\": $options.listAriaLabel\n }, _ctx.ptm('list')), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function (option, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getOptionRenderKey(option, $options.getOptionIndex(i, getItemOptions))\n }, [$options.isOptionGroup(option) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('optionGroup'),\n role: \"option\",\n ref_for: true\n }, _ctx.ptm('optionGroup')), [renderSlot(_ctx.$slots, \"optiongroup\", {\n option: option.optionGroup,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionGroupLabel(option.optionGroup)), 1)];\n })], 16, _hoisted_7)) : withDirectives((openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('option', {\n option: option,\n i: i,\n getItemOptions: getItemOptions\n }),\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": $options.isSelected(option),\n \"aria-disabled\": $options.isOptionDisabled(option),\n \"aria-setsize\": $options.ariaSetSize,\n \"aria-posinset\": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),\n onClick: function onClick($event) {\n return $options.onOptionSelect($event, option);\n },\n onMousemove: function onMousemove($event) {\n return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));\n },\n \"data-p-selected\": $options.isSelected(option),\n \"data-p-focus\": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),\n \"data-p-disabled\": $options.isOptionDisabled(option),\n ref_for: true\n }, $options.getPTOptions(option, getItemOptions, i, 'option')), [renderSlot(_ctx.$slots, \"option\", {\n option: option,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionLabel(option)), 1)];\n })], 16, _hoisted_8)), [[_directive_ripple]])], 64);\n }), 128)), !items || items && items.length === 0 ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage')), [renderSlot(_ctx.$slots, \"empty\", {}, function () {\n return [createTextVNode(toDisplayString($options.searchResultMessageText), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_6)];\n }),\n _: 2\n }, [_ctx.$slots.loader ? {\n name: \"loader\",\n fn: withCtx(function (_ref2) {\n var options = _ref2.options;\n return [renderSlot(_ctx.$slots, \"loader\", {\n options: options\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"style\", \"items\", \"disabled\", \"pt\"]), renderSlot(_ctx.$slots, \"footer\", {\n value: _ctx.modelValue,\n suggestions: $options.visibleOptions\n }), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSelectedMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.selectedMessageText), 17)], 16, _hoisted_5)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 3\n }, 8, [\"appendTo\"])], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'WindowMaximizeIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M7 14H11.8C12.3835 14 12.9431 13.7682 13.3556 13.3556C13.7682 12.9431 14 12.3835 14 11.8V2.2C14 1.61652 13.7682 1.05694 13.3556 0.644365C12.9431 0.231785 12.3835 0 11.8 0H2.2C1.61652 0 1.05694 0.231785 0.644365 0.644365C0.231785 1.05694 0 1.61652 0 2.2V7C0 7.15913 0.063214 7.31174 0.175736 7.42426C0.288258 7.53679 0.44087 7.6 0.6 7.6C0.75913 7.6 0.911742 7.53679 1.02426 7.42426C1.13679 7.31174 1.2 7.15913 1.2 7V2.2C1.2 1.93478 1.30536 1.68043 1.49289 1.49289C1.68043 1.30536 1.93478 1.2 2.2 1.2H11.8C12.0652 1.2 12.3196 1.30536 12.5071 1.49289C12.6946 1.68043 12.8 1.93478 12.8 2.2V11.8C12.8 12.0652 12.6946 12.3196 12.5071 12.5071C12.3196 12.6946 12.0652 12.8 11.8 12.8H7C6.84087 12.8 6.68826 12.8632 6.57574 12.9757C6.46321 13.0883 6.4 13.2409 6.4 13.4C6.4 13.5591 6.46321 13.7117 6.57574 13.8243C6.68826 13.9368 6.84087 14 7 14ZM9.77805 7.42192C9.89013 7.534 10.0415 7.59788 10.2 7.59995C10.3585 7.59788 10.5099 7.534 10.622 7.42192C10.7341 7.30985 10.798 7.15844 10.8 6.99995V3.94242C10.8066 3.90505 10.8096 3.86689 10.8089 3.82843C10.8079 3.77159 10.7988 3.7157 10.7824 3.6623C10.756 3.55552 10.701 3.45698 10.622 3.37798C10.5099 3.2659 10.3585 3.20202 10.2 3.19995H7.00002C6.84089 3.19995 6.68828 3.26317 6.57576 3.37569C6.46324 3.48821 6.40002 3.64082 6.40002 3.79995C6.40002 3.95908 6.46324 4.11169 6.57576 4.22422C6.68828 4.33674 6.84089 4.39995 7.00002 4.39995H8.80006L6.19997 7.00005C6.10158 7.11005 6.04718 7.25246 6.04718 7.40005C6.04718 7.54763 6.10158 7.69004 6.19997 7.80005C6.30202 7.91645 6.44561 7.98824 6.59997 8.00005C6.75432 7.98824 6.89791 7.91645 6.99997 7.80005L9.60002 5.26841V6.99995C9.6021 7.15844 9.66598 7.30985 9.77805 7.42192ZM1.4 14H3.8C4.17066 13.9979 4.52553 13.8498 4.78763 13.5877C5.04973 13.3256 5.1979 12.9707 5.2 12.6V10.2C5.1979 9.82939 5.04973 9.47452 4.78763 9.21242C4.52553 8.95032 4.17066 8.80215 3.8 8.80005H1.4C1.02934 8.80215 0.674468 8.95032 0.412371 9.21242C0.150274 9.47452 0.00210008 9.82939 0 10.2V12.6C0.00210008 12.9707 0.150274 13.3256 0.412371 13.5877C0.674468 13.8498 1.02934 13.9979 1.4 14ZM1.25858 10.0586C1.29609 10.0211 1.34696 10 1.4 10H3.8C3.85304 10 3.90391 10.0211 3.94142 10.0586C3.97893 10.0961 4 10.147 4 10.2V12.6C4 12.6531 3.97893 12.704 3.94142 12.7415C3.90391 12.779 3.85304 12.8 3.8 12.8H1.4C1.34696 12.8 1.29609 12.779 1.25858 12.7415C1.22107 12.704 1.2 12.6531 1.2 12.6V10.2C1.2 10.147 1.22107 10.0961 1.25858 10.0586Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'WindowMinimizeIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M11.8 0H2.2C1.61652 0 1.05694 0.231785 0.644365 0.644365C0.231785 1.05694 0 1.61652 0 2.2V7C0 7.15913 0.063214 7.31174 0.175736 7.42426C0.288258 7.53679 0.44087 7.6 0.6 7.6C0.75913 7.6 0.911742 7.53679 1.02426 7.42426C1.13679 7.31174 1.2 7.15913 1.2 7V2.2C1.2 1.93478 1.30536 1.68043 1.49289 1.49289C1.68043 1.30536 1.93478 1.2 2.2 1.2H11.8C12.0652 1.2 12.3196 1.30536 12.5071 1.49289C12.6946 1.68043 12.8 1.93478 12.8 2.2V11.8C12.8 12.0652 12.6946 12.3196 12.5071 12.5071C12.3196 12.6946 12.0652 12.8 11.8 12.8H7C6.84087 12.8 6.68826 12.8632 6.57574 12.9757C6.46321 13.0883 6.4 13.2409 6.4 13.4C6.4 13.5591 6.46321 13.7117 6.57574 13.8243C6.68826 13.9368 6.84087 14 7 14H11.8C12.3835 14 12.9431 13.7682 13.3556 13.3556C13.7682 12.9431 14 12.3835 14 11.8V2.2C14 1.61652 13.7682 1.05694 13.3556 0.644365C12.9431 0.231785 12.3835 0 11.8 0ZM6.368 7.952C6.44137 7.98326 6.52025 7.99958 6.6 8H9.8C9.95913 8 10.1117 7.93678 10.2243 7.82426C10.3368 7.71174 10.4 7.55913 10.4 7.4C10.4 7.24087 10.3368 7.08826 10.2243 6.97574C10.1117 6.86321 9.95913 6.8 9.8 6.8H8.048L10.624 4.224C10.73 4.11026 10.7877 3.95982 10.7849 3.80438C10.7822 3.64894 10.7192 3.50063 10.6093 3.3907C10.4994 3.28077 10.3511 3.2178 10.1956 3.21506C10.0402 3.21232 9.88974 3.27002 9.776 3.376L7.2 5.952V4.2C7.2 4.04087 7.13679 3.88826 7.02426 3.77574C6.91174 3.66321 6.75913 3.6 6.6 3.6C6.44087 3.6 6.28826 3.66321 6.17574 3.77574C6.06321 3.88826 6 4.04087 6 4.2V7.4C6.00042 7.47975 6.01674 7.55862 6.048 7.632C6.07656 7.70442 6.11971 7.7702 6.17475 7.82524C6.2298 7.88029 6.29558 7.92344 6.368 7.952ZM1.4 8.80005H3.8C4.17066 8.80215 4.52553 8.95032 4.78763 9.21242C5.04973 9.47452 5.1979 9.82939 5.2 10.2V12.6C5.1979 12.9707 5.04973 13.3256 4.78763 13.5877C4.52553 13.8498 4.17066 13.9979 3.8 14H1.4C1.02934 13.9979 0.674468 13.8498 0.412371 13.5877C0.150274 13.3256 0.00210008 12.9707 0 12.6V10.2C0.00210008 9.82939 0.150274 9.47452 0.412371 9.21242C0.674468 8.95032 1.02934 8.80215 1.4 8.80005ZM3.94142 12.7415C3.97893 12.704 4 12.6531 4 12.6V10.2C4 10.147 3.97893 10.0961 3.94142 10.0586C3.90391 10.0211 3.85304 10 3.8 10H1.4C1.34696 10 1.29609 10.0211 1.25858 10.0586C1.22107 10.0961 1.2 10.147 1.2 10.2V12.6C1.2 12.6531 1.22107 12.704 1.25858 12.7415C1.29609 12.779 1.34696 12.8 1.4 12.8H3.8C3.85304 12.8 3.90391 12.779 3.94142 12.7415Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar FocusTrapStyle = BaseStyle.extend({\n name: 'focustrap-directive'\n});\n\nexport { FocusTrapStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { focus, getFirstFocusableElement, getLastFocusableElement, isFocusableElement, createElement } from '@primeuix/utils/dom';\nimport { isNotEmpty } from '@primeuix/utils/object';\nimport BaseDirective from '@primevue/core/basedirective';\nimport FocusTrapStyle from 'primevue/focustrap/style';\n\nvar BaseFocusTrap = BaseDirective.extend({\n style: FocusTrapStyle\n});\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar FocusTrap = BaseFocusTrap.extend('focustrap', {\n mounted: function mounted(el, binding) {\n var _ref = binding.value || {},\n disabled = _ref.disabled;\n if (!disabled) {\n this.createHiddenFocusableElements(el, binding);\n this.bind(el, binding);\n this.autoElementFocus(el, binding);\n }\n el.setAttribute('data-pd-focustrap', true);\n this.$el = el;\n },\n updated: function updated(el, binding) {\n var _ref2 = binding.value || {},\n disabled = _ref2.disabled;\n disabled && this.unbind(el);\n },\n unmounted: function unmounted(el) {\n this.unbind(el);\n },\n methods: {\n getComputedSelector: function getComputedSelector(selector) {\n return \":not(.p-hidden-focusable):not([data-p-hidden-focusable=\\\"true\\\"])\".concat(selector !== null && selector !== void 0 ? selector : '');\n },\n bind: function bind(el, binding) {\n var _this = this;\n var _ref3 = binding.value || {},\n onFocusIn = _ref3.onFocusIn,\n onFocusOut = _ref3.onFocusOut;\n el.$_pfocustrap_mutationobserver = new MutationObserver(function (mutationList) {\n mutationList.forEach(function (mutation) {\n if (mutation.type === 'childList' && !el.contains(document.activeElement)) {\n var findNextFocusableElement = function findNextFocusableElement(_el) {\n var focusableElement = isFocusableElement(_el) ? isFocusableElement(_el, _this.getComputedSelector(el.$_pfocustrap_focusableselector)) ? _el : getFirstFocusableElement(el, _this.getComputedSelector(el.$_pfocustrap_focusableselector)) : getFirstFocusableElement(_el);\n return isNotEmpty(focusableElement) ? focusableElement : _el.nextSibling && findNextFocusableElement(_el.nextSibling);\n };\n focus(findNextFocusableElement(mutation.nextSibling));\n }\n });\n });\n el.$_pfocustrap_mutationobserver.disconnect();\n el.$_pfocustrap_mutationobserver.observe(el, {\n childList: true\n });\n el.$_pfocustrap_focusinlistener = function (event) {\n return onFocusIn && onFocusIn(event);\n };\n el.$_pfocustrap_focusoutlistener = function (event) {\n return onFocusOut && onFocusOut(event);\n };\n el.addEventListener('focusin', el.$_pfocustrap_focusinlistener);\n el.addEventListener('focusout', el.$_pfocustrap_focusoutlistener);\n },\n unbind: function unbind(el) {\n el.$_pfocustrap_mutationobserver && el.$_pfocustrap_mutationobserver.disconnect();\n el.$_pfocustrap_focusinlistener && el.removeEventListener('focusin', el.$_pfocustrap_focusinlistener) && (el.$_pfocustrap_focusinlistener = null);\n el.$_pfocustrap_focusoutlistener && el.removeEventListener('focusout', el.$_pfocustrap_focusoutlistener) && (el.$_pfocustrap_focusoutlistener = null);\n },\n autoFocus: function autoFocus(options) {\n this.autoElementFocus(this.$el, {\n value: _objectSpread(_objectSpread({}, options), {}, {\n autoFocus: true\n })\n });\n },\n autoElementFocus: function autoElementFocus(el, binding) {\n var _ref4 = binding.value || {},\n _ref4$autoFocusSelect = _ref4.autoFocusSelector,\n autoFocusSelector = _ref4$autoFocusSelect === void 0 ? '' : _ref4$autoFocusSelect,\n _ref4$firstFocusableS = _ref4.firstFocusableSelector,\n firstFocusableSelector = _ref4$firstFocusableS === void 0 ? '' : _ref4$firstFocusableS,\n _ref4$autoFocus = _ref4.autoFocus,\n autoFocus = _ref4$autoFocus === void 0 ? false : _ref4$autoFocus;\n var focusableElement = getFirstFocusableElement(el, \"[autofocus]\".concat(this.getComputedSelector(autoFocusSelector)));\n autoFocus && !focusableElement && (focusableElement = getFirstFocusableElement(el, this.getComputedSelector(firstFocusableSelector)));\n focus(focusableElement);\n },\n onFirstHiddenElementFocus: function onFirstHiddenElementFocus(event) {\n var _this$$el;\n var currentTarget = event.currentTarget,\n relatedTarget = event.relatedTarget;\n var focusableElement = relatedTarget === currentTarget.$_pfocustrap_lasthiddenfocusableelement || !((_this$$el = this.$el) !== null && _this$$el !== void 0 && _this$$el.contains(relatedTarget)) ? getFirstFocusableElement(currentTarget.parentElement, this.getComputedSelector(currentTarget.$_pfocustrap_focusableselector)) : currentTarget.$_pfocustrap_lasthiddenfocusableelement;\n focus(focusableElement);\n },\n onLastHiddenElementFocus: function onLastHiddenElementFocus(event) {\n var _this$$el2;\n var currentTarget = event.currentTarget,\n relatedTarget = event.relatedTarget;\n var focusableElement = relatedTarget === currentTarget.$_pfocustrap_firsthiddenfocusableelement || !((_this$$el2 = this.$el) !== null && _this$$el2 !== void 0 && _this$$el2.contains(relatedTarget)) ? getLastFocusableElement(currentTarget.parentElement, this.getComputedSelector(currentTarget.$_pfocustrap_focusableselector)) : currentTarget.$_pfocustrap_firsthiddenfocusableelement;\n focus(focusableElement);\n },\n createHiddenFocusableElements: function createHiddenFocusableElements(el, binding) {\n var _this2 = this;\n var _ref5 = binding.value || {},\n _ref5$tabIndex = _ref5.tabIndex,\n tabIndex = _ref5$tabIndex === void 0 ? 0 : _ref5$tabIndex,\n _ref5$firstFocusableS = _ref5.firstFocusableSelector,\n firstFocusableSelector = _ref5$firstFocusableS === void 0 ? '' : _ref5$firstFocusableS,\n _ref5$lastFocusableSe = _ref5.lastFocusableSelector,\n lastFocusableSelector = _ref5$lastFocusableSe === void 0 ? '' : _ref5$lastFocusableSe;\n var createFocusableElement = function createFocusableElement(onFocus) {\n return createElement('span', {\n \"class\": 'p-hidden-accessible p-hidden-focusable',\n tabIndex: tabIndex,\n role: 'presentation',\n 'aria-hidden': true,\n 'data-p-hidden-accessible': true,\n 'data-p-hidden-focusable': true,\n onFocus: onFocus === null || onFocus === void 0 ? void 0 : onFocus.bind(_this2)\n });\n };\n var firstFocusableElement = createFocusableElement(this.onFirstHiddenElementFocus);\n var lastFocusableElement = createFocusableElement(this.onLastHiddenElementFocus);\n firstFocusableElement.$_pfocustrap_lasthiddenfocusableelement = lastFocusableElement;\n firstFocusableElement.$_pfocustrap_focusableselector = firstFocusableSelector;\n firstFocusableElement.setAttribute('data-pc-section', 'firstfocusableelement');\n lastFocusableElement.$_pfocustrap_firsthiddenfocusableelement = firstFocusableElement;\n lastFocusableElement.$_pfocustrap_focusableselector = lastFocusableSelector;\n lastFocusableElement.setAttribute('data-pc-section', 'lastfocusableelement');\n el.prepend(firstFocusableElement);\n el.append(lastFocusableElement);\n }\n }\n});\n\nexport { FocusTrap as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-dialog {\\n max-height: 90%;\\n transform: scale(1);\\n border-radius: \".concat(dt('dialog.border.radius'), \";\\n box-shadow: \").concat(dt('dialog.shadow'), \";\\n background: \").concat(dt('dialog.background'), \";\\n border: 1px solid \").concat(dt('dialog.border.color'), \";\\n color: \").concat(dt('dialog.color'), \";\\n}\\n\\n.p-dialog-content {\\n overflow-y: auto;\\n padding: \").concat(dt('dialog.content.padding'), \";\\n}\\n\\n.p-dialog-header {\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n flex-shrink: 0;\\n padding: \").concat(dt('dialog.header.padding'), \";\\n}\\n\\n.p-dialog-title {\\n font-weight: \").concat(dt('dialog.title.font.weight'), \";\\n font-size: \").concat(dt('dialog.title.font.size'), \";\\n}\\n\\n.p-dialog-footer {\\n flex-shrink: 0;\\n padding: \").concat(dt('dialog.footer.padding'), \";\\n display: flex;\\n justify-content: flex-end;\\n gap: \").concat(dt('dialog.footer.gap'), \";\\n}\\n\\n.p-dialog-header-actions {\\n display: flex;\\n align-items: center;\\n gap: \").concat(dt('dialog.header.gap'), \";\\n}\\n.p-dialog-enter-active {\\n transition: all 150ms cubic-bezier(0, 0, 0.2, 1);\\n}\\n\\n.p-dialog-leave-active {\\n transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);\\n}\\n\\n.p-dialog-enter-from,\\n.p-dialog-leave-to {\\n opacity: 0;\\n transform: scale(0.7);\\n}\\n\\n.p-dialog-top .p-dialog,\\n.p-dialog-bottom .p-dialog,\\n.p-dialog-left .p-dialog,\\n.p-dialog-right .p-dialog,\\n.p-dialog-topleft .p-dialog,\\n.p-dialog-topright .p-dialog,\\n.p-dialog-bottomleft .p-dialog,\\n.p-dialog-bottomright .p-dialog {\\n margin: 0.75rem;\\n transform: translate3d(0px, 0px, 0px);\\n}\\n\\n.p-dialog-top .p-dialog-enter-active,\\n.p-dialog-top .p-dialog-leave-active,\\n.p-dialog-bottom .p-dialog-enter-active,\\n.p-dialog-bottom .p-dialog-leave-active,\\n.p-dialog-left .p-dialog-enter-active,\\n.p-dialog-left .p-dialog-leave-active,\\n.p-dialog-right .p-dialog-enter-active,\\n.p-dialog-right .p-dialog-leave-active,\\n.p-dialog-topleft .p-dialog-enter-active,\\n.p-dialog-topleft .p-dialog-leave-active,\\n.p-dialog-topright .p-dialog-enter-active,\\n.p-dialog-topright .p-dialog-leave-active,\\n.p-dialog-bottomleft .p-dialog-enter-active,\\n.p-dialog-bottomleft .p-dialog-leave-active,\\n.p-dialog-bottomright .p-dialog-enter-active,\\n.p-dialog-bottomright .p-dialog-leave-active {\\n transition: all 0.3s ease-out;\\n}\\n\\n.p-dialog-top .p-dialog-enter-from,\\n.p-dialog-top .p-dialog-leave-to {\\n transform: translate3d(0px, -100%, 0px);\\n}\\n\\n.p-dialog-bottom .p-dialog-enter-from,\\n.p-dialog-bottom .p-dialog-leave-to {\\n transform: translate3d(0px, 100%, 0px);\\n}\\n\\n.p-dialog-left .p-dialog-enter-from,\\n.p-dialog-left .p-dialog-leave-to,\\n.p-dialog-topleft .p-dialog-enter-from,\\n.p-dialog-topleft .p-dialog-leave-to,\\n.p-dialog-bottomleft .p-dialog-enter-from,\\n.p-dialog-bottomleft .p-dialog-leave-to {\\n transform: translate3d(-100%, 0px, 0px);\\n}\\n\\n.p-dialog-right .p-dialog-enter-from,\\n.p-dialog-right .p-dialog-leave-to,\\n.p-dialog-topright .p-dialog-enter-from,\\n.p-dialog-topright .p-dialog-leave-to,\\n.p-dialog-bottomright .p-dialog-enter-from,\\n.p-dialog-bottomright .p-dialog-leave-to {\\n transform: translate3d(100%, 0px, 0px);\\n}\\n\\n.p-dialog-maximized {\\n width: 100vw !important;\\n height: 100vh !important;\\n top: 0px !important;\\n left: 0px !important;\\n max-height: 100%;\\n height: 100%;\\n border-radius: 0;\\n}\\n\\n.p-dialog-maximized .p-dialog-content {\\n flex-grow: 1;\\n}\\n\");\n};\n\n/* Position */\nvar inlineStyles = {\n mask: function mask(_ref2) {\n var position = _ref2.position,\n modal = _ref2.modal;\n return {\n position: 'fixed',\n height: '100%',\n width: '100%',\n left: 0,\n top: 0,\n display: 'flex',\n justifyContent: position === 'left' || position === 'topleft' || position === 'bottomleft' ? 'flex-start' : position === 'right' || position === 'topright' || position === 'bottomright' ? 'flex-end' : 'center',\n alignItems: position === 'top' || position === 'topleft' || position === 'topright' ? 'flex-start' : position === 'bottom' || position === 'bottomleft' || position === 'bottomright' ? 'flex-end' : 'center',\n pointerEvents: modal ? 'auto' : 'none'\n };\n },\n root: {\n display: 'flex',\n flexDirection: 'column',\n pointerEvents: 'auto'\n }\n};\nvar classes = {\n mask: function mask(_ref3) {\n var props = _ref3.props;\n var positions = ['left', 'right', 'top', 'topleft', 'topright', 'bottom', 'bottomleft', 'bottomright'];\n var pos = positions.find(function (item) {\n return item === props.position;\n });\n return ['p-dialog-mask', {\n 'p-overlay-mask p-overlay-mask-enter': props.modal\n }, pos ? \"p-dialog-\".concat(pos) : ''];\n },\n root: function root(_ref4) {\n var props = _ref4.props,\n instance = _ref4.instance;\n return ['p-dialog p-component', {\n 'p-dialog-maximized': props.maximizable && instance.maximized\n }];\n },\n header: 'p-dialog-header',\n title: 'p-dialog-title',\n headerActions: 'p-dialog-header-actions',\n pcMaximizeButton: 'p-dialog-maximize-button',\n pcCloseButton: 'p-dialog-close-button',\n content: 'p-dialog-content',\n footer: 'p-dialog-footer'\n};\nvar DialogStyle = BaseStyle.extend({\n name: 'dialog',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { DialogStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { addClass, focus, blockBodyScroll, unblockBodyScroll, setAttribute, addStyle, getOuterWidth, getOuterHeight, getViewport } from '@primeuix/utils/dom';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport TimesIcon from '@primevue/icons/times';\nimport WindowMaximizeIcon from '@primevue/icons/windowmaximize';\nimport WindowMinimizeIcon from '@primevue/icons/windowminimize';\nimport Button from 'primevue/button';\nimport FocusTrap from 'primevue/focustrap';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport { computed, resolveComponent, resolveDirective, openBlock, createBlock, withCtx, createElementBlock, mergeProps, createVNode, Transition, withDirectives, renderSlot, Fragment, normalizeClass, toDisplayString, createCommentVNode, createElementVNode, resolveDynamicComponent, createTextVNode } from 'vue';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport DialogStyle from 'primevue/dialog/style';\n\nvar script$1 = {\n name: 'BaseDialog',\n \"extends\": BaseComponent,\n props: {\n header: {\n type: null,\n \"default\": null\n },\n footer: {\n type: null,\n \"default\": null\n },\n visible: {\n type: Boolean,\n \"default\": false\n },\n modal: {\n type: Boolean,\n \"default\": null\n },\n contentStyle: {\n type: null,\n \"default\": null\n },\n contentClass: {\n type: String,\n \"default\": null\n },\n contentProps: {\n type: null,\n \"default\": null\n },\n maximizable: {\n type: Boolean,\n \"default\": false\n },\n dismissableMask: {\n type: Boolean,\n \"default\": false\n },\n closable: {\n type: Boolean,\n \"default\": true\n },\n closeOnEscape: {\n type: Boolean,\n \"default\": true\n },\n showHeader: {\n type: Boolean,\n \"default\": true\n },\n blockScroll: {\n type: Boolean,\n \"default\": false\n },\n baseZIndex: {\n type: Number,\n \"default\": 0\n },\n autoZIndex: {\n type: Boolean,\n \"default\": true\n },\n position: {\n type: String,\n \"default\": 'center'\n },\n breakpoints: {\n type: Object,\n \"default\": null\n },\n draggable: {\n type: Boolean,\n \"default\": true\n },\n keepInViewport: {\n type: Boolean,\n \"default\": true\n },\n minX: {\n type: Number,\n \"default\": 0\n },\n minY: {\n type: Number,\n \"default\": 0\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n closeIcon: {\n type: String,\n \"default\": undefined\n },\n maximizeIcon: {\n type: String,\n \"default\": undefined\n },\n minimizeIcon: {\n type: String,\n \"default\": undefined\n },\n closeButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n severity: 'secondary',\n text: true,\n rounded: true\n };\n }\n },\n maximizeButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n severity: 'secondary',\n text: true,\n rounded: true\n };\n }\n },\n _instance: null\n },\n style: DialogStyle,\n provide: function provide() {\n return {\n $pcDialog: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Dialog',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:visible', 'show', 'hide', 'after-hide', 'maximize', 'unmaximize', 'dragend'],\n provide: function provide() {\n var _this = this;\n return {\n dialogRef: computed(function () {\n return _this._instance;\n })\n };\n },\n data: function data() {\n return {\n id: this.$attrs.id,\n containerVisible: this.visible,\n maximized: false,\n focusableMax: null,\n focusableClose: null\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n }\n },\n documentKeydownListener: null,\n container: null,\n mask: null,\n content: null,\n headerContainer: null,\n footerContainer: null,\n maximizableButton: null,\n closeButton: null,\n styleElement: null,\n dragging: null,\n documentDragListener: null,\n documentDragEndListener: null,\n lastPageX: null,\n lastPageY: null,\n updated: function updated() {\n if (this.visible) {\n this.containerVisible = this.visible;\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindDocumentState();\n this.unbindGlobalListeners();\n this.destroyStyle();\n if (this.mask && this.autoZIndex) {\n ZIndex.clear(this.mask);\n }\n this.container = null;\n this.mask = null;\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n if (this.breakpoints) {\n this.createStyle();\n }\n },\n methods: {\n close: function close() {\n this.$emit('update:visible', false);\n },\n onBeforeEnter: function onBeforeEnter(el) {\n el.setAttribute(this.attributeSelector, '');\n },\n onEnter: function onEnter() {\n this.$emit('show');\n this.focus();\n this.enableDocumentSettings();\n this.bindGlobalListeners();\n if (this.autoZIndex) {\n ZIndex.set('modal', this.mask, this.baseZIndex + this.$primevue.config.zIndex.modal);\n }\n },\n onBeforeLeave: function onBeforeLeave() {\n if (this.modal) {\n !this.isUnstyled && addClass(this.mask, 'p-overlay-mask-leave');\n }\n },\n onLeave: function onLeave() {\n this.$emit('hide');\n this.focusableClose = null;\n this.focusableMax = null;\n },\n onAfterLeave: function onAfterLeave() {\n if (this.autoZIndex) {\n ZIndex.clear(this.mask);\n }\n this.containerVisible = false;\n this.unbindDocumentState();\n this.unbindGlobalListeners();\n this.$emit('after-hide');\n },\n onMaskClick: function onMaskClick(event) {\n if (this.dismissableMask && this.modal && this.mask === event.target) {\n this.close();\n }\n },\n focus: function focus$1() {\n var findFocusableElement = function findFocusableElement(container) {\n return container && container.querySelector('[autofocus]');\n };\n var focusTarget = this.$slots.footer && findFocusableElement(this.footerContainer);\n if (!focusTarget) {\n focusTarget = this.$slots.header && findFocusableElement(this.headerContainer);\n if (!focusTarget) {\n focusTarget = this.$slots[\"default\"] && findFocusableElement(this.content);\n if (!focusTarget) {\n if (this.maximizable) {\n this.focusableMax = true;\n focusTarget = this.maximizableButton;\n } else {\n this.focusableClose = true;\n focusTarget = this.closeButton;\n }\n }\n }\n }\n if (focusTarget) {\n focus(focusTarget, {\n focusVisible: true\n });\n }\n },\n maximize: function maximize(event) {\n if (this.maximized) {\n this.maximized = false;\n this.$emit('unmaximize', event);\n } else {\n this.maximized = true;\n this.$emit('maximize', event);\n }\n if (!this.modal) {\n this.maximized ? blockBodyScroll() : unblockBodyScroll();\n }\n },\n enableDocumentSettings: function enableDocumentSettings() {\n if (this.modal || !this.modal && this.blockScroll || this.maximizable && this.maximized) {\n blockBodyScroll();\n }\n },\n unbindDocumentState: function unbindDocumentState() {\n if (this.modal || !this.modal && this.blockScroll || this.maximizable && this.maximized) {\n unblockBodyScroll();\n }\n },\n onKeyDown: function onKeyDown(event) {\n if (event.code === 'Escape' && this.closeOnEscape) {\n this.close();\n }\n },\n bindDocumentKeyDownListener: function bindDocumentKeyDownListener() {\n if (!this.documentKeydownListener) {\n this.documentKeydownListener = this.onKeyDown.bind(this);\n window.document.addEventListener('keydown', this.documentKeydownListener);\n }\n },\n unbindDocumentKeyDownListener: function unbindDocumentKeyDownListener() {\n if (this.documentKeydownListener) {\n window.document.removeEventListener('keydown', this.documentKeydownListener);\n this.documentKeydownListener = null;\n }\n },\n containerRef: function containerRef(el) {\n this.container = el;\n },\n maskRef: function maskRef(el) {\n this.mask = el;\n },\n contentRef: function contentRef(el) {\n this.content = el;\n },\n headerContainerRef: function headerContainerRef(el) {\n this.headerContainer = el;\n },\n footerContainerRef: function footerContainerRef(el) {\n this.footerContainer = el;\n },\n maximizableRef: function maximizableRef(el) {\n this.maximizableButton = el ? el.$el : undefined;\n },\n closeButtonRef: function closeButtonRef(el) {\n this.closeButton = el ? el.$el : undefined;\n },\n createStyle: function createStyle() {\n if (!this.styleElement && !this.isUnstyled) {\n var _this$$primevue;\n this.styleElement = document.createElement('style');\n this.styleElement.type = 'text/css';\n setAttribute(this.styleElement, 'nonce', (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.csp) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.nonce);\n document.head.appendChild(this.styleElement);\n var innerHTML = '';\n for (var breakpoint in this.breakpoints) {\n innerHTML += \"\\n @media screen and (max-width: \".concat(breakpoint, \") {\\n .p-dialog[\").concat(this.attributeSelector, \"] {\\n width: \").concat(this.breakpoints[breakpoint], \" !important;\\n }\\n }\\n \");\n }\n this.styleElement.innerHTML = innerHTML;\n }\n },\n destroyStyle: function destroyStyle() {\n if (this.styleElement) {\n document.head.removeChild(this.styleElement);\n this.styleElement = null;\n }\n },\n initDrag: function initDrag(event) {\n if (event.target.closest('div').getAttribute('data-pc-section') === 'headeractions') {\n return;\n }\n if (this.draggable) {\n this.dragging = true;\n this.lastPageX = event.pageX;\n this.lastPageY = event.pageY;\n this.container.style.margin = '0';\n document.body.setAttribute('data-p-unselectable-text', 'true');\n !this.isUnstyled && addStyle(document.body, {\n 'user-select': 'none'\n });\n }\n },\n bindGlobalListeners: function bindGlobalListeners() {\n if (this.draggable) {\n this.bindDocumentDragListener();\n this.bindDocumentDragEndListener();\n }\n if (this.closeOnEscape && this.closable) {\n this.bindDocumentKeyDownListener();\n }\n },\n unbindGlobalListeners: function unbindGlobalListeners() {\n this.unbindDocumentDragListener();\n this.unbindDocumentDragEndListener();\n this.unbindDocumentKeyDownListener();\n },\n bindDocumentDragListener: function bindDocumentDragListener() {\n var _this2 = this;\n this.documentDragListener = function (event) {\n if (_this2.dragging) {\n var width = getOuterWidth(_this2.container);\n var height = getOuterHeight(_this2.container);\n var deltaX = event.pageX - _this2.lastPageX;\n var deltaY = event.pageY - _this2.lastPageY;\n var offset = _this2.container.getBoundingClientRect();\n var leftPos = offset.left + deltaX;\n var topPos = offset.top + deltaY;\n var viewport = getViewport();\n var containerComputedStyle = getComputedStyle(_this2.container);\n var marginLeft = parseFloat(containerComputedStyle.marginLeft);\n var marginTop = parseFloat(containerComputedStyle.marginTop);\n _this2.container.style.position = 'fixed';\n if (_this2.keepInViewport) {\n if (leftPos >= _this2.minX && leftPos + width < viewport.width) {\n _this2.lastPageX = event.pageX;\n _this2.container.style.left = leftPos - marginLeft + 'px';\n }\n if (topPos >= _this2.minY && topPos + height < viewport.height) {\n _this2.lastPageY = event.pageY;\n _this2.container.style.top = topPos - marginTop + 'px';\n }\n } else {\n _this2.lastPageX = event.pageX;\n _this2.container.style.left = leftPos - marginLeft + 'px';\n _this2.lastPageY = event.pageY;\n _this2.container.style.top = topPos - marginTop + 'px';\n }\n }\n };\n window.document.addEventListener('mousemove', this.documentDragListener);\n },\n unbindDocumentDragListener: function unbindDocumentDragListener() {\n if (this.documentDragListener) {\n window.document.removeEventListener('mousemove', this.documentDragListener);\n this.documentDragListener = null;\n }\n },\n bindDocumentDragEndListener: function bindDocumentDragEndListener() {\n var _this3 = this;\n this.documentDragEndListener = function (event) {\n if (_this3.dragging) {\n _this3.dragging = false;\n document.body.removeAttribute('data-p-unselectable-text');\n !_this3.isUnstyled && (document.body.style['user-select'] = '');\n _this3.$emit('dragend', event);\n }\n };\n window.document.addEventListener('mouseup', this.documentDragEndListener);\n },\n unbindDocumentDragEndListener: function unbindDocumentDragEndListener() {\n if (this.documentDragEndListener) {\n window.document.removeEventListener('mouseup', this.documentDragEndListener);\n this.documentDragEndListener = null;\n }\n }\n },\n computed: {\n maximizeIconComponent: function maximizeIconComponent() {\n return this.maximized ? this.minimizeIcon ? 'span' : 'WindowMinimizeIcon' : this.maximizeIcon ? 'span' : 'WindowMaximizeIcon';\n },\n ariaLabelledById: function ariaLabelledById() {\n return this.header != null || this.$attrs['aria-labelledby'] !== null ? this.id + '_header' : null;\n },\n closeAriaLabel: function closeAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.close : undefined;\n },\n attributeSelector: function attributeSelector() {\n return UniqueComponentId();\n }\n },\n directives: {\n ripple: Ripple,\n focustrap: FocusTrap\n },\n components: {\n Button: Button,\n Portal: Portal,\n WindowMinimizeIcon: WindowMinimizeIcon,\n WindowMaximizeIcon: WindowMaximizeIcon,\n TimesIcon: TimesIcon\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"aria-labelledby\", \"aria-modal\"];\nvar _hoisted_2 = [\"id\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Button = resolveComponent(\"Button\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_focustrap = resolveDirective(\"focustrap\");\n return openBlock(), createBlock(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [$data.containerVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.maskRef,\n \"class\": _ctx.cx('mask'),\n style: _ctx.sx('mask', true, {\n position: _ctx.position,\n modal: _ctx.modal\n }),\n onClick: _cache[1] || (_cache[1] = function () {\n return $options.onMaskClick && $options.onMaskClick.apply($options, arguments);\n })\n }, _ctx.ptm('mask')), [createVNode(Transition, mergeProps({\n name: \"p-dialog\",\n onBeforeEnter: $options.onBeforeEnter,\n onEnter: $options.onEnter,\n onBeforeLeave: $options.onBeforeLeave,\n onLeave: $options.onLeave,\n onAfterLeave: $options.onAfterLeave,\n appear: \"\"\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [_ctx.visible ? withDirectives((openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.containerRef,\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n role: \"dialog\",\n \"aria-labelledby\": $options.ariaLabelledById,\n \"aria-modal\": _ctx.modal\n }, _ctx.ptmi('root')), [_ctx.$slots.container ? renderSlot(_ctx.$slots, \"container\", {\n key: 0,\n closeCallback: $options.close,\n maximizeCallback: function maximizeCallback(event) {\n return $options.maximize(event);\n }\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [_ctx.showHeader ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.headerContainerRef,\n \"class\": _ctx.cx('header'),\n onMousedown: _cache[0] || (_cache[0] = function () {\n return $options.initDrag && $options.initDrag.apply($options, arguments);\n })\n }, _ctx.ptm('header')), [renderSlot(_ctx.$slots, \"header\", {\n \"class\": normalizeClass(_ctx.cx('title'))\n }, function () {\n return [_ctx.header ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n id: $options.ariaLabelledById,\n \"class\": _ctx.cx('title')\n }, _ctx.ptm('title')), toDisplayString(_ctx.header), 17, _hoisted_2)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('headerActions')\n }, _ctx.ptm('headerActions')), [_ctx.maximizable ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 0,\n ref: $options.maximizableRef,\n autofocus: $data.focusableMax,\n \"class\": _ctx.cx('pcMaximizeButton'),\n onClick: $options.maximize,\n tabindex: _ctx.maximizable ? '0' : '-1',\n unstyled: _ctx.unstyled\n }, _ctx.maximizeButtonProps, {\n pt: _ctx.ptm('pcMaximizeButton'),\n \"data-pc-group-section\": \"headericon\"\n }), {\n icon: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"maximizeicon\", {\n maximized: $data.maximized\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent($options.maximizeIconComponent), mergeProps({\n \"class\": [slotProps[\"class\"], $data.maximized ? _ctx.minimizeIcon : _ctx.maximizeIcon]\n }, _ctx.ptm('pcMaximizeButton')['icon']), null, 16, [\"class\"]))];\n })];\n }),\n _: 3\n }, 16, [\"autofocus\", \"class\", \"onClick\", \"tabindex\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), _ctx.closable ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 1,\n ref: $options.closeButtonRef,\n autofocus: $data.focusableClose,\n \"class\": _ctx.cx('pcCloseButton'),\n onClick: $options.close,\n \"aria-label\": $options.closeAriaLabel,\n unstyled: _ctx.unstyled\n }, _ctx.closeButtonProps, {\n pt: _ctx.ptm('pcCloseButton'),\n \"data-pc-group-section\": \"headericon\"\n }), {\n icon: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"closeicon\", {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.closeIcon ? 'span' : 'TimesIcon'), mergeProps({\n \"class\": [_ctx.closeIcon, slotProps[\"class\"]]\n }, _ctx.ptm('pcCloseButton')['icon']), null, 16, [\"class\"]))];\n })];\n }),\n _: 3\n }, 16, [\"autofocus\", \"class\", \"onClick\", \"aria-label\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 16)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n ref: $options.contentRef,\n \"class\": [_ctx.cx('content'), _ctx.contentClass],\n style: _ctx.contentStyle\n }, _objectSpread(_objectSpread({}, _ctx.contentProps), _ctx.ptm('content'))), [renderSlot(_ctx.$slots, \"default\")], 16), _ctx.footer || _ctx.$slots.footer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n ref: $options.footerContainerRef,\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [renderSlot(_ctx.$slots, \"footer\", {}, function () {\n return [createTextVNode(toDisplayString(_ctx.footer), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 64))], 16, _hoisted_1)), [[_directive_focustrap, {\n disabled: !_ctx.modal\n }]]) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onBeforeEnter\", \"onEnter\", \"onBeforeLeave\", \"onLeave\", \"onAfterLeave\"])], 16)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 8, [\"appendTo\"]);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-togglebutton {\\n display: inline-flex;\\n cursor: pointer;\\n user-select: none;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n color: \".concat(dt('togglebutton.color'), \";\\n background: \").concat(dt('togglebutton.background'), \";\\n border: 1px solid \").concat(dt('togglebutton.border.color'), \";\\n padding: \").concat(dt('togglebutton.padding'), \";\\n font-size: 1rem;\\n font-family: inherit;\\n font-feature-settings: inherit;\\n transition: background \").concat(dt('togglebutton.transition.duration'), \", color \").concat(dt('togglebutton.transition.duration'), \", border-color \").concat(dt('togglebutton.transition.duration'), \",\\n outline-color \").concat(dt('togglebutton.transition.duration'), \", box-shadow \").concat(dt('togglebutton.transition.duration'), \";\\n border-radius: \").concat(dt('togglebutton.border.radius'), \";\\n outline-color: transparent;\\n font-weight: \").concat(dt('togglebutton.font.weight'), \";\\n}\\n\\n.p-togglebutton-content {\\n position: relative;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: \").concat(dt('togglebutton.gap'), \";\\n}\\n\\n.p-togglebutton-label,\\n.p-togglebutton-icon {\\n position: relative;\\n transition: none;\\n}\\n\\n.p-togglebutton::before {\\n content: \\\"\\\";\\n background: transparent;\\n transition: background \").concat(dt('togglebutton.transition.duration'), \", color \").concat(dt('togglebutton.transition.duration'), \", border-color \").concat(dt('togglebutton.transition.duration'), \",\\n outline-color \").concat(dt('togglebutton.transition.duration'), \", box-shadow \").concat(dt('togglebutton.transition.duration'), \";\\n position: absolute;\\n left: \").concat(dt('togglebutton.content.left'), \";\\n top: \").concat(dt('togglebutton.content.top'), \";\\n width: calc(100% - calc(2 * \").concat(dt('togglebutton.content.left'), \"));\\n height: calc(100% - calc(2 * \").concat(dt('togglebutton.content.top'), \"));\\n border-radius: \").concat(dt('togglebutton.border.radius'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked::before {\\n background: \").concat(dt('togglebutton.content.checked.background'), \";\\n box-shadow: \").concat(dt('togglebutton.content.checked.shadow'), \";\\n}\\n\\n.p-togglebutton:not(:disabled):not(.p-togglebutton-checked):hover {\\n background: \").concat(dt('togglebutton.hover.background'), \";\\n color: \").concat(dt('togglebutton.hover.color'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked {\\n background: \").concat(dt('togglebutton.checked.background'), \";\\n border-color: \").concat(dt('togglebutton.checked.border.color'), \";\\n color: \").concat(dt('togglebutton.checked.color'), \";\\n}\\n\\n.p-togglebutton:focus-visible {\\n box-shadow: \").concat(dt('togglebutton.focus.ring.shadow'), \";\\n outline: \").concat(dt('togglebutton.focus.ring.width'), \" \").concat(dt('togglebutton.focus.ring.style'), \" \").concat(dt('togglebutton.focus.ring.color'), \";\\n outline-offset: \").concat(dt('togglebutton.focus.ring.offset'), \";\\n}\\n\\n.p-togglebutton.p-invalid {\\n border-color: \").concat(dt('togglebutton.invalid.border.color'), \";\\n}\\n\\n.p-togglebutton:disabled {\\n opacity: 1;\\n cursor: default;\\n background: \").concat(dt('togglebutton.disabled.background'), \";\\n border-color: \").concat(dt('togglebutton.disabled.border.color'), \";\\n color: \").concat(dt('togglebutton.disabled.color'), \";\\n}\\n\\n.p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.color'), \";\\n}\\n\\n.p-togglebutton:not(:disabled):not(.p-togglebutton-checked):hover .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.hover.color'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.checked.color'), \";\\n}\\n\\n.p-togglebutton:disabled .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.disabled.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-togglebutton p-component', {\n 'p-togglebutton-checked': instance.active,\n 'p-invalid': props.invalid\n }];\n },\n content: 'p-togglebutton-content',\n icon: 'p-togglebutton-icon',\n label: 'p-togglebutton-label'\n};\nvar ToggleButtonStyle = BaseStyle.extend({\n name: 'togglebutton',\n theme: theme,\n classes: classes\n});\n\nexport { ToggleButtonStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { isNotEmpty } from '@primeuix/utils/object';\nimport Ripple from 'primevue/ripple';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ToggleButtonStyle from 'primevue/togglebutton/style';\nimport { resolveDirective, withDirectives, openBlock, createElementBlock, mergeProps, createElementVNode, renderSlot, normalizeClass, createCommentVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseToggleButton',\n \"extends\": BaseComponent,\n props: {\n modelValue: Boolean,\n onIcon: String,\n offIcon: String,\n onLabel: {\n type: String,\n \"default\": 'Yes'\n },\n offLabel: {\n type: String,\n \"default\": 'No'\n },\n iconPos: {\n type: String,\n \"default\": 'left'\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: ToggleButtonStyle,\n provide: function provide() {\n return {\n $pcToggleButton: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ToggleButton',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n active: this.active,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n if (!this.disabled && !this.readonly) {\n this.$emit('update:modelValue', !this.modelValue);\n this.$emit('change', event);\n }\n }\n },\n computed: {\n active: function active() {\n return this.modelValue === true;\n },\n hasLabel: function hasLabel() {\n return isNotEmpty(this.onLabel) && isNotEmpty(this.offLabel);\n },\n label: function label() {\n return this.hasLabel ? this.modelValue ? this.onLabel : this.offLabel : ' ';\n }\n },\n directives: {\n ripple: Ripple\n }\n};\n\nvar _hoisted_1 = [\"tabindex\", \"disabled\", \"aria-pressed\", \"data-p-checked\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n type: \"button\",\n \"class\": _ctx.cx('root'),\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n \"aria-pressed\": _ctx.modelValue,\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.active,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('content')\n }, $options.getPTOptions('content')), [renderSlot(_ctx.$slots, \"default\", {}, function () {\n return [renderSlot(_ctx.$slots, \"icon\", {\n value: _ctx.modelValue,\n \"class\": normalizeClass(_ctx.cx('icon'))\n }, function () {\n return [_ctx.onIcon || _ctx.offIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('icon'), _ctx.modelValue ? _ctx.onIcon : _ctx.offIcon]\n }, $options.getPTOptions('icon')), null, 16)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('label')\n }, $options.getPTOptions('label')), toDisplayString($options.label), 17)];\n })], 16)], 16, _hoisted_1)), [[_directive_ripple]]);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-selectbutton {\\n display: inline-flex;\\n user-select: none;\\n vertical-align: bottom;\\n outline-color: transparent;\\n border-radius: \".concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton .p-togglebutton {\\n border-radius: 0;\\n border-width: 1px 1px 1px 0;\\n}\\n\\n.p-selectbutton .p-togglebutton:focus-visible {\\n position: relative;\\n z-index: 1;\\n}\\n\\n.p-selectbutton .p-togglebutton:first-child {\\n border-left-width: 1px;\\n border-top-left-radius: \").concat(dt('selectbutton.border.radius'), \";\\n border-bottom-left-radius: \").concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton .p-togglebutton:last-child {\\n border-top-right-radius: \").concat(dt('selectbutton.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton.p-invalid {\\n outline: 1px solid \").concat(dt('selectbutton.invalid.border.color'), \";\\n outline-offset: 0;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-selectbutton p-component', {\n 'p-invalid': props.invalid\n }];\n }\n};\nvar SelectButtonStyle = BaseStyle.extend({\n name: 'selectbutton',\n theme: theme,\n classes: classes\n});\n\nexport { SelectButtonStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { resolveFieldData, equals } from '@primeuix/utils/object';\nimport Ripple from 'primevue/ripple';\nimport ToggleButton from 'primevue/togglebutton';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SelectButtonStyle from 'primevue/selectbutton/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, Fragment, renderList, createBlock, createSlots, withCtx, renderSlot, createElementVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseSelectButton',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n options: Array,\n optionLabel: null,\n optionValue: null,\n optionDisabled: null,\n multiple: Boolean,\n allowEmpty: {\n type: Boolean,\n \"default\": true\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: Boolean,\n dataKey: null,\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: SelectButtonStyle,\n provide: function provide() {\n return {\n $pcSelectButton: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _createForOfIteratorHelper(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'SelectButton',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change'],\n methods: {\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return this.optionValue ? resolveFieldData(option, this.optionValue) : option;\n },\n getOptionRenderKey: function getOptionRenderKey(option) {\n return this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option);\n },\n getPTOptions: function getPTOptions(option, key) {\n return this.ptm(key, {\n context: {\n active: this.isSelected(option),\n disabled: this.isOptionDisabled(option),\n option: option\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n onOptionSelect: function onOptionSelect(event, option, index) {\n var _this = this;\n if (this.disabled || this.isOptionDisabled(option)) {\n return;\n }\n var selected = this.isSelected(option);\n if (selected && !this.allowEmpty) {\n return;\n }\n var optionValue = this.getOptionValue(option);\n var newValue;\n if (this.multiple) {\n if (selected) newValue = this.modelValue.filter(function (val) {\n return !equals(val, optionValue, _this.equalityKey);\n });else newValue = this.modelValue ? [].concat(_toConsumableArray(this.modelValue), [optionValue]) : [optionValue];\n } else {\n newValue = selected ? null : optionValue;\n }\n this.focusedIndex = index;\n this.$emit('update:modelValue', newValue);\n this.$emit('change', {\n event: event,\n value: newValue\n });\n },\n isSelected: function isSelected(option) {\n var selected = false;\n var optionValue = this.getOptionValue(option);\n if (this.multiple) {\n if (this.modelValue) {\n var _iterator = _createForOfIteratorHelper(this.modelValue),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var val = _step.value;\n if (equals(val, optionValue, this.equalityKey)) {\n selected = true;\n break;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n } else {\n selected = equals(this.modelValue, optionValue, this.equalityKey);\n }\n return selected;\n }\n },\n computed: {\n equalityKey: function equalityKey() {\n return this.optionValue ? null : this.dataKey;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n ToggleButton: ToggleButton\n }\n};\n\nvar _hoisted_1 = [\"aria-labelledby\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_ToggleButton = resolveComponent(\"ToggleButton\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"group\",\n \"aria-labelledby\": _ctx.ariaLabelledby\n }, _ctx.ptmi('root')), [(openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.options, function (option, index) {\n return openBlock(), createBlock(_component_ToggleButton, {\n key: $options.getOptionRenderKey(option),\n modelValue: $options.isSelected(option),\n onLabel: $options.getOptionLabel(option),\n offLabel: $options.getOptionLabel(option),\n disabled: _ctx.disabled || $options.isOptionDisabled(option),\n unstyled: _ctx.unstyled,\n onChange: function onChange($event) {\n return $options.onOptionSelect($event, option, index);\n },\n pt: _ctx.ptm('pcButton')\n }, createSlots({\n _: 2\n }, [_ctx.$slots.option ? {\n name: \"default\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"option\", {\n option: option,\n index: index\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n ref_for: true\n }, _ctx.ptm('pcButton')['label']), toDisplayString($options.getOptionLabel(option)), 17)];\n })];\n }),\n key: \"0\"\n } : undefined]), 1032, [\"modelValue\", \"onLabel\", \"offLabel\", \"disabled\", \"unstyled\", \"onChange\", \"pt\"]);\n }), 128))], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n\r\n\r\n\r\n","\r\n\r\n\r\n\r\n\r\n","\r\n\r\n\r\n\r\n\r\n\r\n\r\n","/*!\n * shared v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\n/**\n * Original Utilities\n * written by kazuya kawaguchi\n */\nconst inBrowser = typeof window !== 'undefined';\nlet mark;\nlet measure;\nif ((process.env.NODE_ENV !== 'production')) {\n const perf = inBrowser && window.performance;\n if (perf &&\n perf.mark &&\n perf.measure &&\n perf.clearMarks &&\n // @ts-ignore browser compat\n perf.clearMeasures) {\n mark = (tag) => {\n perf.mark(tag);\n };\n measure = (name, startTag, endTag) => {\n perf.measure(name, startTag, endTag);\n perf.clearMarks(startTag);\n perf.clearMarks(endTag);\n };\n }\n}\nconst RE_ARGS = /\\{([0-9a-zA-Z]+)\\}/g;\n/* eslint-disable */\nfunction format(message, ...args) {\n if (args.length === 1 && isObject(args[0])) {\n args = args[0];\n }\n if (!args || !args.hasOwnProperty) {\n args = {};\n }\n return message.replace(RE_ARGS, (match, identifier) => {\n return args.hasOwnProperty(identifier) ? args[identifier] : '';\n });\n}\nconst makeSymbol = (name, shareable = false) => !shareable ? Symbol(name) : Symbol.for(name);\nconst generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });\nconst friendlyJSONstringify = (json) => JSON.stringify(json)\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n .replace(/\\u0027/g, '\\\\u0027');\nconst isNumber = (val) => typeof val === 'number' && isFinite(val);\nconst isDate = (val) => toTypeString(val) === '[object Date]';\nconst isRegExp = (val) => toTypeString(val) === '[object RegExp]';\nconst isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;\nconst assign = Object.assign;\nlet _globalThis;\nconst getGlobalThis = () => {\n // prettier-ignore\n return (_globalThis ||\n (_globalThis =\n typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {}));\n};\nfunction escapeHtml(rawText) {\n return rawText\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwn(obj, key) {\n return hasOwnProperty.call(obj, key);\n}\n/* eslint-enable */\n/**\n * Useful Utilities By Evan you\n * Modified by kazuya kawaguchi\n * MIT License\n * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts\n * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts\n */\nconst isArray = Array.isArray;\nconst isFunction = (val) => typeof val === 'function';\nconst isString = (val) => typeof val === 'string';\nconst isBoolean = (val) => typeof val === 'boolean';\nconst isSymbol = (val) => typeof val === 'symbol';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObject = (val) => val !== null && typeof val === 'object';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPromise = (val) => {\n return isObject(val) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst isPlainObject = (val) => {\n if (!isObject(val))\n return false;\n const proto = Object.getPrototypeOf(val);\n return proto === null || proto.constructor === Object;\n};\n// for converting list and named values to displayed strings.\nconst toDisplayString = (val) => {\n return val == null\n ? ''\n : isArray(val) || (isPlainObject(val) && val.toString === objectToString)\n ? JSON.stringify(val, null, 2)\n : String(val);\n};\nfunction join(items, separator = '') {\n return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');\n}\nconst RANGE = 2;\nfunction generateCodeFrame(source, start = 0, end = source.length) {\n const lines = source.split(/\\r?\\n/);\n let count = 0;\n const res = [];\n for (let i = 0; i < lines.length; i++) {\n count += lines[i].length + 1;\n if (count >= start) {\n for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {\n if (j < 0 || j >= lines.length)\n continue;\n const line = j + 1;\n res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);\n const lineLength = lines[j].length;\n if (j === i) {\n // push underline\n const pad = start - (count - lineLength) + 1;\n const length = Math.max(1, end > count ? lineLength - pad : end - start);\n res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));\n }\n else if (j > i) {\n if (end > count) {\n const length = Math.max(Math.min(end - count, lineLength), 1);\n res.push(` | ` + '^'.repeat(length));\n }\n count += lineLength + 1;\n }\n }\n break;\n }\n }\n return res.join('\\n');\n}\nfunction incrementer(code) {\n let current = code;\n return () => ++current;\n}\n\nfunction warn(msg, err) {\n if (typeof console !== 'undefined') {\n console.warn(`[intlify] ` + msg);\n /* istanbul ignore if */\n if (err) {\n console.warn(err.stack);\n }\n }\n}\nconst hasWarned = {};\nfunction warnOnce(msg) {\n if (!hasWarned[msg]) {\n hasWarned[msg] = true;\n warn(msg);\n }\n}\n\n/**\n * Event emitter, forked from the below:\n * - original repository url: https://github.com/developit/mitt\n * - code url: https://github.com/developit/mitt/blob/master/src/index.ts\n * - author: Jason Miller (https://github.com/developit)\n * - license: MIT\n */\n/**\n * Create a event emitter\n *\n * @returns An event emitter\n */\nfunction createEmitter() {\n const events = new Map();\n const emitter = {\n events,\n on(event, handler) {\n const handlers = events.get(event);\n const added = handlers && handlers.push(handler);\n if (!added) {\n events.set(event, [handler]);\n }\n },\n off(event, handler) {\n const handlers = events.get(event);\n if (handlers) {\n handlers.splice(handlers.indexOf(handler) >>> 0, 1);\n }\n },\n emit(event, payload) {\n (events.get(event) || [])\n .slice()\n .map(handler => handler(payload));\n (events.get('*') || [])\n .slice()\n .map(handler => handler(event, payload));\n }\n };\n return emitter;\n}\n\nconst isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction deepCopy(src, des) {\n // src and des should both be objects, and none of them can be a array\n if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {\n throw new Error('Invalid value');\n }\n const stack = [{ src, des }];\n while (stack.length) {\n const { src, des } = stack.pop();\n Object.keys(src).forEach(key => {\n if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {\n // replace with src[key] when:\n // src[key] or des[key] is not an object, or\n // src[key] or des[key] is an array\n des[key] = src[key];\n }\n else {\n // src[key] and des[key] are both objects, merge them\n stack.push({ src: src[key], des: des[key] });\n }\n });\n }\n}\n\nexport { assign, createEmitter, deepCopy, escapeHtml, format, friendlyJSONstringify, generateCodeFrame, generateFormatCacheKey, getGlobalThis, hasOwn, inBrowser, incrementer, isArray, isBoolean, isDate, isEmptyObject, isFunction, isNumber, isObject, isPlainObject, isPromise, isRegExp, isString, isSymbol, join, makeSymbol, mark, measure, objectToString, toDisplayString, toTypeString, warn, warnOnce };\n","/*!\n * message-compiler v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nconst LOCATION_STUB = {\n start: { line: 1, column: 1, offset: 0 },\n end: { line: 1, column: 1, offset: 0 }\n};\nfunction createPosition(line, column, offset) {\n return { line, column, offset };\n}\nfunction createLocation(start, end, source) {\n const loc = { start, end };\n if (source != null) {\n loc.source = source;\n }\n return loc;\n}\n\n/**\n * Original Utilities\n * written by kazuya kawaguchi\n */\nconst RE_ARGS = /\\{([0-9a-zA-Z]+)\\}/g;\n/* eslint-disable */\nfunction format(message, ...args) {\n if (args.length === 1 && isObject(args[0])) {\n args = args[0];\n }\n if (!args || !args.hasOwnProperty) {\n args = {};\n }\n return message.replace(RE_ARGS, (match, identifier) => {\n return args.hasOwnProperty(identifier) ? args[identifier] : '';\n });\n}\nconst assign = Object.assign;\nconst isString = (val) => typeof val === 'string';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObject = (val) => val !== null && typeof val === 'object';\nfunction join(items, separator = '') {\n return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');\n}\n\nconst CompileWarnCodes = {\n USE_MODULO_SYNTAX: 1,\n __EXTEND_POINT__: 2\n};\n/** @internal */\nconst warnMessages = {\n [CompileWarnCodes.USE_MODULO_SYNTAX]: `Use modulo before '{{0}}'.`\n};\nfunction createCompileWarn(code, loc, ...args) {\n const msg = format(warnMessages[code] || '', ...(args || [])) ;\n const message = { message: String(msg), code };\n if (loc) {\n message.location = loc;\n }\n return message;\n}\n\nconst CompileErrorCodes = {\n // tokenizer error codes\n EXPECTED_TOKEN: 1,\n INVALID_TOKEN_IN_PLACEHOLDER: 2,\n UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,\n UNKNOWN_ESCAPE_SEQUENCE: 4,\n INVALID_UNICODE_ESCAPE_SEQUENCE: 5,\n UNBALANCED_CLOSING_BRACE: 6,\n UNTERMINATED_CLOSING_BRACE: 7,\n EMPTY_PLACEHOLDER: 8,\n NOT_ALLOW_NEST_PLACEHOLDER: 9,\n INVALID_LINKED_FORMAT: 10,\n // parser error codes\n MUST_HAVE_MESSAGES_IN_PLURAL: 11,\n UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,\n UNEXPECTED_EMPTY_LINKED_KEY: 13,\n UNEXPECTED_LEXICAL_ANALYSIS: 14,\n // generator error codes\n UNHANDLED_CODEGEN_NODE_TYPE: 15,\n // minifier error codes\n UNHANDLED_MINIFIER_NODE_TYPE: 16,\n // Special value for higher-order compilers to pick up the last code\n // to avoid collision of error codes. This should always be kept as the last\n // item.\n __EXTEND_POINT__: 17\n};\n/** @internal */\nconst errorMessages = {\n // tokenizer error messages\n [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,\n [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,\n [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,\n [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\\\{0}`,\n [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,\n [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,\n [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,\n [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,\n [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,\n [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,\n // parser error messages\n [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,\n [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,\n [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,\n [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,\n // generator error messages\n [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,\n // minimizer error messages\n [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`\n};\nfunction createCompileError(code, loc, options = {}) {\n const { domain, messages, args } = options;\n const msg = format((messages || errorMessages)[code] || '', ...(args || []))\n ;\n const error = new SyntaxError(String(msg));\n error.code = code;\n if (loc) {\n error.location = loc;\n }\n error.domain = domain;\n return error;\n}\n/** @internal */\nfunction defaultOnError(error) {\n throw error;\n}\n\n// eslint-disable-next-line no-useless-escape\nconst RE_HTML_TAG = /<\\/?[\\w\\s=\"/.':;#-\\/]+>/;\nconst detectHtmlTag = (source) => RE_HTML_TAG.test(source);\n\nconst CHAR_SP = ' ';\nconst CHAR_CR = '\\r';\nconst CHAR_LF = '\\n';\nconst CHAR_LS = String.fromCharCode(0x2028);\nconst CHAR_PS = String.fromCharCode(0x2029);\nfunction createScanner(str) {\n const _buf = str;\n let _index = 0;\n let _line = 1;\n let _column = 1;\n let _peekOffset = 0;\n const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;\n const isLF = (index) => _buf[index] === CHAR_LF;\n const isPS = (index) => _buf[index] === CHAR_PS;\n const isLS = (index) => _buf[index] === CHAR_LS;\n const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);\n const index = () => _index;\n const line = () => _line;\n const column = () => _column;\n const peekOffset = () => _peekOffset;\n const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];\n const currentChar = () => charAt(_index);\n const currentPeek = () => charAt(_index + _peekOffset);\n function next() {\n _peekOffset = 0;\n if (isLineEnd(_index)) {\n _line++;\n _column = 0;\n }\n if (isCRLF(_index)) {\n _index++;\n }\n _index++;\n _column++;\n return _buf[_index];\n }\n function peek() {\n if (isCRLF(_index + _peekOffset)) {\n _peekOffset++;\n }\n _peekOffset++;\n return _buf[_index + _peekOffset];\n }\n function reset() {\n _index = 0;\n _line = 1;\n _column = 1;\n _peekOffset = 0;\n }\n function resetPeek(offset = 0) {\n _peekOffset = offset;\n }\n function skipToPeek() {\n const target = _index + _peekOffset;\n // eslint-disable-next-line no-unmodified-loop-condition\n while (target !== _index) {\n next();\n }\n _peekOffset = 0;\n }\n return {\n index,\n line,\n column,\n peekOffset,\n charAt,\n currentChar,\n currentPeek,\n next,\n peek,\n reset,\n resetPeek,\n skipToPeek\n };\n}\n\nconst EOF = undefined;\nconst DOT = '.';\nconst LITERAL_DELIMITER = \"'\";\nconst ERROR_DOMAIN$3 = 'tokenizer';\nfunction createTokenizer(source, options = {}) {\n const location = options.location !== false;\n const _scnr = createScanner(source);\n const currentOffset = () => _scnr.index();\n const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());\n const _initLoc = currentPosition();\n const _initOffset = currentOffset();\n const _context = {\n currentType: 14 /* TokenTypes.EOF */,\n offset: _initOffset,\n startLoc: _initLoc,\n endLoc: _initLoc,\n lastType: 14 /* TokenTypes.EOF */,\n lastOffset: _initOffset,\n lastStartLoc: _initLoc,\n lastEndLoc: _initLoc,\n braceNest: 0,\n inLinked: false,\n text: ''\n };\n const context = () => _context;\n const { onError } = options;\n function emitError(code, pos, offset, ...args) {\n const ctx = context();\n pos.column += offset;\n pos.offset += offset;\n if (onError) {\n const loc = location ? createLocation(ctx.startLoc, pos) : null;\n const err = createCompileError(code, loc, {\n domain: ERROR_DOMAIN$3,\n args\n });\n onError(err);\n }\n }\n function getToken(context, type, value) {\n context.endLoc = currentPosition();\n context.currentType = type;\n const token = { type };\n if (location) {\n token.loc = createLocation(context.startLoc, context.endLoc);\n }\n if (value != null) {\n token.value = value;\n }\n return token;\n }\n const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);\n function eat(scnr, ch) {\n if (scnr.currentChar() === ch) {\n scnr.next();\n return ch;\n }\n else {\n emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);\n return '';\n }\n }\n function peekSpaces(scnr) {\n let buf = '';\n while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {\n buf += scnr.currentPeek();\n scnr.peek();\n }\n return buf;\n }\n function skipSpaces(scnr) {\n const buf = peekSpaces(scnr);\n scnr.skipToPeek();\n return buf;\n }\n function isIdentifierStart(ch) {\n if (ch === EOF) {\n return false;\n }\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n cc === 95 // _\n );\n }\n function isNumberStart(ch) {\n if (ch === EOF) {\n return false;\n }\n const cc = ch.charCodeAt(0);\n return cc >= 48 && cc <= 57; // 0-9\n }\n function isNamedIdentifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = isIdentifierStart(scnr.currentPeek());\n scnr.resetPeek();\n return ret;\n }\n function isListIdentifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();\n const ret = isNumberStart(ch);\n scnr.resetPeek();\n return ret;\n }\n function isLiteralStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === LITERAL_DELIMITER;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedDotStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 8 /* TokenTypes.LinkedAlias */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \".\" /* TokenChars.LinkedDot */;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedModifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 9 /* TokenTypes.LinkedDot */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = isIdentifierStart(scnr.currentPeek());\n scnr.resetPeek();\n return ret;\n }\n function isLinkedDelimiterStart(scnr, context) {\n const { currentType } = context;\n if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||\n currentType === 12 /* TokenTypes.LinkedModifier */)) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \":\" /* TokenChars.LinkedDelimiter */;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedReferStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {\n return false;\n }\n const fn = () => {\n const ch = scnr.currentPeek();\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n return isIdentifierStart(scnr.peek());\n }\n else if (ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"%\" /* TokenChars.Modulo */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n ch === \":\" /* TokenChars.LinkedDelimiter */ ||\n ch === \".\" /* TokenChars.LinkedDot */ ||\n ch === CHAR_SP ||\n !ch) {\n return false;\n }\n else if (ch === CHAR_LF) {\n scnr.peek();\n return fn();\n }\n else {\n // other characters\n return isTextStart(scnr, false);\n }\n };\n const ret = fn();\n scnr.resetPeek();\n return ret;\n }\n function isPluralStart(scnr) {\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \"|\" /* TokenChars.Pipe */;\n scnr.resetPeek();\n return ret;\n }\n function detectModuloStart(scnr) {\n const spaces = peekSpaces(scnr);\n const ret = scnr.currentPeek() === \"%\" /* TokenChars.Modulo */ &&\n scnr.peek() === \"{\" /* TokenChars.BraceLeft */;\n scnr.resetPeek();\n return {\n isModulo: ret,\n hasSpace: spaces.length > 0\n };\n }\n function isTextStart(scnr, reset = true) {\n const fn = (hasSpace = false, prev = '', detectModulo = false) => {\n const ch = scnr.currentPeek();\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n return prev === \"%\" /* TokenChars.Modulo */ ? false : hasSpace;\n }\n else if (ch === \"@\" /* TokenChars.LinkedAlias */ || !ch) {\n return prev === \"%\" /* TokenChars.Modulo */ ? true : hasSpace;\n }\n else if (ch === \"%\" /* TokenChars.Modulo */) {\n scnr.peek();\n return fn(hasSpace, \"%\" /* TokenChars.Modulo */, true);\n }\n else if (ch === \"|\" /* TokenChars.Pipe */) {\n return prev === \"%\" /* TokenChars.Modulo */ || detectModulo\n ? true\n : !(prev === CHAR_SP || prev === CHAR_LF);\n }\n else if (ch === CHAR_SP) {\n scnr.peek();\n return fn(true, CHAR_SP, detectModulo);\n }\n else if (ch === CHAR_LF) {\n scnr.peek();\n return fn(true, CHAR_LF, detectModulo);\n }\n else {\n return true;\n }\n };\n const ret = fn();\n reset && scnr.resetPeek();\n return ret;\n }\n function takeChar(scnr, fn) {\n const ch = scnr.currentChar();\n if (ch === EOF) {\n return EOF;\n }\n if (fn(ch)) {\n scnr.next();\n return ch;\n }\n return null;\n }\n function isIdentifier(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n (cc >= 48 && cc <= 57) || // 0-9\n cc === 95 || // _\n cc === 36 // $\n );\n }\n function takeIdentifierChar(scnr) {\n return takeChar(scnr, isIdentifier);\n }\n function isNamedIdentifier(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n (cc >= 48 && cc <= 57) || // 0-9\n cc === 95 || // _\n cc === 36 || // $\n cc === 45 // -\n );\n }\n function takeNamedIdentifierChar(scnr) {\n return takeChar(scnr, isNamedIdentifier);\n }\n function isDigit(ch) {\n const cc = ch.charCodeAt(0);\n return cc >= 48 && cc <= 57; // 0-9\n }\n function takeDigit(scnr) {\n return takeChar(scnr, isDigit);\n }\n function isHexDigit(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 48 && cc <= 57) || // 0-9\n (cc >= 65 && cc <= 70) || // A-F\n (cc >= 97 && cc <= 102)); // a-f\n }\n function takeHexDigit(scnr) {\n return takeChar(scnr, isHexDigit);\n }\n function getDigits(scnr) {\n let ch = '';\n let num = '';\n while ((ch = takeDigit(scnr))) {\n num += ch;\n }\n return num;\n }\n function readModulo(scnr) {\n skipSpaces(scnr);\n const ch = scnr.currentChar();\n if (ch !== \"%\" /* TokenChars.Modulo */) {\n emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);\n }\n scnr.next();\n return \"%\" /* TokenChars.Modulo */;\n }\n function readText(scnr) {\n let buf = '';\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const ch = scnr.currentChar();\n if (ch === \"{\" /* TokenChars.BraceLeft */ ||\n ch === \"}\" /* TokenChars.BraceRight */ ||\n ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n !ch) {\n break;\n }\n else if (ch === \"%\" /* TokenChars.Modulo */) {\n if (isTextStart(scnr)) {\n buf += ch;\n scnr.next();\n }\n else {\n break;\n }\n }\n else if (ch === CHAR_SP || ch === CHAR_LF) {\n if (isTextStart(scnr)) {\n buf += ch;\n scnr.next();\n }\n else if (isPluralStart(scnr)) {\n break;\n }\n else {\n buf += ch;\n scnr.next();\n }\n }\n else {\n buf += ch;\n scnr.next();\n }\n }\n return buf;\n }\n function readNamedIdentifier(scnr) {\n skipSpaces(scnr);\n let ch = '';\n let name = '';\n while ((ch = takeNamedIdentifierChar(scnr))) {\n name += ch;\n }\n if (scnr.currentChar() === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n return name;\n }\n function readListIdentifier(scnr) {\n skipSpaces(scnr);\n let value = '';\n if (scnr.currentChar() === '-') {\n scnr.next();\n value += `-${getDigits(scnr)}`;\n }\n else {\n value += getDigits(scnr);\n }\n if (scnr.currentChar() === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n return value;\n }\n function isLiteral(ch) {\n return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;\n }\n function readLiteral(scnr) {\n skipSpaces(scnr);\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n let ch = '';\n let literal = '';\n while ((ch = takeChar(scnr, isLiteral))) {\n if (ch === '\\\\') {\n literal += readEscapeSequence(scnr);\n }\n else {\n literal += ch;\n }\n }\n const current = scnr.currentChar();\n if (current === CHAR_LF || current === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);\n // TODO: Is it correct really?\n if (current === CHAR_LF) {\n scnr.next();\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n }\n return literal;\n }\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n return literal;\n }\n function readEscapeSequence(scnr) {\n const ch = scnr.currentChar();\n switch (ch) {\n case '\\\\':\n case `\\'`: // eslint-disable-line no-useless-escape\n scnr.next();\n return `\\\\${ch}`;\n case 'u':\n return readUnicodeEscapeSequence(scnr, ch, 4);\n case 'U':\n return readUnicodeEscapeSequence(scnr, ch, 6);\n default:\n emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);\n return '';\n }\n }\n function readUnicodeEscapeSequence(scnr, unicode, digits) {\n eat(scnr, unicode);\n let sequence = '';\n for (let i = 0; i < digits; i++) {\n const ch = takeHexDigit(scnr);\n if (!ch) {\n emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\\\${unicode}${sequence}${scnr.currentChar()}`);\n break;\n }\n sequence += ch;\n }\n return `\\\\${unicode}${sequence}`;\n }\n function isInvalidIdentifier(ch) {\n return (ch !== \"{\" /* TokenChars.BraceLeft */ &&\n ch !== \"}\" /* TokenChars.BraceRight */ &&\n ch !== CHAR_SP &&\n ch !== CHAR_LF);\n }\n function readInvalidIdentifier(scnr) {\n skipSpaces(scnr);\n let ch = '';\n let identifiers = '';\n while ((ch = takeChar(scnr, isInvalidIdentifier))) {\n identifiers += ch;\n }\n return identifiers;\n }\n function readLinkedModifier(scnr) {\n let ch = '';\n let name = '';\n while ((ch = takeIdentifierChar(scnr))) {\n name += ch;\n }\n return name;\n }\n function readLinkedRefer(scnr) {\n const fn = (buf) => {\n const ch = scnr.currentChar();\n if (ch === \"{\" /* TokenChars.BraceLeft */ ||\n ch === \"%\" /* TokenChars.Modulo */ ||\n ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n ch === \"(\" /* TokenChars.ParenLeft */ ||\n ch === \")\" /* TokenChars.ParenRight */ ||\n !ch) {\n return buf;\n }\n else if (ch === CHAR_SP) {\n return buf;\n }\n else if (ch === CHAR_LF || ch === DOT) {\n buf += ch;\n scnr.next();\n return fn(buf);\n }\n else {\n buf += ch;\n scnr.next();\n return fn(buf);\n }\n };\n return fn('');\n }\n function readPlural(scnr) {\n skipSpaces(scnr);\n const plural = eat(scnr, \"|\" /* TokenChars.Pipe */);\n skipSpaces(scnr);\n return plural;\n }\n // TODO: We need refactoring of token parsing ...\n function readTokenInPlaceholder(scnr, context) {\n let token = null;\n const ch = scnr.currentChar();\n switch (ch) {\n case \"{\" /* TokenChars.BraceLeft */:\n if (context.braceNest >= 1) {\n emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);\n }\n scnr.next();\n token = getToken(context, 2 /* TokenTypes.BraceLeft */, \"{\" /* TokenChars.BraceLeft */);\n skipSpaces(scnr);\n context.braceNest++;\n return token;\n case \"}\" /* TokenChars.BraceRight */:\n if (context.braceNest > 0 &&\n context.currentType === 2 /* TokenTypes.BraceLeft */) {\n emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);\n }\n scnr.next();\n token = getToken(context, 3 /* TokenTypes.BraceRight */, \"}\" /* TokenChars.BraceRight */);\n context.braceNest--;\n context.braceNest > 0 && skipSpaces(scnr);\n if (context.inLinked && context.braceNest === 0) {\n context.inLinked = false;\n }\n return token;\n case \"@\" /* TokenChars.LinkedAlias */:\n if (context.braceNest > 0) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n token = readTokenInLinked(scnr, context) || getEndToken(context);\n context.braceNest = 0;\n return token;\n default: {\n let validNamedIdentifier = true;\n let validListIdentifier = true;\n let validLiteral = true;\n if (isPluralStart(scnr)) {\n if (context.braceNest > 0) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n if (context.braceNest > 0 &&\n (context.currentType === 5 /* TokenTypes.Named */ ||\n context.currentType === 6 /* TokenTypes.List */ ||\n context.currentType === 7 /* TokenTypes.Literal */)) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n context.braceNest = 0;\n return readToken(scnr, context);\n }\n if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {\n token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));\n skipSpaces(scnr);\n return token;\n }\n if ((validListIdentifier = isListIdentifierStart(scnr, context))) {\n token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));\n skipSpaces(scnr);\n return token;\n }\n if ((validLiteral = isLiteralStart(scnr, context))) {\n token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));\n skipSpaces(scnr);\n return token;\n }\n if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {\n // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...\n token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));\n emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);\n skipSpaces(scnr);\n return token;\n }\n break;\n }\n }\n return token;\n }\n // TODO: We need refactoring of token parsing ...\n function readTokenInLinked(scnr, context) {\n const { currentType } = context;\n let token = null;\n const ch = scnr.currentChar();\n if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||\n currentType === 9 /* TokenTypes.LinkedDot */ ||\n currentType === 12 /* TokenTypes.LinkedModifier */ ||\n currentType === 10 /* TokenTypes.LinkedDelimiter */) &&\n (ch === CHAR_LF || ch === CHAR_SP)) {\n emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);\n }\n switch (ch) {\n case \"@\" /* TokenChars.LinkedAlias */:\n scnr.next();\n token = getToken(context, 8 /* TokenTypes.LinkedAlias */, \"@\" /* TokenChars.LinkedAlias */);\n context.inLinked = true;\n return token;\n case \".\" /* TokenChars.LinkedDot */:\n skipSpaces(scnr);\n scnr.next();\n return getToken(context, 9 /* TokenTypes.LinkedDot */, \".\" /* TokenChars.LinkedDot */);\n case \":\" /* TokenChars.LinkedDelimiter */:\n skipSpaces(scnr);\n scnr.next();\n return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, \":\" /* TokenChars.LinkedDelimiter */);\n default:\n if (isPluralStart(scnr)) {\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n if (isLinkedDotStart(scnr, context) ||\n isLinkedDelimiterStart(scnr, context)) {\n skipSpaces(scnr);\n return readTokenInLinked(scnr, context);\n }\n if (isLinkedModifierStart(scnr, context)) {\n skipSpaces(scnr);\n return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));\n }\n if (isLinkedReferStart(scnr, context)) {\n skipSpaces(scnr);\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n // scan the placeholder\n return readTokenInPlaceholder(scnr, context) || token;\n }\n else {\n return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));\n }\n }\n if (currentType === 8 /* TokenTypes.LinkedAlias */) {\n emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);\n }\n context.braceNest = 0;\n context.inLinked = false;\n return readToken(scnr, context);\n }\n }\n // TODO: We need refactoring of token parsing ...\n function readToken(scnr, context) {\n let token = { type: 14 /* TokenTypes.EOF */ };\n if (context.braceNest > 0) {\n return readTokenInPlaceholder(scnr, context) || getEndToken(context);\n }\n if (context.inLinked) {\n return readTokenInLinked(scnr, context) || getEndToken(context);\n }\n const ch = scnr.currentChar();\n switch (ch) {\n case \"{\" /* TokenChars.BraceLeft */:\n return readTokenInPlaceholder(scnr, context) || getEndToken(context);\n case \"}\" /* TokenChars.BraceRight */:\n emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);\n scnr.next();\n return getToken(context, 3 /* TokenTypes.BraceRight */, \"}\" /* TokenChars.BraceRight */);\n case \"@\" /* TokenChars.LinkedAlias */:\n return readTokenInLinked(scnr, context) || getEndToken(context);\n default: {\n if (isPluralStart(scnr)) {\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n const { isModulo, hasSpace } = detectModuloStart(scnr);\n if (isModulo) {\n return hasSpace\n ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))\n : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));\n }\n if (isTextStart(scnr)) {\n return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));\n }\n break;\n }\n }\n return token;\n }\n function nextToken() {\n const { currentType, offset, startLoc, endLoc } = _context;\n _context.lastType = currentType;\n _context.lastOffset = offset;\n _context.lastStartLoc = startLoc;\n _context.lastEndLoc = endLoc;\n _context.offset = currentOffset();\n _context.startLoc = currentPosition();\n if (_scnr.currentChar() === EOF) {\n return getToken(_context, 14 /* TokenTypes.EOF */);\n }\n return readToken(_scnr, _context);\n }\n return {\n nextToken,\n currentOffset,\n currentPosition,\n context\n };\n}\n\nconst ERROR_DOMAIN$2 = 'parser';\n// Backslash backslash, backslash quote, uHHHH, UHHHHHH.\nconst KNOWN_ESCAPES = /(?:\\\\\\\\|\\\\'|\\\\u([0-9a-fA-F]{4})|\\\\U([0-9a-fA-F]{6}))/g;\nfunction fromEscapeSequence(match, codePoint4, codePoint6) {\n switch (match) {\n case `\\\\\\\\`:\n return `\\\\`;\n // eslint-disable-next-line no-useless-escape\n case `\\\\\\'`:\n // eslint-disable-next-line no-useless-escape\n return `\\'`;\n default: {\n const codePoint = parseInt(codePoint4 || codePoint6, 16);\n if (codePoint <= 0xd7ff || codePoint >= 0xe000) {\n return String.fromCodePoint(codePoint);\n }\n // invalid ...\n // Replace them with U+FFFD REPLACEMENT CHARACTER.\n return '�';\n }\n }\n}\nfunction createParser(options = {}) {\n const location = options.location !== false;\n const { onError, onWarn } = options;\n function emitError(tokenzer, code, start, offset, ...args) {\n const end = tokenzer.currentPosition();\n end.offset += offset;\n end.column += offset;\n if (onError) {\n const loc = location ? createLocation(start, end) : null;\n const err = createCompileError(code, loc, {\n domain: ERROR_DOMAIN$2,\n args\n });\n onError(err);\n }\n }\n function emitWarn(tokenzer, code, start, offset, ...args) {\n const end = tokenzer.currentPosition();\n end.offset += offset;\n end.column += offset;\n if (onWarn) {\n const loc = location ? createLocation(start, end) : null;\n onWarn(createCompileWarn(code, loc, args));\n }\n }\n function startNode(type, offset, loc) {\n const node = { type };\n if (location) {\n node.start = offset;\n node.end = offset;\n node.loc = { start: loc, end: loc };\n }\n return node;\n }\n function endNode(node, offset, pos, type) {\n if (type) {\n node.type = type;\n }\n if (location) {\n node.end = offset;\n if (node.loc) {\n node.loc.end = pos;\n }\n }\n }\n function parseText(tokenizer, value) {\n const context = tokenizer.context();\n const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);\n node.value = value;\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseList(tokenizer, index) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(5 /* NodeTypes.List */, offset, loc);\n node.index = parseInt(index, 10);\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseNamed(tokenizer, key, modulo) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(4 /* NodeTypes.Named */, offset, loc);\n node.key = key;\n if (modulo === true) {\n node.modulo = true;\n }\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLiteral(tokenizer, value) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(9 /* NodeTypes.Literal */, offset, loc);\n node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLinkedModifier(tokenizer) {\n const token = tokenizer.nextToken();\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc\n const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);\n if (token.type !== 12 /* TokenTypes.LinkedModifier */) {\n // empty modifier\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);\n node.value = '';\n endNode(node, offset, loc);\n return {\n nextConsumeToken: token,\n node\n };\n }\n // check token\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.value = token.value || '';\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return {\n node\n };\n }\n function parseLinkedKey(tokenizer, value) {\n const context = tokenizer.context();\n const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);\n node.value = value;\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLinked(tokenizer) {\n const context = tokenizer.context();\n const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);\n let token = tokenizer.nextToken();\n if (token.type === 9 /* TokenTypes.LinkedDot */) {\n const parsed = parseLinkedModifier(tokenizer);\n linkedNode.modifier = parsed.node;\n token = parsed.nextConsumeToken || tokenizer.nextToken();\n }\n // asset check token\n if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n token = tokenizer.nextToken();\n // skip brace left\n if (token.type === 2 /* TokenTypes.BraceLeft */) {\n token = tokenizer.nextToken();\n }\n switch (token.type) {\n case 11 /* TokenTypes.LinkedKey */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseLinkedKey(tokenizer, token.value || '');\n break;\n case 5 /* TokenTypes.Named */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseNamed(tokenizer, token.value || '');\n break;\n case 6 /* TokenTypes.List */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseList(tokenizer, token.value || '');\n break;\n case 7 /* TokenTypes.Literal */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseLiteral(tokenizer, token.value || '');\n break;\n default: {\n // empty key\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);\n const nextContext = tokenizer.context();\n const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);\n emptyLinkedKeyNode.value = '';\n endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);\n linkedNode.key = emptyLinkedKeyNode;\n endNode(linkedNode, nextContext.offset, nextContext.startLoc);\n return {\n nextConsumeToken: token,\n node: linkedNode\n };\n }\n }\n endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());\n return {\n node: linkedNode\n };\n }\n function parseMessage(tokenizer) {\n const context = tokenizer.context();\n const startOffset = context.currentType === 1 /* TokenTypes.Pipe */\n ? tokenizer.currentOffset()\n : context.offset;\n const startLoc = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.endLoc\n : context.startLoc;\n const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);\n node.items = [];\n let nextToken = null;\n let modulo = null;\n do {\n const token = nextToken || tokenizer.nextToken();\n nextToken = null;\n switch (token.type) {\n case 0 /* TokenTypes.Text */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseText(tokenizer, token.value || ''));\n break;\n case 6 /* TokenTypes.List */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseList(tokenizer, token.value || ''));\n break;\n case 4 /* TokenTypes.Modulo */:\n modulo = true;\n break;\n case 5 /* TokenTypes.Named */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseNamed(tokenizer, token.value || '', !!modulo));\n if (modulo) {\n emitWarn(tokenizer, CompileWarnCodes.USE_MODULO_SYNTAX, context.lastStartLoc, 0, getTokenCaption(token));\n modulo = null;\n }\n break;\n case 7 /* TokenTypes.Literal */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseLiteral(tokenizer, token.value || ''));\n break;\n case 8 /* TokenTypes.LinkedAlias */: {\n const parsed = parseLinked(tokenizer);\n node.items.push(parsed.node);\n nextToken = parsed.nextConsumeToken || null;\n break;\n }\n }\n } while (context.currentType !== 14 /* TokenTypes.EOF */ &&\n context.currentType !== 1 /* TokenTypes.Pipe */);\n // adjust message node loc\n const endOffset = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.lastOffset\n : tokenizer.currentOffset();\n const endLoc = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.lastEndLoc\n : tokenizer.currentPosition();\n endNode(node, endOffset, endLoc);\n return node;\n }\n function parsePlural(tokenizer, offset, loc, msgNode) {\n const context = tokenizer.context();\n let hasEmptyMessage = msgNode.items.length === 0;\n const node = startNode(1 /* NodeTypes.Plural */, offset, loc);\n node.cases = [];\n node.cases.push(msgNode);\n do {\n const msg = parseMessage(tokenizer);\n if (!hasEmptyMessage) {\n hasEmptyMessage = msg.items.length === 0;\n }\n node.cases.push(msg);\n } while (context.currentType !== 14 /* TokenTypes.EOF */);\n if (hasEmptyMessage) {\n emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);\n }\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseResource(tokenizer) {\n const context = tokenizer.context();\n const { offset, startLoc } = context;\n const msgNode = parseMessage(tokenizer);\n if (context.currentType === 14 /* TokenTypes.EOF */) {\n return msgNode;\n }\n else {\n return parsePlural(tokenizer, offset, startLoc, msgNode);\n }\n }\n function parse(source) {\n const tokenizer = createTokenizer(source, assign({}, options));\n const context = tokenizer.context();\n const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);\n if (location && node.loc) {\n node.loc.source = source;\n }\n node.body = parseResource(tokenizer);\n if (options.onCacheKey) {\n node.cacheKey = options.onCacheKey(source);\n }\n // assert whether achieved to EOF\n if (context.currentType !== 14 /* TokenTypes.EOF */) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');\n }\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n return { parse };\n}\nfunction getTokenCaption(token) {\n if (token.type === 14 /* TokenTypes.EOF */) {\n return 'EOF';\n }\n const name = (token.value || '').replace(/\\r?\\n/gu, '\\\\n');\n return name.length > 10 ? name.slice(0, 9) + '…' : name;\n}\n\nfunction createTransformer(ast, options = {} // eslint-disable-line\n) {\n const _context = {\n ast,\n helpers: new Set()\n };\n const context = () => _context;\n const helper = (name) => {\n _context.helpers.add(name);\n return name;\n };\n return { context, helper };\n}\nfunction traverseNodes(nodes, transformer) {\n for (let i = 0; i < nodes.length; i++) {\n traverseNode(nodes[i], transformer);\n }\n}\nfunction traverseNode(node, transformer) {\n // TODO: if we need pre-hook of transform, should be implemented to here\n switch (node.type) {\n case 1 /* NodeTypes.Plural */:\n traverseNodes(node.cases, transformer);\n transformer.helper(\"plural\" /* HelperNameMap.PLURAL */);\n break;\n case 2 /* NodeTypes.Message */:\n traverseNodes(node.items, transformer);\n break;\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n traverseNode(linked.key, transformer);\n transformer.helper(\"linked\" /* HelperNameMap.LINKED */);\n transformer.helper(\"type\" /* HelperNameMap.TYPE */);\n break;\n }\n case 5 /* NodeTypes.List */:\n transformer.helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */);\n transformer.helper(\"list\" /* HelperNameMap.LIST */);\n break;\n case 4 /* NodeTypes.Named */:\n transformer.helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */);\n transformer.helper(\"named\" /* HelperNameMap.NAMED */);\n break;\n }\n // TODO: if we need post-hook of transform, should be implemented to here\n}\n// transform AST\nfunction transform(ast, options = {} // eslint-disable-line\n) {\n const transformer = createTransformer(ast);\n transformer.helper(\"normalize\" /* HelperNameMap.NORMALIZE */);\n // traverse\n ast.body && traverseNode(ast.body, transformer);\n // set meta information\n const context = transformer.context();\n ast.helpers = Array.from(context.helpers);\n}\n\nfunction optimize(ast) {\n const body = ast.body;\n if (body.type === 2 /* NodeTypes.Message */) {\n optimizeMessageNode(body);\n }\n else {\n body.cases.forEach(c => optimizeMessageNode(c));\n }\n return ast;\n}\nfunction optimizeMessageNode(message) {\n if (message.items.length === 1) {\n const item = message.items[0];\n if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {\n message.static = item.value;\n delete item.value; // optimization for size\n }\n }\n else {\n const values = [];\n for (let i = 0; i < message.items.length; i++) {\n const item = message.items[i];\n if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {\n break;\n }\n if (item.value == null) {\n break;\n }\n values.push(item.value);\n }\n if (values.length === message.items.length) {\n message.static = join(values);\n for (let i = 0; i < message.items.length; i++) {\n const item = message.items[i];\n if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {\n delete item.value; // optimization for size\n }\n }\n }\n }\n}\n\nconst ERROR_DOMAIN$1 = 'minifier';\n/* eslint-disable @typescript-eslint/no-explicit-any */\nfunction minify(node) {\n node.t = node.type;\n switch (node.type) {\n case 0 /* NodeTypes.Resource */: {\n const resource = node;\n minify(resource.body);\n resource.b = resource.body;\n delete resource.body;\n break;\n }\n case 1 /* NodeTypes.Plural */: {\n const plural = node;\n const cases = plural.cases;\n for (let i = 0; i < cases.length; i++) {\n minify(cases[i]);\n }\n plural.c = cases;\n delete plural.cases;\n break;\n }\n case 2 /* NodeTypes.Message */: {\n const message = node;\n const items = message.items;\n for (let i = 0; i < items.length; i++) {\n minify(items[i]);\n }\n message.i = items;\n delete message.items;\n if (message.static) {\n message.s = message.static;\n delete message.static;\n }\n break;\n }\n case 3 /* NodeTypes.Text */:\n case 9 /* NodeTypes.Literal */:\n case 8 /* NodeTypes.LinkedModifier */:\n case 7 /* NodeTypes.LinkedKey */: {\n const valueNode = node;\n if (valueNode.value) {\n valueNode.v = valueNode.value;\n delete valueNode.value;\n }\n break;\n }\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n minify(linked.key);\n linked.k = linked.key;\n delete linked.key;\n if (linked.modifier) {\n minify(linked.modifier);\n linked.m = linked.modifier;\n delete linked.modifier;\n }\n break;\n }\n case 5 /* NodeTypes.List */: {\n const list = node;\n list.i = list.index;\n delete list.index;\n break;\n }\n case 4 /* NodeTypes.Named */: {\n const named = node;\n named.k = named.key;\n delete named.key;\n break;\n }\n default:\n {\n throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {\n domain: ERROR_DOMAIN$1,\n args: [node.type]\n });\n }\n }\n delete node.type;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// \nconst ERROR_DOMAIN = 'parser';\nfunction createCodeGenerator(ast, options) {\n const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;\n const location = options.location !== false;\n const _context = {\n filename,\n code: '',\n column: 1,\n line: 1,\n offset: 0,\n map: undefined,\n breakLineCode,\n needIndent: _needIndent,\n indentLevel: 0\n };\n if (location && ast.loc) {\n _context.source = ast.loc.source;\n }\n const context = () => _context;\n function push(code, node) {\n _context.code += code;\n }\n function _newline(n, withBreakLine = true) {\n const _breakLineCode = withBreakLine ? breakLineCode : '';\n push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);\n }\n function indent(withNewLine = true) {\n const level = ++_context.indentLevel;\n withNewLine && _newline(level);\n }\n function deindent(withNewLine = true) {\n const level = --_context.indentLevel;\n withNewLine && _newline(level);\n }\n function newline() {\n _newline(_context.indentLevel);\n }\n const helper = (key) => `_${key}`;\n const needIndent = () => _context.needIndent;\n return {\n context,\n push,\n indent,\n deindent,\n newline,\n helper,\n needIndent\n };\n}\nfunction generateLinkedNode(generator, node) {\n const { helper } = generator;\n generator.push(`${helper(\"linked\" /* HelperNameMap.LINKED */)}(`);\n generateNode(generator, node.key);\n if (node.modifier) {\n generator.push(`, `);\n generateNode(generator, node.modifier);\n generator.push(`, _type`);\n }\n else {\n generator.push(`, undefined, _type`);\n }\n generator.push(`)`);\n}\nfunction generateMessageNode(generator, node) {\n const { helper, needIndent } = generator;\n generator.push(`${helper(\"normalize\" /* HelperNameMap.NORMALIZE */)}([`);\n generator.indent(needIndent());\n const length = node.items.length;\n for (let i = 0; i < length; i++) {\n generateNode(generator, node.items[i]);\n if (i === length - 1) {\n break;\n }\n generator.push(', ');\n }\n generator.deindent(needIndent());\n generator.push('])');\n}\nfunction generatePluralNode(generator, node) {\n const { helper, needIndent } = generator;\n if (node.cases.length > 1) {\n generator.push(`${helper(\"plural\" /* HelperNameMap.PLURAL */)}([`);\n generator.indent(needIndent());\n const length = node.cases.length;\n for (let i = 0; i < length; i++) {\n generateNode(generator, node.cases[i]);\n if (i === length - 1) {\n break;\n }\n generator.push(', ');\n }\n generator.deindent(needIndent());\n generator.push(`])`);\n }\n}\nfunction generateResource(generator, node) {\n if (node.body) {\n generateNode(generator, node.body);\n }\n else {\n generator.push('null');\n }\n}\nfunction generateNode(generator, node) {\n const { helper } = generator;\n switch (node.type) {\n case 0 /* NodeTypes.Resource */:\n generateResource(generator, node);\n break;\n case 1 /* NodeTypes.Plural */:\n generatePluralNode(generator, node);\n break;\n case 2 /* NodeTypes.Message */:\n generateMessageNode(generator, node);\n break;\n case 6 /* NodeTypes.Linked */:\n generateLinkedNode(generator, node);\n break;\n case 8 /* NodeTypes.LinkedModifier */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 7 /* NodeTypes.LinkedKey */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 5 /* NodeTypes.List */:\n generator.push(`${helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */)}(${helper(\"list\" /* HelperNameMap.LIST */)}(${node.index}))`, node);\n break;\n case 4 /* NodeTypes.Named */:\n generator.push(`${helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */)}(${helper(\"named\" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);\n break;\n case 9 /* NodeTypes.Literal */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 3 /* NodeTypes.Text */:\n generator.push(JSON.stringify(node.value), node);\n break;\n default:\n {\n throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {\n domain: ERROR_DOMAIN,\n args: [node.type]\n });\n }\n }\n}\n// generate code from AST\nconst generate = (ast, options = {} // eslint-disable-line\n) => {\n const mode = isString(options.mode) ? options.mode : 'normal';\n const filename = isString(options.filename)\n ? options.filename\n : 'message.intl';\n const sourceMap = !!options.sourceMap;\n // prettier-ignore\n const breakLineCode = options.breakLineCode != null\n ? options.breakLineCode\n : mode === 'arrow'\n ? ';'\n : '\\n';\n const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';\n const helpers = ast.helpers || [];\n const generator = createCodeGenerator(ast, {\n mode,\n filename,\n sourceMap,\n breakLineCode,\n needIndent\n });\n generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);\n generator.indent(needIndent);\n if (helpers.length > 0) {\n generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);\n generator.newline();\n }\n generator.push(`return `);\n generateNode(generator, ast);\n generator.deindent(needIndent);\n generator.push(`}`);\n delete ast.helpers;\n const { code, map } = generator.context();\n return {\n ast,\n code,\n map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n};\n\nfunction baseCompile(source, options = {}) {\n const assignedOptions = assign({}, options);\n const jit = !!assignedOptions.jit;\n const enalbeMinify = !!assignedOptions.minify;\n const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;\n // parse source codes\n const parser = createParser(assignedOptions);\n const ast = parser.parse(source);\n if (!jit) {\n // transform ASTs\n transform(ast, assignedOptions);\n // generate javascript codes\n return generate(ast, assignedOptions);\n }\n else {\n // optimize ASTs\n enambeOptimize && optimize(ast);\n // minimize ASTs\n enalbeMinify && minify(ast);\n // In JIT mode, no ast transform, no code generation.\n return { ast, code: '' };\n }\n}\n\nexport { CompileErrorCodes, CompileWarnCodes, ERROR_DOMAIN$2 as ERROR_DOMAIN, LOCATION_STUB, baseCompile, createCompileError, createCompileWarn, createLocation, createParser, createPosition, defaultOnError, detectHtmlTag, errorMessages, warnMessages };\n","/*!\n * core-base v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nimport { getGlobalThis, isObject, isFunction, isString, isNumber, isPlainObject, assign, join, toDisplayString, isArray, incrementer, format as format$1, isPromise, isBoolean, warn, isRegExp, warnOnce, escapeHtml, inBrowser, mark, measure, isEmptyObject, generateCodeFrame, generateFormatCacheKey, isDate } from '@intlify/shared';\nimport { CompileWarnCodes, CompileErrorCodes, createCompileError, detectHtmlTag, defaultOnError, baseCompile as baseCompile$1 } from '@intlify/message-compiler';\nexport { CompileErrorCodes, createCompileError } from '@intlify/message-compiler';\n\n/**\n * This is only called in esm-bundler builds.\n * istanbul-ignore-next\n */\nfunction initFeatureFlags() {\n if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {\n getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;\n }\n if (typeof __INTLIFY_JIT_COMPILATION__ !== 'boolean') {\n getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;\n }\n if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {\n getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;\n }\n}\n\nconst pathStateMachine = [];\npathStateMachine[0 /* States.BEFORE_PATH */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]\n};\npathStateMachine[1 /* States.IN_PATH */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],\n [\".\" /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]\n};\npathStateMachine[2 /* States.BEFORE_IDENT */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"0\" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]\n};\npathStateMachine[3 /* States.IN_IDENT */] = {\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"0\" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"w\" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],\n [\".\" /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]\n};\npathStateMachine[4 /* States.IN_SUB_PATH */] = {\n [\"'\" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],\n [\"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [\n 4 /* States.IN_SUB_PATH */,\n 2 /* Actions.INC_SUB_PATH_DEPTH */\n ],\n [\"]\" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]\n};\npathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {\n [\"'\" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]\n};\npathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {\n [\"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]\n};\n/**\n * Check if an expression is a literal value.\n */\nconst literalValueRE = /^\\s?(?:true|false|-?[\\d.]+|'[^']*'|\"[^\"]*\")\\s?$/;\nfunction isLiteral(exp) {\n return literalValueRE.test(exp);\n}\n/**\n * Strip quotes from a string\n */\nfunction stripQuotes(str) {\n const a = str.charCodeAt(0);\n const b = str.charCodeAt(str.length - 1);\n return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;\n}\n/**\n * Determine the type of a character in a keypath.\n */\nfunction getPathCharType(ch) {\n if (ch === undefined || ch === null) {\n return \"o\" /* PathCharTypes.END_OF_FAIL */;\n }\n const code = ch.charCodeAt(0);\n switch (code) {\n case 0x5b: // [\n case 0x5d: // ]\n case 0x2e: // .\n case 0x22: // \"\n case 0x27: // '\n return ch;\n case 0x5f: // _\n case 0x24: // $\n case 0x2d: // -\n return \"i\" /* PathCharTypes.IDENT */;\n case 0x09: // Tab (HT)\n case 0x0a: // Newline (LF)\n case 0x0d: // Return (CR)\n case 0xa0: // No-break space (NBSP)\n case 0xfeff: // Byte Order Mark (BOM)\n case 0x2028: // Line Separator (LS)\n case 0x2029: // Paragraph Separator (PS)\n return \"w\" /* PathCharTypes.WORKSPACE */;\n }\n return \"i\" /* PathCharTypes.IDENT */;\n}\n/**\n * Format a subPath, return its plain form if it is\n * a literal string or number. Otherwise prepend the\n * dynamic indicator (*).\n */\nfunction formatSubPath(path) {\n const trimmed = path.trim();\n // invalid leading 0\n if (path.charAt(0) === '0' && isNaN(parseInt(path))) {\n return false;\n }\n return isLiteral(trimmed)\n ? stripQuotes(trimmed)\n : \"*\" /* PathCharTypes.ASTARISK */ + trimmed;\n}\n/**\n * Parse a string path into an array of segments\n */\nfunction parse(path) {\n const keys = [];\n let index = -1;\n let mode = 0 /* States.BEFORE_PATH */;\n let subPathDepth = 0;\n let c;\n let key; // eslint-disable-line\n let newChar;\n let type;\n let transition;\n let action;\n let typeMap;\n const actions = [];\n actions[0 /* Actions.APPEND */] = () => {\n if (key === undefined) {\n key = newChar;\n }\n else {\n key += newChar;\n }\n };\n actions[1 /* Actions.PUSH */] = () => {\n if (key !== undefined) {\n keys.push(key);\n key = undefined;\n }\n };\n actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {\n actions[0 /* Actions.APPEND */]();\n subPathDepth++;\n };\n actions[3 /* Actions.PUSH_SUB_PATH */] = () => {\n if (subPathDepth > 0) {\n subPathDepth--;\n mode = 4 /* States.IN_SUB_PATH */;\n actions[0 /* Actions.APPEND */]();\n }\n else {\n subPathDepth = 0;\n if (key === undefined) {\n return false;\n }\n key = formatSubPath(key);\n if (key === false) {\n return false;\n }\n else {\n actions[1 /* Actions.PUSH */]();\n }\n }\n };\n function maybeUnescapeQuote() {\n const nextChar = path[index + 1];\n if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&\n nextChar === \"'\" /* PathCharTypes.SINGLE_QUOTE */) ||\n (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&\n nextChar === \"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */)) {\n index++;\n newChar = '\\\\' + nextChar;\n actions[0 /* Actions.APPEND */]();\n return true;\n }\n }\n while (mode !== null) {\n index++;\n c = path[index];\n if (c === '\\\\' && maybeUnescapeQuote()) {\n continue;\n }\n type = getPathCharType(c);\n typeMap = pathStateMachine[mode];\n transition = typeMap[type] || typeMap[\"l\" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;\n // check parse error\n if (transition === 8 /* States.ERROR */) {\n return;\n }\n mode = transition[0];\n if (transition[1] !== undefined) {\n action = actions[transition[1]];\n if (action) {\n newChar = c;\n if (action() === false) {\n return;\n }\n }\n }\n // check parse finish\n if (mode === 7 /* States.AFTER_PATH */) {\n return keys;\n }\n }\n}\n// path token cache\nconst cache = new Map();\n/**\n * key-value message resolver\n *\n * @remarks\n * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved\n *\n * @param obj - A target object to be resolved with path\n * @param path - A {@link Path | path} to resolve the value of message\n *\n * @returns A resolved {@link PathValue | path value}\n *\n * @VueI18nGeneral\n */\nfunction resolveWithKeyValue(obj, path) {\n return isObject(obj) ? obj[path] : null;\n}\n/**\n * message resolver\n *\n * @remarks\n * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.\n *\n * @param obj - A target object to be resolved with path\n * @param path - A {@link Path | path} to resolve the value of message\n *\n * @returns A resolved {@link PathValue | path value}\n *\n * @VueI18nGeneral\n */\nfunction resolveValue(obj, path) {\n // check object\n if (!isObject(obj)) {\n return null;\n }\n // parse path\n let hit = cache.get(path);\n if (!hit) {\n hit = parse(path);\n if (hit) {\n cache.set(path, hit);\n }\n }\n // check hit\n if (!hit) {\n return null;\n }\n // resolve path value\n const len = hit.length;\n let last = obj;\n let i = 0;\n while (i < len) {\n const val = last[hit[i]];\n if (val === undefined) {\n return null;\n }\n if (isFunction(last)) {\n return null;\n }\n last = val;\n i++;\n }\n return last;\n}\n\nconst DEFAULT_MODIFIER = (str) => str;\nconst DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line\nconst DEFAULT_MESSAGE_DATA_TYPE = 'text';\nconst DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);\nconst DEFAULT_INTERPOLATE = toDisplayString;\nfunction pluralDefault(choice, choicesLength) {\n choice = Math.abs(choice);\n if (choicesLength === 2) {\n // prettier-ignore\n return choice\n ? choice > 1\n ? 1\n : 0\n : 1;\n }\n return choice ? Math.min(choice, 2) : 0;\n}\nfunction getPluralIndex(options) {\n // prettier-ignore\n const index = isNumber(options.pluralIndex)\n ? options.pluralIndex\n : -1;\n // prettier-ignore\n return options.named && (isNumber(options.named.count) || isNumber(options.named.n))\n ? isNumber(options.named.count)\n ? options.named.count\n : isNumber(options.named.n)\n ? options.named.n\n : index\n : index;\n}\nfunction normalizeNamed(pluralIndex, props) {\n if (!props.count) {\n props.count = pluralIndex;\n }\n if (!props.n) {\n props.n = pluralIndex;\n }\n}\nfunction createMessageContext(options = {}) {\n const locale = options.locale;\n const pluralIndex = getPluralIndex(options);\n const pluralRule = isObject(options.pluralRules) &&\n isString(locale) &&\n isFunction(options.pluralRules[locale])\n ? options.pluralRules[locale]\n : pluralDefault;\n const orgPluralRule = isObject(options.pluralRules) &&\n isString(locale) &&\n isFunction(options.pluralRules[locale])\n ? pluralDefault\n : undefined;\n const plural = (messages) => {\n return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];\n };\n const _list = options.list || [];\n const list = (index) => _list[index];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _named = options.named || {};\n isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);\n const named = (key) => _named[key];\n function message(key) {\n // prettier-ignore\n const msg = isFunction(options.messages)\n ? options.messages(key)\n : isObject(options.messages)\n ? options.messages[key]\n : false;\n return !msg\n ? options.parent\n ? options.parent.message(key) // resolve from parent messages\n : DEFAULT_MESSAGE\n : msg;\n }\n const _modifier = (name) => options.modifiers\n ? options.modifiers[name]\n : DEFAULT_MODIFIER;\n const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)\n ? options.processor.normalize\n : DEFAULT_NORMALIZE;\n const interpolate = isPlainObject(options.processor) &&\n isFunction(options.processor.interpolate)\n ? options.processor.interpolate\n : DEFAULT_INTERPOLATE;\n const type = isPlainObject(options.processor) && isString(options.processor.type)\n ? options.processor.type\n : DEFAULT_MESSAGE_DATA_TYPE;\n const linked = (key, ...args) => {\n const [arg1, arg2] = args;\n let type = 'text';\n let modifier = '';\n if (args.length === 1) {\n if (isObject(arg1)) {\n modifier = arg1.modifier || modifier;\n type = arg1.type || type;\n }\n else if (isString(arg1)) {\n modifier = arg1 || modifier;\n }\n }\n else if (args.length === 2) {\n if (isString(arg1)) {\n modifier = arg1 || modifier;\n }\n if (isString(arg2)) {\n type = arg2 || type;\n }\n }\n const ret = message(key)(ctx);\n const msg = \n // The message in vnode resolved with linked are returned as an array by processor.nomalize\n type === 'vnode' && isArray(ret) && modifier\n ? ret[0]\n : ret;\n return modifier ? _modifier(modifier)(msg, type) : msg;\n };\n const ctx = {\n [\"list\" /* HelperNameMap.LIST */]: list,\n [\"named\" /* HelperNameMap.NAMED */]: named,\n [\"plural\" /* HelperNameMap.PLURAL */]: plural,\n [\"linked\" /* HelperNameMap.LINKED */]: linked,\n [\"message\" /* HelperNameMap.MESSAGE */]: message,\n [\"type\" /* HelperNameMap.TYPE */]: type,\n [\"interpolate\" /* HelperNameMap.INTERPOLATE */]: interpolate,\n [\"normalize\" /* HelperNameMap.NORMALIZE */]: normalize,\n [\"values\" /* HelperNameMap.VALUES */]: assign({}, _list, _named)\n };\n return ctx;\n}\n\nlet devtools = null;\nfunction setDevToolsHook(hook) {\n devtools = hook;\n}\nfunction getDevToolsHook() {\n return devtools;\n}\nfunction initI18nDevTools(i18n, version, meta) {\n // TODO: queue if devtools is undefined\n devtools &&\n devtools.emit(\"i18n:init\" /* IntlifyDevToolsHooks.I18nInit */, {\n timestamp: Date.now(),\n i18n,\n version,\n meta\n });\n}\nconst translateDevTools = /* #__PURE__*/ createDevToolsHook(\"function:translate\" /* IntlifyDevToolsHooks.FunctionTranslate */);\nfunction createDevToolsHook(hook) {\n return (payloads) => devtools && devtools.emit(hook, payloads);\n}\n\nconst code$1 = CompileWarnCodes.__EXTEND_POINT__;\nconst inc$1 = incrementer(code$1);\nconst CoreWarnCodes = {\n NOT_FOUND_KEY: code$1, // 2\n FALLBACK_TO_TRANSLATE: inc$1(), // 3\n CANNOT_FORMAT_NUMBER: inc$1(), // 4\n FALLBACK_TO_NUMBER_FORMAT: inc$1(), // 5\n CANNOT_FORMAT_DATE: inc$1(), // 6\n FALLBACK_TO_DATE_FORMAT: inc$1(), // 7\n EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(), // 8\n __EXTEND_POINT__: inc$1() // 9\n};\n/** @internal */\nconst warnMessages = {\n [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,\n [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,\n [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,\n [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`\n};\nfunction getWarnMessage(code, ...args) {\n return format$1(warnMessages[code], ...args);\n}\n\nconst code = CompileErrorCodes.__EXTEND_POINT__;\nconst inc = incrementer(code);\nconst CoreErrorCodes = {\n INVALID_ARGUMENT: code, // 17\n INVALID_DATE_ARGUMENT: inc(), // 18\n INVALID_ISO_DATE_ARGUMENT: inc(), // 19\n NOT_SUPPORT_NON_STRING_MESSAGE: inc(), // 20\n NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(), // 21\n NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(), // 22\n NOT_SUPPORT_LOCALE_TYPE: inc(), // 23\n __EXTEND_POINT__: inc() // 24\n};\nfunction createCoreError(code) {\n return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages } : undefined);\n}\n/** @internal */\nconst errorMessages = {\n [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',\n [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +\n 'Make sure your Date represents a valid date.',\n [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',\n [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'\n};\n\n/** @internal */\nfunction getLocale(context, options) {\n return options.locale != null\n ? resolveLocale(options.locale)\n : resolveLocale(context.locale);\n}\nlet _resolveLocale;\n/** @internal */\nfunction resolveLocale(locale) {\n if (isString(locale)) {\n return locale;\n }\n else {\n if (isFunction(locale)) {\n if (locale.resolvedOnce && _resolveLocale != null) {\n return _resolveLocale;\n }\n else if (locale.constructor.name === 'Function') {\n const resolve = locale();\n if (isPromise(resolve)) {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);\n }\n return (_resolveLocale = resolve);\n }\n else {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);\n }\n }\n else {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);\n }\n }\n}\n/**\n * Fallback with simple implemenation\n *\n * @remarks\n * A fallback locale function implemented with a simple fallback algorithm.\n *\n * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.\n *\n * @param ctx - A {@link CoreContext | context}\n * @param fallback - A {@link FallbackLocale | fallback locale}\n * @param start - A starting {@link Locale | locale}\n *\n * @returns Fallback locales\n *\n * @VueI18nGeneral\n */\nfunction fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars\n) {\n // prettier-ignore\n return [...new Set([\n start,\n ...(isArray(fallback)\n ? fallback\n : isObject(fallback)\n ? Object.keys(fallback)\n : isString(fallback)\n ? [fallback]\n : [start])\n ])];\n}\n/**\n * Fallback with locale chain\n *\n * @remarks\n * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.\n *\n * @param ctx - A {@link CoreContext | context}\n * @param fallback - A {@link FallbackLocale | fallback locale}\n * @param start - A starting {@link Locale | locale}\n *\n * @returns Fallback locales\n *\n * @VueI18nSee [Fallbacking](../guide/essentials/fallback)\n *\n * @VueI18nGeneral\n */\nfunction fallbackWithLocaleChain(ctx, fallback, start) {\n const startLocale = isString(start) ? start : DEFAULT_LOCALE;\n const context = ctx;\n if (!context.__localeChainCache) {\n context.__localeChainCache = new Map();\n }\n let chain = context.__localeChainCache.get(startLocale);\n if (!chain) {\n chain = [];\n // first block defined by start\n let block = [start];\n // while any intervening block found\n while (isArray(block)) {\n block = appendBlockToChain(chain, block, fallback);\n }\n // prettier-ignore\n // last block defined by default\n const defaults = isArray(fallback) || !isPlainObject(fallback)\n ? fallback\n : fallback['default']\n ? fallback['default']\n : null;\n // convert defaults to array\n block = isString(defaults) ? [defaults] : defaults;\n if (isArray(block)) {\n appendBlockToChain(chain, block, false);\n }\n context.__localeChainCache.set(startLocale, chain);\n }\n return chain;\n}\nfunction appendBlockToChain(chain, block, blocks) {\n let follow = true;\n for (let i = 0; i < block.length && isBoolean(follow); i++) {\n const locale = block[i];\n if (isString(locale)) {\n follow = appendLocaleToChain(chain, block[i], blocks);\n }\n }\n return follow;\n}\nfunction appendLocaleToChain(chain, locale, blocks) {\n let follow;\n const tokens = locale.split('-');\n do {\n const target = tokens.join('-');\n follow = appendItemToChain(chain, target, blocks);\n tokens.splice(-1, 1);\n } while (tokens.length && follow === true);\n return follow;\n}\nfunction appendItemToChain(chain, target, blocks) {\n let follow = false;\n if (!chain.includes(target)) {\n follow = true;\n if (target) {\n follow = target[target.length - 1] !== '!';\n const locale = target.replace(/!/g, '');\n chain.push(locale);\n if ((isArray(blocks) || isPlainObject(blocks)) &&\n blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n follow = blocks[locale];\n }\n }\n }\n return follow;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Intlify core-base version\n * @internal\n */\nconst VERSION = '9.13.1';\nconst NOT_REOSLVED = -1;\nconst DEFAULT_LOCALE = 'en-US';\nconst MISSING_RESOLVE_VALUE = '';\nconst capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;\nfunction getDefaultLinkedModifiers() {\n return {\n upper: (val, type) => {\n // prettier-ignore\n return type === 'text' && isString(val)\n ? val.toUpperCase()\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? val.children.toUpperCase()\n : val;\n },\n lower: (val, type) => {\n // prettier-ignore\n return type === 'text' && isString(val)\n ? val.toLowerCase()\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? val.children.toLowerCase()\n : val;\n },\n capitalize: (val, type) => {\n // prettier-ignore\n return (type === 'text' && isString(val)\n ? capitalize(val)\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? capitalize(val.children)\n : val);\n }\n };\n}\nlet _compiler;\nfunction registerMessageCompiler(compiler) {\n _compiler = compiler;\n}\nlet _resolver;\n/**\n * Register the message resolver\n *\n * @param resolver - A {@link MessageResolver} function\n *\n * @VueI18nGeneral\n */\nfunction registerMessageResolver(resolver) {\n _resolver = resolver;\n}\nlet _fallbacker;\n/**\n * Register the locale fallbacker\n *\n * @param fallbacker - A {@link LocaleFallbacker} function\n *\n * @VueI18nGeneral\n */\nfunction registerLocaleFallbacker(fallbacker) {\n _fallbacker = fallbacker;\n}\n// Additional Meta for Intlify DevTools\nlet _additionalMeta = null;\n/* #__NO_SIDE_EFFECTS__ */\nconst setAdditionalMeta = (meta) => {\n _additionalMeta = meta;\n};\n/* #__NO_SIDE_EFFECTS__ */\nconst getAdditionalMeta = () => _additionalMeta;\nlet _fallbackContext = null;\nconst setFallbackContext = (context) => {\n _fallbackContext = context;\n};\nconst getFallbackContext = () => _fallbackContext;\n// ID for CoreContext\nlet _cid = 0;\nfunction createCoreContext(options = {}) {\n // setup options\n const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;\n const version = isString(options.version) ? options.version : VERSION;\n const locale = isString(options.locale) || isFunction(options.locale)\n ? options.locale\n : DEFAULT_LOCALE;\n const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;\n const fallbackLocale = isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n isString(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale;\n const messages = isPlainObject(options.messages)\n ? options.messages\n : { [_locale]: {} };\n const datetimeFormats = isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale]: {} }\n ;\n const numberFormats = isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale]: {} }\n ;\n const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());\n const pluralRules = options.pluralRules || {};\n const missing = isFunction(options.missing) ? options.missing : null;\n const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n const fallbackFormat = !!options.fallbackFormat;\n const unresolving = !!options.unresolving;\n const postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n const processor = isPlainObject(options.processor) ? options.processor : null;\n const warnHtmlMessage = isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n const escapeParameter = !!options.escapeParameter;\n const messageCompiler = isFunction(options.messageCompiler)\n ? options.messageCompiler\n : _compiler;\n if ((process.env.NODE_ENV !== 'production') &&\n !false &&\n !false &&\n isFunction(options.messageCompiler)) {\n warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));\n }\n const messageResolver = isFunction(options.messageResolver)\n ? options.messageResolver\n : _resolver || resolveWithKeyValue;\n const localeFallbacker = isFunction(options.localeFallbacker)\n ? options.localeFallbacker\n : _fallbacker || fallbackWithSimple;\n const fallbackContext = isObject(options.fallbackContext)\n ? options.fallbackContext\n : undefined;\n // setup internal options\n const internalOptions = options;\n const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)\n ? internalOptions.__datetimeFormatters\n : new Map()\n ;\n const __numberFormatters = isObject(internalOptions.__numberFormatters)\n ? internalOptions.__numberFormatters\n : new Map()\n ;\n const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};\n _cid++;\n const context = {\n version,\n cid: _cid,\n locale,\n fallbackLocale,\n messages,\n modifiers,\n pluralRules,\n missing,\n missingWarn,\n fallbackWarn,\n fallbackFormat,\n unresolving,\n postTranslation,\n processor,\n warnHtmlMessage,\n escapeParameter,\n messageCompiler,\n messageResolver,\n localeFallbacker,\n fallbackContext,\n onWarn,\n __meta\n };\n {\n context.datetimeFormats = datetimeFormats;\n context.numberFormats = numberFormats;\n context.__datetimeFormatters = __datetimeFormatters;\n context.__numberFormatters = __numberFormatters;\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n context.__v_emitter =\n internalOptions.__v_emitter != null\n ? internalOptions.__v_emitter\n : undefined;\n }\n // NOTE: experimental !!\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n initI18nDevTools(context, version, __meta);\n }\n return context;\n}\n/** @internal */\nfunction isTranslateFallbackWarn(fallback, key) {\n return fallback instanceof RegExp ? fallback.test(key) : fallback;\n}\n/** @internal */\nfunction isTranslateMissingWarn(missing, key) {\n return missing instanceof RegExp ? missing.test(key) : missing;\n}\n/** @internal */\nfunction handleMissing(context, key, locale, missingWarn, type) {\n const { missing, onWarn } = context;\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"missing\" /* VueDevToolsTimelineEvents.MISSING */, {\n locale,\n key,\n type,\n groupId: `${type}:${key}`\n });\n }\n }\n if (missing !== null) {\n const ret = missing(context, locale, key, type);\n return isString(ret) ? ret : key;\n }\n else {\n if ((process.env.NODE_ENV !== 'production') && isTranslateMissingWarn(missingWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));\n }\n return key;\n }\n}\n/** @internal */\nfunction updateFallbackLocale(ctx, locale, fallback) {\n const context = ctx;\n context.__localeChainCache = new Map();\n ctx.localeFallbacker(ctx, fallback, locale);\n}\n/** @internal */\nfunction isAlmostSameLocale(locale, compareLocale) {\n if (locale === compareLocale)\n return false;\n return locale.split('-')[0] === compareLocale.split('-')[0];\n}\n/** @internal */\nfunction isImplicitFallback(targetLocale, locales) {\n const index = locales.indexOf(targetLocale);\n if (index === -1) {\n return false;\n }\n for (let i = index + 1; i < locales.length; i++) {\n if (isAlmostSameLocale(targetLocale, locales[i])) {\n return true;\n }\n }\n return false;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction format(ast) {\n const msg = (ctx) => formatParts(ctx, ast);\n return msg;\n}\nfunction formatParts(ctx, ast) {\n const body = ast.b || ast.body;\n if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {\n const plural = body;\n const cases = plural.c || plural.cases;\n return ctx.plural(cases.reduce((messages, c) => [\n ...messages,\n formatMessageParts(ctx, c)\n ], []));\n }\n else {\n return formatMessageParts(ctx, body);\n }\n}\nfunction formatMessageParts(ctx, node) {\n const _static = node.s || node.static;\n if (_static) {\n return ctx.type === 'text'\n ? _static\n : ctx.normalize([_static]);\n }\n else {\n const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);\n return ctx.normalize(messages);\n }\n}\nfunction formatMessagePart(ctx, node) {\n const type = node.t || node.type;\n switch (type) {\n case 3 /* NodeTypes.Text */: {\n const text = node;\n return (text.v || text.value);\n }\n case 9 /* NodeTypes.Literal */: {\n const literal = node;\n return (literal.v || literal.value);\n }\n case 4 /* NodeTypes.Named */: {\n const named = node;\n return ctx.interpolate(ctx.named(named.k || named.key));\n }\n case 5 /* NodeTypes.List */: {\n const list = node;\n return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));\n }\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n const modifier = linked.m || linked.modifier;\n return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);\n }\n case 7 /* NodeTypes.LinkedKey */: {\n const linkedKey = node;\n return (linkedKey.v || linkedKey.value);\n }\n case 8 /* NodeTypes.LinkedModifier */: {\n const linkedModifier = node;\n return (linkedModifier.v || linkedModifier.value);\n }\n default:\n throw new Error(`unhandled node type on format message part: ${type}`);\n }\n}\n\nconst WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;\nfunction checkHtmlMessage(source, warnHtmlMessage) {\n if (warnHtmlMessage && detectHtmlTag(source)) {\n warn(format$1(WARN_MESSAGE, { source }));\n }\n}\nconst defaultOnCacheKey = (message) => message;\nlet compileCache = Object.create(null);\nfunction onCompileWarn(_warn) {\n if (_warn.code === CompileWarnCodes.USE_MODULO_SYNTAX) {\n warn(`The use of named interpolation with modulo syntax is deprecated. ` +\n `It will be removed in v10.\\n` +\n `reference: https://vue-i18n.intlify.dev/guide/essentials/syntax#rails-i18n-format \\n` +\n `(message compiler warning message: ${_warn.message})`);\n }\n}\nfunction clearCompileCache() {\n compileCache = Object.create(null);\n}\nconst isMessageAST = (val) => isObject(val) &&\n (val.t === 0 || val.type === 0) &&\n ('b' in val || 'body' in val);\nfunction baseCompile(message, options = {}) {\n // error detecting on compile\n let detectError = false;\n const onError = options.onError || defaultOnError;\n options.onError = (err) => {\n detectError = true;\n onError(err);\n };\n // compile with mesasge-compiler\n return { ...baseCompile$1(message, options), detectError };\n}\n/* #__NO_SIDE_EFFECTS__ */\nconst compileToFunction = (message, context) => {\n if (!isString(message)) {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);\n }\n // set onWarn\n if ((process.env.NODE_ENV !== 'production')) {\n context.onWarn = onCompileWarn;\n }\n {\n // check HTML message\n const warnHtmlMessage = isBoolean(context.warnHtmlMessage)\n ? context.warnHtmlMessage\n : true;\n (process.env.NODE_ENV !== 'production') && checkHtmlMessage(message, warnHtmlMessage);\n // check caches\n const onCacheKey = context.onCacheKey || defaultOnCacheKey;\n const cacheKey = onCacheKey(message);\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compile\n const { code, detectError } = baseCompile(message, context);\n // evaluate function\n const msg = new Function(`return ${code}`)();\n // if occurred compile error, don't cache\n return !detectError\n ? (compileCache[cacheKey] = msg)\n : msg;\n }\n};\nfunction compile(message, context) {\n // set onWarn\n if ((process.env.NODE_ENV !== 'production')) {\n context.onWarn = onCompileWarn;\n }\n if (((__INTLIFY_JIT_COMPILATION__ && !__INTLIFY_DROP_MESSAGE_COMPILER__)) &&\n isString(message)) {\n // check HTML message\n const warnHtmlMessage = isBoolean(context.warnHtmlMessage)\n ? context.warnHtmlMessage\n : true;\n (process.env.NODE_ENV !== 'production') && checkHtmlMessage(message, warnHtmlMessage);\n // check caches\n const onCacheKey = context.onCacheKey || defaultOnCacheKey;\n const cacheKey = onCacheKey(message);\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compile with JIT mode\n const { ast, detectError } = baseCompile(message, {\n ...context,\n location: (process.env.NODE_ENV !== 'production'),\n jit: true\n });\n // compose message function from AST\n const msg = format(ast);\n // if occurred compile error, don't cache\n return !detectError\n ? (compileCache[cacheKey] = msg)\n : msg;\n }\n else {\n if ((process.env.NODE_ENV !== 'production') && !isMessageAST(message)) {\n warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);\n return (() => message);\n }\n // AST case (passed from bundler)\n const cacheKey = message.cacheKey;\n if (cacheKey) {\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compose message function from message (AST)\n return (compileCache[cacheKey] =\n format(message));\n }\n else {\n return format(message);\n }\n }\n}\n\nconst NOOP_MESSAGE_FUNCTION = () => '';\nconst isMessageFunction = (val) => isFunction(val);\n// implementation of `translate` function\nfunction translate(context, ...args) {\n const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;\n const [key, options] = parseTranslateArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const escapeParameter = isBoolean(options.escapeParameter)\n ? options.escapeParameter\n : context.escapeParameter;\n const resolvedMessage = !!options.resolvedMessage;\n // prettier-ignore\n const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option\n ? !isBoolean(options.default)\n ? options.default\n : (!messageCompiler ? () => key : key)\n : fallbackFormat // default by `fallbackFormat` option\n ? (!messageCompiler ? () => key : key)\n : '';\n const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';\n const locale = getLocale(context, options);\n // escape params\n escapeParameter && escapeParams(options);\n // resolve message format\n // eslint-disable-next-line prefer-const\n let [formatScope, targetLocale, message] = !resolvedMessage\n ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)\n : [\n key,\n locale,\n messages[locale] || {}\n ];\n // NOTE:\n // Fix to work around `ssrTransfrom` bug in Vite.\n // https://github.com/vitejs/vite/issues/4306\n // To get around this, use temporary variables.\n // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243\n let format = formatScope;\n // if you use default message, set it as message format!\n let cacheBaseKey = key;\n if (!resolvedMessage &&\n !(isString(format) ||\n isMessageAST(format) ||\n isMessageFunction(format))) {\n if (enableDefaultMsg) {\n format = defaultMsgOrKey;\n cacheBaseKey = format;\n }\n }\n // checking message format and target locale\n if (!resolvedMessage &&\n (!(isString(format) ||\n isMessageAST(format) ||\n isMessageFunction(format)) ||\n !isString(targetLocale))) {\n return unresolving ? NOT_REOSLVED : key;\n }\n // TODO: refactor\n if ((process.env.NODE_ENV !== 'production') && isString(format) && context.messageCompiler == null) {\n warn(`The message format compilation is not supported in this build. ` +\n `Because message compiler isn't included. ` +\n `You need to pre-compilation all message format. ` +\n `So translate function return '${key}'.`);\n return key;\n }\n // setup compile error detecting\n let occurred = false;\n const onError = () => {\n occurred = true;\n };\n // compile message format\n const msg = !isMessageFunction(format)\n ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)\n : format;\n // if occurred compile error, return the message format\n if (occurred) {\n return format;\n }\n // evaluate message with context\n const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);\n const msgContext = createMessageContext(ctxOptions);\n const messaged = evaluateMessage(context, msg, msgContext);\n // if use post translation option, proceed it with handler\n const ret = postTranslation\n ? postTranslation(messaged, key)\n : messaged;\n // NOTE: experimental !!\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n // prettier-ignore\n const payloads = {\n timestamp: Date.now(),\n key: isString(key)\n ? key\n : isMessageFunction(format)\n ? format.key\n : '',\n locale: targetLocale || (isMessageFunction(format)\n ? format.locale\n : ''),\n format: isString(format)\n ? format\n : isMessageFunction(format)\n ? format.source\n : '',\n message: ret\n };\n payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});\n translateDevTools(payloads);\n }\n return ret;\n}\nfunction escapeParams(options) {\n if (isArray(options.list)) {\n options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);\n }\n else if (isObject(options.named)) {\n Object.keys(options.named).forEach(key => {\n if (isString(options.named[key])) {\n options.named[key] = escapeHtml(options.named[key]);\n }\n });\n }\n}\nfunction resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {\n const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;\n const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any\n let message = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'translate';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n !isAlmostSameLocale(locale, targetLocale) &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n message =\n messages[targetLocale] || {};\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-resolve-start';\n endTag = 'intlify-message-resolve-end';\n mark && mark(startTag);\n }\n if ((format = resolveValue(message, key)) === null) {\n // if null, resolve with object key path\n format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start && format) {\n emitter.emit(\"message-resolve\" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {\n type: \"message-resolve\" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,\n key,\n message: format,\n time: end - start,\n groupId: `${type}:${key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message resolve', startTag, endTag);\n }\n }\n if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {\n break;\n }\n if (!isImplicitFallback(targetLocale, locales)) {\n const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n key, targetLocale, missingWarn, type);\n if (missingRet !== key) {\n format = missingRet;\n }\n }\n from = to;\n }\n return [format, targetLocale, message];\n}\nfunction compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {\n const { messageCompiler, warnHtmlMessage } = context;\n if (isMessageFunction(format)) {\n const msg = format;\n msg.locale = msg.locale || targetLocale;\n msg.key = msg.key || key;\n return msg;\n }\n if (messageCompiler == null) {\n const msg = (() => format);\n msg.locale = targetLocale;\n msg.key = key;\n return msg;\n }\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-compilation-start';\n endTag = 'intlify-message-compilation-end';\n mark && mark(startTag);\n }\n const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start) {\n emitter.emit(\"message-compilation\" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {\n type: \"message-compilation\" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,\n message: format,\n time: end - start,\n groupId: `${'translate'}:${key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message compilation', startTag, endTag);\n }\n }\n msg.locale = targetLocale;\n msg.key = key;\n msg.source = format;\n return msg;\n}\nfunction evaluateMessage(context, msg, msgCtx) {\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-evaluation-start';\n endTag = 'intlify-message-evaluation-end';\n mark && mark(startTag);\n }\n const messaged = msg(msgCtx);\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start) {\n emitter.emit(\"message-evaluation\" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {\n type: \"message-evaluation\" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,\n value: messaged,\n time: end - start,\n groupId: `${'translate'}:${msg.key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message evaluation', startTag, endTag);\n }\n }\n return messaged;\n}\n/** @internal */\nfunction parseTranslateArgs(...args) {\n const [arg1, arg2, arg3] = args;\n const options = {};\n if (!isString(arg1) &&\n !isNumber(arg1) &&\n !isMessageFunction(arg1) &&\n !isMessageAST(arg1)) {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n // prettier-ignore\n const key = isNumber(arg1)\n ? String(arg1)\n : isMessageFunction(arg1)\n ? arg1\n : arg1;\n if (isNumber(arg2)) {\n options.plural = arg2;\n }\n else if (isString(arg2)) {\n options.default = arg2;\n }\n else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {\n options.named = arg2;\n }\n else if (isArray(arg2)) {\n options.list = arg2;\n }\n if (isNumber(arg3)) {\n options.plural = arg3;\n }\n else if (isString(arg3)) {\n options.default = arg3;\n }\n else if (isPlainObject(arg3)) {\n assign(options, arg3);\n }\n return [key, options];\n}\nfunction getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {\n return {\n locale,\n key,\n warnHtmlMessage,\n onError: (err) => {\n onError && onError(err);\n if ((process.env.NODE_ENV !== 'production')) {\n const _source = getSourceForCodeFrame(source);\n const message = `Message compilation error: ${err.message}`;\n const codeFrame = err.location &&\n _source &&\n generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);\n const emitter = context.__v_emitter;\n if (emitter && _source) {\n emitter.emit(\"compile-error\" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {\n message: _source,\n error: err.message,\n start: err.location && err.location.start.offset,\n end: err.location && err.location.end.offset,\n groupId: `${'translate'}:${key}`\n });\n }\n console.error(codeFrame ? `${message}\\n${codeFrame}` : message);\n }\n else {\n throw err;\n }\n },\n onCacheKey: (source) => generateFormatCacheKey(locale, key, source)\n };\n}\nfunction getSourceForCodeFrame(source) {\n if (isString(source)) {\n return source;\n }\n else {\n if (source.loc && source.loc.source) {\n return source.loc.source;\n }\n }\n}\nfunction getMessageContextOptions(context, locale, message, options) {\n const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;\n const resolveMessage = (key) => {\n let val = resolveValue(message, key);\n // fallback to root context\n if (val == null && fallbackContext) {\n const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);\n val = resolveValue(message, key);\n }\n if (isString(val) || isMessageAST(val)) {\n let occurred = false;\n const onError = () => {\n occurred = true;\n };\n const msg = compileMessageFormat(context, key, locale, val, key, onError);\n return !occurred\n ? msg\n : NOOP_MESSAGE_FUNCTION;\n }\n else if (isMessageFunction(val)) {\n return val;\n }\n else {\n // TODO: should be implemented warning message\n return NOOP_MESSAGE_FUNCTION;\n }\n };\n const ctxOptions = {\n locale,\n modifiers,\n pluralRules,\n messages: resolveMessage\n };\n if (context.processor) {\n ctxOptions.processor = context.processor;\n }\n if (options.list) {\n ctxOptions.list = options.list;\n }\n if (options.named) {\n ctxOptions.named = options.named;\n }\n if (isNumber(options.plural)) {\n ctxOptions.pluralIndex = options.plural;\n }\n return ctxOptions;\n}\n\nconst intlDefined = typeof Intl !== 'undefined';\nconst Availabilities = {\n dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',\n numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'\n};\n\n// implementation of `datetime` function\nfunction datetime(context, ...args) {\n const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;\n const { __datetimeFormatters } = context;\n if ((process.env.NODE_ENV !== 'production') && !Availabilities.dateTimeFormat) {\n onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));\n return MISSING_RESOLVE_VALUE;\n }\n const [key, value, options, overrides] = parseDateTimeArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const part = !!options.part;\n const locale = getLocale(context, options);\n const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n fallbackLocale, locale);\n if (!isString(key) || key === '') {\n return new Intl.DateTimeFormat(locale, overrides).format(value);\n }\n // resolve format\n let datetimeFormat = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'datetime format';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n datetimeFormat =\n datetimeFormats[targetLocale] || {};\n format = datetimeFormat[key];\n if (isPlainObject(format))\n break;\n handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any\n from = to;\n }\n // checking format and target locale\n if (!isPlainObject(format) || !isString(targetLocale)) {\n return unresolving ? NOT_REOSLVED : key;\n }\n let id = `${targetLocale}__${key}`;\n if (!isEmptyObject(overrides)) {\n id = `${id}__${JSON.stringify(overrides)}`;\n }\n let formatter = __datetimeFormatters.get(id);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));\n __datetimeFormatters.set(id, formatter);\n }\n return !part ? formatter.format(value) : formatter.formatToParts(value);\n}\n/** @internal */\nconst DATETIME_FORMAT_OPTIONS_KEYS = [\n 'localeMatcher',\n 'weekday',\n 'era',\n 'year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'timeZoneName',\n 'formatMatcher',\n 'hour12',\n 'timeZone',\n 'dateStyle',\n 'timeStyle',\n 'calendar',\n 'dayPeriod',\n 'numberingSystem',\n 'hourCycle',\n 'fractionalSecondDigits'\n];\n/** @internal */\nfunction parseDateTimeArgs(...args) {\n const [arg1, arg2, arg3, arg4] = args;\n const options = {};\n let overrides = {};\n let value;\n if (isString(arg1)) {\n // Only allow ISO strings - other date formats are often supported,\n // but may cause different results in different browsers.\n const matches = arg1.match(/(\\d{4}-\\d{2}-\\d{2})(T|\\s)?(.*)/);\n if (!matches) {\n throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);\n }\n // Some browsers can not parse the iso datetime separated by space,\n // this is a compromise solution by replace the 'T'/' ' with 'T'\n const dateTime = matches[3]\n ? matches[3].trim().startsWith('T')\n ? `${matches[1].trim()}${matches[3].trim()}`\n : `${matches[1].trim()}T${matches[3].trim()}`\n : matches[1].trim();\n value = new Date(dateTime);\n try {\n // This will fail if the date is not valid\n value.toISOString();\n }\n catch (e) {\n throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);\n }\n }\n else if (isDate(arg1)) {\n if (isNaN(arg1.getTime())) {\n throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);\n }\n value = arg1;\n }\n else if (isNumber(arg1)) {\n value = arg1;\n }\n else {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n if (isString(arg2)) {\n options.key = arg2;\n }\n else if (isPlainObject(arg2)) {\n Object.keys(arg2).forEach(key => {\n if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {\n overrides[key] = arg2[key];\n }\n else {\n options[key] = arg2[key];\n }\n });\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isPlainObject(arg3)) {\n overrides = arg3;\n }\n if (isPlainObject(arg4)) {\n overrides = arg4;\n }\n return [options.key || '', value, options, overrides];\n}\n/** @internal */\nfunction clearDateTimeFormat(ctx, locale, format) {\n const context = ctx;\n for (const key in format) {\n const id = `${locale}__${key}`;\n if (!context.__datetimeFormatters.has(id)) {\n continue;\n }\n context.__datetimeFormatters.delete(id);\n }\n}\n\n// implementation of `number` function\nfunction number(context, ...args) {\n const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;\n const { __numberFormatters } = context;\n if ((process.env.NODE_ENV !== 'production') && !Availabilities.numberFormat) {\n onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));\n return MISSING_RESOLVE_VALUE;\n }\n const [key, value, options, overrides] = parseNumberArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const part = !!options.part;\n const locale = getLocale(context, options);\n const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n fallbackLocale, locale);\n if (!isString(key) || key === '') {\n return new Intl.NumberFormat(locale, overrides).format(value);\n }\n // resolve format\n let numberFormat = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'number format';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n numberFormat =\n numberFormats[targetLocale] || {};\n format = numberFormat[key];\n if (isPlainObject(format))\n break;\n handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any\n from = to;\n }\n // checking format and target locale\n if (!isPlainObject(format) || !isString(targetLocale)) {\n return unresolving ? NOT_REOSLVED : key;\n }\n let id = `${targetLocale}__${key}`;\n if (!isEmptyObject(overrides)) {\n id = `${id}__${JSON.stringify(overrides)}`;\n }\n let formatter = __numberFormatters.get(id);\n if (!formatter) {\n formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));\n __numberFormatters.set(id, formatter);\n }\n return !part ? formatter.format(value) : formatter.formatToParts(value);\n}\n/** @internal */\nconst NUMBER_FORMAT_OPTIONS_KEYS = [\n 'localeMatcher',\n 'style',\n 'currency',\n 'currencyDisplay',\n 'currencySign',\n 'useGrouping',\n 'minimumIntegerDigits',\n 'minimumFractionDigits',\n 'maximumFractionDigits',\n 'minimumSignificantDigits',\n 'maximumSignificantDigits',\n 'compactDisplay',\n 'notation',\n 'signDisplay',\n 'unit',\n 'unitDisplay',\n 'roundingMode',\n 'roundingPriority',\n 'roundingIncrement',\n 'trailingZeroDisplay'\n];\n/** @internal */\nfunction parseNumberArgs(...args) {\n const [arg1, arg2, arg3, arg4] = args;\n const options = {};\n let overrides = {};\n if (!isNumber(arg1)) {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n const value = arg1;\n if (isString(arg2)) {\n options.key = arg2;\n }\n else if (isPlainObject(arg2)) {\n Object.keys(arg2).forEach(key => {\n if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {\n overrides[key] = arg2[key];\n }\n else {\n options[key] = arg2[key];\n }\n });\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isPlainObject(arg3)) {\n overrides = arg3;\n }\n if (isPlainObject(arg4)) {\n overrides = arg4;\n }\n return [options.key || '', value, options, overrides];\n}\n/** @internal */\nfunction clearNumberFormat(ctx, locale, format) {\n const context = ctx;\n for (const key in format) {\n const id = `${locale}__${key}`;\n if (!context.__numberFormatters.has(id)) {\n continue;\n }\n context.__numberFormatters.delete(id);\n }\n}\n\n{\n initFeatureFlags();\n}\n\nexport { CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, compileToFunction, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };\n","/*!\n * vue-i18n v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nimport { getGlobalThis, incrementer, format, makeSymbol, isPlainObject, isArray, deepCopy, isString, hasOwn, isObject, warn, warnOnce, isBoolean, isRegExp, isFunction, inBrowser, assign, isNumber, createEmitter, isEmptyObject } from '@intlify/shared';\nimport { CoreWarnCodes, CoreErrorCodes, createCompileError, DEFAULT_LOCALE, updateFallbackLocale, setFallbackContext, createCoreContext, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, getFallbackContext, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, isMessageAST, isMessageFunction, fallbackWithLocaleChain, NUMBER_FORMAT_OPTIONS_KEYS, DATETIME_FORMAT_OPTIONS_KEYS, registerMessageCompiler, compile, compileToFunction, registerMessageResolver, resolveValue, registerLocaleFallbacker, setDevToolsHook } from '@intlify/core-base';\nimport { createVNode, Text, computed, watch, getCurrentInstance, ref, shallowRef, Fragment, defineComponent, h, effectScope, inject, onMounted, onUnmounted, onBeforeMount, isRef } from 'vue';\nimport { setupDevtoolsPlugin } from '@vue/devtools-api';\n\n/**\n * Vue I18n Version\n *\n * @remarks\n * Semver format. Same format as the package.json `version` field.\n *\n * @VueI18nGeneral\n */\nconst VERSION = '9.13.1';\n/**\n * This is only called in esm-bundler builds.\n * istanbul-ignore-next\n */\nfunction initFeatureFlags() {\n if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {\n getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;\n }\n if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {\n getGlobalThis().__VUE_I18N_LEGACY_API__ = true;\n }\n if (typeof __INTLIFY_JIT_COMPILATION__ !== 'boolean') {\n getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;\n }\n if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {\n getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;\n }\n if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {\n getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;\n }\n}\n\nconst code$1 = CoreWarnCodes.__EXTEND_POINT__;\nconst inc$1 = incrementer(code$1);\nconst I18nWarnCodes = {\n FALLBACK_TO_ROOT: code$1, // 9\n NOT_SUPPORTED_PRESERVE: inc$1(), // 10\n NOT_SUPPORTED_FORMATTER: inc$1(), // 11\n NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(), // 12\n NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(), // 13\n COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(), // 14\n NOT_FOUND_PARENT_SCOPE: inc$1(), // 15\n IGNORE_OBJ_FLATTEN: inc$1(), // 16\n NOTICE_DROP_ALLOW_COMPOSITION: inc$1(), // 17\n NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG: inc$1() // 18\n};\nconst warnMessages = {\n [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,\n [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,\n [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,\n [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,\n [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,\n [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,\n [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,\n [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,\n [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`,\n [I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG]: `'translateExistCompatible' option will be dropped in the next major version.`\n};\nfunction getWarnMessage(code, ...args) {\n return format(warnMessages[code], ...args);\n}\n\nconst code = CoreErrorCodes.__EXTEND_POINT__;\nconst inc = incrementer(code);\nconst I18nErrorCodes = {\n // composer module errors\n UNEXPECTED_RETURN_TYPE: code, // 24\n // legacy module errors\n INVALID_ARGUMENT: inc(), // 25\n // i18n module errors\n MUST_BE_CALL_SETUP_TOP: inc(), // 26\n NOT_INSTALLED: inc(), // 27\n NOT_AVAILABLE_IN_LEGACY_MODE: inc(), // 28\n // directive module errors\n REQUIRED_VALUE: inc(), // 29\n INVALID_VALUE: inc(), // 30\n // vue-devtools errors\n CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(), // 31\n NOT_INSTALLED_WITH_PROVIDE: inc(), // 32\n // unexpected error\n UNEXPECTED_ERROR: inc(), // 33\n // not compatible legacy vue-i18n constructor\n NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(), // 34\n // bridge support vue 2.x only\n BRIDGE_SUPPORT_VUE_2_ONLY: inc(), // 35\n // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``\n MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(), // 36\n // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly\n NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(), // 37\n // for enhancement\n __EXTEND_POINT__: inc() // 38\n};\nfunction createI18nError(code, ...args) {\n return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);\n}\nconst errorMessages = {\n [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',\n [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',\n [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',\n [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',\n [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',\n [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',\n [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,\n [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,\n [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,\n [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',\n [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',\n [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',\n [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',\n [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'\n};\n\nconst TranslateVNodeSymbol = \n/* #__PURE__*/ makeSymbol('__translateVNode');\nconst DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');\nconst NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');\nconst EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');\nconst DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');\nconst SetPluralRulesSymbol = makeSymbol('__setPluralRules');\nmakeSymbol('__intlifyMeta');\nconst InejctWithOptionSymbol = \n/* #__PURE__*/ makeSymbol('__injectWithOption');\nconst DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');\nconst __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Transform flat json in obj to normal json in obj\n */\nfunction handleFlatJson(obj) {\n // check obj\n if (!isObject(obj)) {\n return obj;\n }\n for (const key in obj) {\n // check key\n if (!hasOwn(obj, key)) {\n continue;\n }\n // handle for normal json\n if (!key.includes('.')) {\n // recursive process value if value is also a object\n if (isObject(obj[key])) {\n handleFlatJson(obj[key]);\n }\n }\n // handle for flat json, transform to normal json\n else {\n // go to the last object\n const subKeys = key.split('.');\n const lastIndex = subKeys.length - 1;\n let currentObj = obj;\n let hasStringValue = false;\n for (let i = 0; i < lastIndex; i++) {\n if (!(subKeys[i] in currentObj)) {\n currentObj[subKeys[i]] = {};\n }\n if (!isObject(currentObj[subKeys[i]])) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {\n key: subKeys[i]\n }));\n hasStringValue = true;\n break;\n }\n currentObj = currentObj[subKeys[i]];\n }\n // update last object value, delete old property\n if (!hasStringValue) {\n currentObj[subKeys[lastIndex]] = obj[key];\n delete obj[key];\n }\n // recursive process value if value is also a object\n if (isObject(currentObj[subKeys[lastIndex]])) {\n handleFlatJson(currentObj[subKeys[lastIndex]]);\n }\n }\n }\n return obj;\n}\nfunction getLocaleMessages(locale, options) {\n const { messages, __i18n, messageResolver, flatJson } = options;\n // prettier-ignore\n const ret = (isPlainObject(messages)\n ? messages\n : isArray(__i18n)\n ? {}\n : { [locale]: {} });\n // merge locale messages of i18n custom block\n if (isArray(__i18n)) {\n __i18n.forEach(custom => {\n if ('locale' in custom && 'resource' in custom) {\n const { locale, resource } = custom;\n if (locale) {\n ret[locale] = ret[locale] || {};\n deepCopy(resource, ret[locale]);\n }\n else {\n deepCopy(resource, ret);\n }\n }\n else {\n isString(custom) && deepCopy(JSON.parse(custom), ret);\n }\n });\n }\n // handle messages for flat json\n if (messageResolver == null && flatJson) {\n for (const key in ret) {\n if (hasOwn(ret, key)) {\n handleFlatJson(ret[key]);\n }\n }\n }\n return ret;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getComponentOptions(instance) {\n return instance.type ;\n}\nfunction adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n let messages = isObject(options.messages) ? options.messages : {};\n if ('__i18nGlobal' in componentOptions) {\n messages = getLocaleMessages(gl.locale.value, {\n messages,\n __i18n: componentOptions.__i18nGlobal\n });\n }\n // merge locale messages\n const locales = Object.keys(messages);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeLocaleMessage(locale, messages[locale]);\n });\n }\n {\n // merge datetime formats\n if (isObject(options.datetimeFormats)) {\n const locales = Object.keys(options.datetimeFormats);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);\n });\n }\n }\n // merge number formats\n if (isObject(options.numberFormats)) {\n const locales = Object.keys(options.numberFormats);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeNumberFormat(locale, options.numberFormats[locale]);\n });\n }\n }\n }\n}\nfunction createTextNode(key) {\n return createVNode(Text, null, key, 0)\n ;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// extend VNode interface\nconst DEVTOOLS_META = '__INTLIFY_META__';\nconst NOOP_RETURN_ARRAY = () => [];\nconst NOOP_RETURN_FALSE = () => false;\nlet composerID = 0;\nfunction defineCoreMissingHandler(missing) {\n return ((ctx, locale, key, type) => {\n return missing(locale, key, getCurrentInstance() || undefined, type);\n });\n}\n// for Intlify DevTools\n/* #__NO_SIDE_EFFECTS__ */\nconst getMetaInfo = () => {\n const instance = getCurrentInstance();\n let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any\n return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])\n ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any\n : null;\n};\n/**\n * Create composer interface factory\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction createComposer(options = {}, VueI18nLegacy) {\n const { __root, __injectWithOption } = options;\n const _isGlobal = __root === undefined;\n const flatJson = options.flatJson;\n const _ref = inBrowser ? ref : shallowRef;\n const translateExistCompatible = !!options.translateExistCompatible;\n if ((process.env.NODE_ENV !== 'production')) {\n if (translateExistCompatible && !false) {\n warnOnce(getWarnMessage(I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG));\n }\n }\n let _inheritLocale = isBoolean(options.inheritLocale)\n ? options.inheritLocale\n : true;\n const _locale = _ref(\n // prettier-ignore\n __root && _inheritLocale\n ? __root.locale.value\n : isString(options.locale)\n ? options.locale\n : DEFAULT_LOCALE);\n const _fallbackLocale = _ref(\n // prettier-ignore\n __root && _inheritLocale\n ? __root.fallbackLocale.value\n : isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale.value);\n const _messages = _ref(getLocaleMessages(_locale.value, options));\n // prettier-ignore\n const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale.value]: {} })\n ;\n // prettier-ignore\n const _numberFormats = _ref(isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale.value]: {} })\n ;\n // warning suppress options\n // prettier-ignore\n let _missingWarn = __root\n ? __root.missingWarn\n : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n // prettier-ignore\n let _fallbackWarn = __root\n ? __root.fallbackWarn\n : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n // prettier-ignore\n let _fallbackRoot = __root\n ? __root.fallbackRoot\n : isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n // configure fall back to root\n let _fallbackFormat = !!options.fallbackFormat;\n // runtime missing\n let _missing = isFunction(options.missing) ? options.missing : null;\n let _runtimeMissing = isFunction(options.missing)\n ? defineCoreMissingHandler(options.missing)\n : null;\n // postTranslation handler\n let _postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n // prettier-ignore\n let _warnHtmlMessage = __root\n ? __root.warnHtmlMessage\n : isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n let _escapeParameter = !!options.escapeParameter;\n // custom linked modifiers\n // prettier-ignore\n const _modifiers = __root\n ? __root.modifiers\n : isPlainObject(options.modifiers)\n ? options.modifiers\n : {};\n // pluralRules\n let _pluralRules = options.pluralRules || (__root && __root.pluralRules);\n // runtime context\n // eslint-disable-next-line prefer-const\n let _context;\n const getCoreContext = () => {\n _isGlobal && setFallbackContext(null);\n const ctxOptions = {\n version: VERSION,\n locale: _locale.value,\n fallbackLocale: _fallbackLocale.value,\n messages: _messages.value,\n modifiers: _modifiers,\n pluralRules: _pluralRules,\n missing: _runtimeMissing === null ? undefined : _runtimeMissing,\n missingWarn: _missingWarn,\n fallbackWarn: _fallbackWarn,\n fallbackFormat: _fallbackFormat,\n unresolving: true,\n postTranslation: _postTranslation === null ? undefined : _postTranslation,\n warnHtmlMessage: _warnHtmlMessage,\n escapeParameter: _escapeParameter,\n messageResolver: options.messageResolver,\n messageCompiler: options.messageCompiler,\n __meta: { framework: 'vue' }\n };\n {\n ctxOptions.datetimeFormats = _datetimeFormats.value;\n ctxOptions.numberFormats = _numberFormats.value;\n ctxOptions.__datetimeFormatters = isPlainObject(_context)\n ? _context.__datetimeFormatters\n : undefined;\n ctxOptions.__numberFormatters = isPlainObject(_context)\n ? _context.__numberFormatters\n : undefined;\n }\n if ((process.env.NODE_ENV !== 'production')) {\n ctxOptions.__v_emitter = isPlainObject(_context)\n ? _context.__v_emitter\n : undefined;\n }\n const ctx = createCoreContext(ctxOptions);\n _isGlobal && setFallbackContext(ctx);\n return ctx;\n };\n _context = getCoreContext();\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n // track reactivity\n function trackReactivityValues() {\n return [\n _locale.value,\n _fallbackLocale.value,\n _messages.value,\n _datetimeFormats.value,\n _numberFormats.value\n ]\n ;\n }\n // locale\n const locale = computed({\n get: () => _locale.value,\n set: val => {\n _locale.value = val;\n _context.locale = _locale.value;\n }\n });\n // fallbackLocale\n const fallbackLocale = computed({\n get: () => _fallbackLocale.value,\n set: val => {\n _fallbackLocale.value = val;\n _context.fallbackLocale = _fallbackLocale.value;\n updateFallbackLocale(_context, _locale.value, val);\n }\n });\n // messages\n const messages = computed(() => _messages.value);\n // datetimeFormats\n const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);\n // numberFormats\n const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);\n // getPostTranslationHandler\n function getPostTranslationHandler() {\n return isFunction(_postTranslation) ? _postTranslation : null;\n }\n // setPostTranslationHandler\n function setPostTranslationHandler(handler) {\n _postTranslation = handler;\n _context.postTranslation = handler;\n }\n // getMissingHandler\n function getMissingHandler() {\n return _missing;\n }\n // setMissingHandler\n function setMissingHandler(handler) {\n if (handler !== null) {\n _runtimeMissing = defineCoreMissingHandler(handler);\n }\n _missing = handler;\n _context.missing = _runtimeMissing;\n }\n function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n return type !== 'translate' || !arg.resolvedMessage;\n }\n const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {\n trackReactivityValues(); // track reactive dependency\n // NOTE: experimental !!\n let ret;\n try {\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n setAdditionalMeta(getMetaInfo());\n }\n if (!_isGlobal) {\n _context.fallbackContext = __root\n ? getFallbackContext()\n : undefined;\n }\n ret = fn(_context);\n }\n finally {\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n setAdditionalMeta(null);\n }\n if (!_isGlobal) {\n _context.fallbackContext = undefined;\n }\n }\n if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)\n isNumber(ret) &&\n ret === NOT_REOSLVED) ||\n (warnType === 'translate exists' && !ret) // for `te`\n ) {\n const [key, arg2] = argumentParser();\n if ((process.env.NODE_ENV !== 'production') &&\n __root &&\n isString(key) &&\n isResolvedTranslateMessage(warnType, arg2)) {\n if (_fallbackRoot &&\n (isTranslateFallbackWarn(_fallbackWarn, key) ||\n isTranslateMissingWarn(_missingWarn, key))) {\n warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {\n key,\n type: warnType\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n const { __v_emitter: emitter } = _context;\n if (emitter && _fallbackRoot) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type: warnType,\n key,\n to: 'global',\n groupId: `${warnType}:${key}`\n });\n }\n }\n }\n return __root && _fallbackRoot\n ? fallbackSuccess(__root)\n : fallbackFail(key);\n }\n else if (successCondition(ret)) {\n return ret;\n }\n else {\n /* istanbul ignore next */\n throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);\n }\n };\n // t\n function t(...args) {\n return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));\n }\n // rt\n function rt(...args) {\n const [arg1, arg2, arg3] = args;\n if (arg3 && !isObject(arg3)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);\n }\n // d\n function d(...args) {\n return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));\n }\n // n\n function n(...args) {\n return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));\n }\n // for custom processor\n function normalize(values) {\n return values.map(val => isString(val) || isNumber(val) || isBoolean(val)\n ? createTextNode(String(val))\n : val);\n }\n const interpolate = (val) => val;\n const processor = {\n normalize,\n interpolate,\n type: 'vnode'\n };\n // translateVNode, using for `i18n-t` component\n function translateVNode(...args) {\n return wrapWithDeps(context => {\n let ret;\n const _context = context;\n try {\n _context.processor = processor;\n ret = Reflect.apply(translate, null, [_context, ...args]);\n }\n finally {\n _context.processor = null;\n }\n return ret;\n }, () => parseTranslateArgs(...args), 'translate', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));\n }\n // numberParts, using for `i18n-n` component\n function numberParts(...args) {\n return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));\n }\n // datetimeParts, using for `i18n-d` component\n function datetimeParts(...args) {\n return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));\n }\n function setPluralRules(rules) {\n _pluralRules = rules;\n _context.pluralRules = _pluralRules;\n }\n // te\n function te(key, locale) {\n return wrapWithDeps(() => {\n if (!key) {\n return false;\n }\n const targetLocale = isString(locale) ? locale : _locale.value;\n const message = getLocaleMessage(targetLocale);\n const resolved = _context.messageResolver(message, key);\n return !translateExistCompatible\n ? isMessageAST(resolved) ||\n isMessageFunction(resolved) ||\n isString(resolved)\n : resolved != null;\n }, () => [key], 'translate exists', root => {\n return Reflect.apply(root.te, root, [key, locale]);\n }, NOOP_RETURN_FALSE, val => isBoolean(val));\n }\n function resolveMessages(key) {\n let messages = null;\n const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);\n for (let i = 0; i < locales.length; i++) {\n const targetLocaleMessages = _messages.value[locales[i]] || {};\n const messageValue = _context.messageResolver(targetLocaleMessages, key);\n if (messageValue != null) {\n messages = messageValue;\n break;\n }\n }\n return messages;\n }\n // tm\n function tm(key) {\n const messages = resolveMessages(key);\n // prettier-ignore\n return messages != null\n ? messages\n : __root\n ? __root.tm(key) || {}\n : {};\n }\n // getLocaleMessage\n function getLocaleMessage(locale) {\n return (_messages.value[locale] || {});\n }\n // setLocaleMessage\n function setLocaleMessage(locale, message) {\n if (flatJson) {\n const _message = { [locale]: message };\n for (const key in _message) {\n if (hasOwn(_message, key)) {\n handleFlatJson(_message[key]);\n }\n }\n message = _message[locale];\n }\n _messages.value[locale] = message;\n _context.messages = _messages.value;\n }\n // mergeLocaleMessage\n function mergeLocaleMessage(locale, message) {\n _messages.value[locale] = _messages.value[locale] || {};\n const _message = { [locale]: message };\n if (flatJson) {\n for (const key in _message) {\n if (hasOwn(_message, key)) {\n handleFlatJson(_message[key]);\n }\n }\n }\n message = _message[locale];\n deepCopy(message, _messages.value[locale]);\n _context.messages = _messages.value;\n }\n // getDateTimeFormat\n function getDateTimeFormat(locale) {\n return _datetimeFormats.value[locale] || {};\n }\n // setDateTimeFormat\n function setDateTimeFormat(locale, format) {\n _datetimeFormats.value[locale] = format;\n _context.datetimeFormats = _datetimeFormats.value;\n clearDateTimeFormat(_context, locale, format);\n }\n // mergeDateTimeFormat\n function mergeDateTimeFormat(locale, format) {\n _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);\n _context.datetimeFormats = _datetimeFormats.value;\n clearDateTimeFormat(_context, locale, format);\n }\n // getNumberFormat\n function getNumberFormat(locale) {\n return _numberFormats.value[locale] || {};\n }\n // setNumberFormat\n function setNumberFormat(locale, format) {\n _numberFormats.value[locale] = format;\n _context.numberFormats = _numberFormats.value;\n clearNumberFormat(_context, locale, format);\n }\n // mergeNumberFormat\n function mergeNumberFormat(locale, format) {\n _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);\n _context.numberFormats = _numberFormats.value;\n clearNumberFormat(_context, locale, format);\n }\n // for debug\n composerID++;\n // watch root locale & fallbackLocale\n if (__root && inBrowser) {\n watch(__root.locale, (val) => {\n if (_inheritLocale) {\n _locale.value = val;\n _context.locale = val;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n });\n watch(__root.fallbackLocale, (val) => {\n if (_inheritLocale) {\n _fallbackLocale.value = val;\n _context.fallbackLocale = val;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n });\n }\n // define basic composition API!\n const composer = {\n id: composerID,\n locale,\n fallbackLocale,\n get inheritLocale() {\n return _inheritLocale;\n },\n set inheritLocale(val) {\n _inheritLocale = val;\n if (val && __root) {\n _locale.value = __root.locale.value;\n _fallbackLocale.value = __root.fallbackLocale.value;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n },\n get availableLocales() {\n return Object.keys(_messages.value).sort();\n },\n messages,\n get modifiers() {\n return _modifiers;\n },\n get pluralRules() {\n return _pluralRules || {};\n },\n get isGlobal() {\n return _isGlobal;\n },\n get missingWarn() {\n return _missingWarn;\n },\n set missingWarn(val) {\n _missingWarn = val;\n _context.missingWarn = _missingWarn;\n },\n get fallbackWarn() {\n return _fallbackWarn;\n },\n set fallbackWarn(val) {\n _fallbackWarn = val;\n _context.fallbackWarn = _fallbackWarn;\n },\n get fallbackRoot() {\n return _fallbackRoot;\n },\n set fallbackRoot(val) {\n _fallbackRoot = val;\n },\n get fallbackFormat() {\n return _fallbackFormat;\n },\n set fallbackFormat(val) {\n _fallbackFormat = val;\n _context.fallbackFormat = _fallbackFormat;\n },\n get warnHtmlMessage() {\n return _warnHtmlMessage;\n },\n set warnHtmlMessage(val) {\n _warnHtmlMessage = val;\n _context.warnHtmlMessage = val;\n },\n get escapeParameter() {\n return _escapeParameter;\n },\n set escapeParameter(val) {\n _escapeParameter = val;\n _context.escapeParameter = val;\n },\n t,\n getLocaleMessage,\n setLocaleMessage,\n mergeLocaleMessage,\n getPostTranslationHandler,\n setPostTranslationHandler,\n getMissingHandler,\n setMissingHandler,\n [SetPluralRulesSymbol]: setPluralRules\n };\n {\n composer.datetimeFormats = datetimeFormats;\n composer.numberFormats = numberFormats;\n composer.rt = rt;\n composer.te = te;\n composer.tm = tm;\n composer.d = d;\n composer.n = n;\n composer.getDateTimeFormat = getDateTimeFormat;\n composer.setDateTimeFormat = setDateTimeFormat;\n composer.mergeDateTimeFormat = mergeDateTimeFormat;\n composer.getNumberFormat = getNumberFormat;\n composer.setNumberFormat = setNumberFormat;\n composer.mergeNumberFormat = mergeNumberFormat;\n composer[InejctWithOptionSymbol] = __injectWithOption;\n composer[TranslateVNodeSymbol] = translateVNode;\n composer[DatetimePartsSymbol] = datetimeParts;\n composer[NumberPartsSymbol] = numberParts;\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n composer[EnableEmitter] = (emitter) => {\n _context.__v_emitter = emitter;\n };\n composer[DisableEmitter] = () => {\n _context.__v_emitter = undefined;\n };\n }\n return composer;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Convert to I18n Composer Options from VueI18n Options\n *\n * @internal\n */\nfunction convertComposerOptions(options) {\n const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;\n const fallbackLocale = isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : locale;\n const missing = isFunction(options.missing) ? options.missing : undefined;\n const missingWarn = isBoolean(options.silentTranslationWarn) ||\n isRegExp(options.silentTranslationWarn)\n ? !options.silentTranslationWarn\n : true;\n const fallbackWarn = isBoolean(options.silentFallbackWarn) ||\n isRegExp(options.silentFallbackWarn)\n ? !options.silentFallbackWarn\n : true;\n const fallbackRoot = isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n const fallbackFormat = !!options.formatFallbackMessages;\n const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};\n const pluralizationRules = options.pluralizationRules;\n const postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : undefined;\n const warnHtmlMessage = isString(options.warnHtmlInMessage)\n ? options.warnHtmlInMessage !== 'off'\n : true;\n const escapeParameter = !!options.escapeParameterHtml;\n const inheritLocale = isBoolean(options.sync) ? options.sync : true;\n if ((process.env.NODE_ENV !== 'production') && options.formatter) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n }\n if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n }\n let messages = options.messages;\n if (isPlainObject(options.sharedMessages)) {\n const sharedMessages = options.sharedMessages;\n const locales = Object.keys(sharedMessages);\n messages = locales.reduce((messages, locale) => {\n const message = messages[locale] || (messages[locale] = {});\n assign(message, sharedMessages[locale]);\n return messages;\n }, (messages || {}));\n }\n const { __i18n, __root, __injectWithOption } = options;\n const datetimeFormats = options.datetimeFormats;\n const numberFormats = options.numberFormats;\n const flatJson = options.flatJson;\n const translateExistCompatible = options\n .translateExistCompatible;\n return {\n locale,\n fallbackLocale,\n messages,\n flatJson,\n datetimeFormats,\n numberFormats,\n missing,\n missingWarn,\n fallbackWarn,\n fallbackRoot,\n fallbackFormat,\n modifiers,\n pluralRules: pluralizationRules,\n postTranslation,\n warnHtmlMessage,\n escapeParameter,\n messageResolver: options.messageResolver,\n inheritLocale,\n translateExistCompatible,\n __i18n,\n __root,\n __injectWithOption\n };\n}\n/**\n * create VueI18n interface factory\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction createVueI18n(options = {}, VueI18nLegacy) {\n {\n const composer = createComposer(convertComposerOptions(options));\n const { __extender } = options;\n // defines VueI18n\n const vueI18n = {\n // id\n id: composer.id,\n // locale\n get locale() {\n return composer.locale.value;\n },\n set locale(val) {\n composer.locale.value = val;\n },\n // fallbackLocale\n get fallbackLocale() {\n return composer.fallbackLocale.value;\n },\n set fallbackLocale(val) {\n composer.fallbackLocale.value = val;\n },\n // messages\n get messages() {\n return composer.messages.value;\n },\n // datetimeFormats\n get datetimeFormats() {\n return composer.datetimeFormats.value;\n },\n // numberFormats\n get numberFormats() {\n return composer.numberFormats.value;\n },\n // availableLocales\n get availableLocales() {\n return composer.availableLocales;\n },\n // formatter\n get formatter() {\n (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n // dummy\n return {\n interpolate() {\n return [];\n }\n };\n },\n set formatter(val) {\n (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n },\n // missing\n get missing() {\n return composer.getMissingHandler();\n },\n set missing(handler) {\n composer.setMissingHandler(handler);\n },\n // silentTranslationWarn\n get silentTranslationWarn() {\n return isBoolean(composer.missingWarn)\n ? !composer.missingWarn\n : composer.missingWarn;\n },\n set silentTranslationWarn(val) {\n composer.missingWarn = isBoolean(val) ? !val : val;\n },\n // silentFallbackWarn\n get silentFallbackWarn() {\n return isBoolean(composer.fallbackWarn)\n ? !composer.fallbackWarn\n : composer.fallbackWarn;\n },\n set silentFallbackWarn(val) {\n composer.fallbackWarn = isBoolean(val) ? !val : val;\n },\n // modifiers\n get modifiers() {\n return composer.modifiers;\n },\n // formatFallbackMessages\n get formatFallbackMessages() {\n return composer.fallbackFormat;\n },\n set formatFallbackMessages(val) {\n composer.fallbackFormat = val;\n },\n // postTranslation\n get postTranslation() {\n return composer.getPostTranslationHandler();\n },\n set postTranslation(handler) {\n composer.setPostTranslationHandler(handler);\n },\n // sync\n get sync() {\n return composer.inheritLocale;\n },\n set sync(val) {\n composer.inheritLocale = val;\n },\n // warnInHtmlMessage\n get warnHtmlInMessage() {\n return composer.warnHtmlMessage ? 'warn' : 'off';\n },\n set warnHtmlInMessage(val) {\n composer.warnHtmlMessage = val !== 'off';\n },\n // escapeParameterHtml\n get escapeParameterHtml() {\n return composer.escapeParameter;\n },\n set escapeParameterHtml(val) {\n composer.escapeParameter = val;\n },\n // preserveDirectiveContent\n get preserveDirectiveContent() {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n return true;\n },\n set preserveDirectiveContent(val) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n },\n // pluralizationRules\n get pluralizationRules() {\n return composer.pluralRules || {};\n },\n // for internal\n __composer: composer,\n // t\n t(...args) {\n const [arg1, arg2, arg3] = args;\n const options = {};\n let list = null;\n let named = null;\n if (!isString(arg1)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n const key = arg1;\n if (isString(arg2)) {\n options.locale = arg2;\n }\n else if (isArray(arg2)) {\n list = arg2;\n }\n else if (isPlainObject(arg2)) {\n named = arg2;\n }\n if (isArray(arg3)) {\n list = arg3;\n }\n else if (isPlainObject(arg3)) {\n named = arg3;\n }\n // return composer.t(key, (list || named || {}) as any, options)\n return Reflect.apply(composer.t, composer, [\n key,\n (list || named || {}),\n options\n ]);\n },\n rt(...args) {\n return Reflect.apply(composer.rt, composer, [...args]);\n },\n // tc\n tc(...args) {\n const [arg1, arg2, arg3] = args;\n const options = { plural: 1 };\n let list = null;\n let named = null;\n if (!isString(arg1)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n const key = arg1;\n if (isString(arg2)) {\n options.locale = arg2;\n }\n else if (isNumber(arg2)) {\n options.plural = arg2;\n }\n else if (isArray(arg2)) {\n list = arg2;\n }\n else if (isPlainObject(arg2)) {\n named = arg2;\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isArray(arg3)) {\n list = arg3;\n }\n else if (isPlainObject(arg3)) {\n named = arg3;\n }\n // return composer.t(key, (list || named || {}) as any, options)\n return Reflect.apply(composer.t, composer, [\n key,\n (list || named || {}),\n options\n ]);\n },\n // te\n te(key, locale) {\n return composer.te(key, locale);\n },\n // tm\n tm(key) {\n return composer.tm(key);\n },\n // getLocaleMessage\n getLocaleMessage(locale) {\n return composer.getLocaleMessage(locale);\n },\n // setLocaleMessage\n setLocaleMessage(locale, message) {\n composer.setLocaleMessage(locale, message);\n },\n // mergeLocaleMessage\n mergeLocaleMessage(locale, message) {\n composer.mergeLocaleMessage(locale, message);\n },\n // d\n d(...args) {\n return Reflect.apply(composer.d, composer, [...args]);\n },\n // getDateTimeFormat\n getDateTimeFormat(locale) {\n return composer.getDateTimeFormat(locale);\n },\n // setDateTimeFormat\n setDateTimeFormat(locale, format) {\n composer.setDateTimeFormat(locale, format);\n },\n // mergeDateTimeFormat\n mergeDateTimeFormat(locale, format) {\n composer.mergeDateTimeFormat(locale, format);\n },\n // n\n n(...args) {\n return Reflect.apply(composer.n, composer, [...args]);\n },\n // getNumberFormat\n getNumberFormat(locale) {\n return composer.getNumberFormat(locale);\n },\n // setNumberFormat\n setNumberFormat(locale, format) {\n composer.setNumberFormat(locale, format);\n },\n // mergeNumberFormat\n mergeNumberFormat(locale, format) {\n composer.mergeNumberFormat(locale, format);\n },\n // getChoiceIndex\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getChoiceIndex(choice, choicesLength) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));\n return -1;\n }\n };\n vueI18n.__extender = __extender;\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n vueI18n.__enableEmitter = (emitter) => {\n const __composer = composer;\n __composer[EnableEmitter] && __composer[EnableEmitter](emitter);\n };\n vueI18n.__disableEmitter = () => {\n const __composer = composer;\n __composer[DisableEmitter] && __composer[DisableEmitter]();\n };\n }\n return vueI18n;\n }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nconst baseFormatProps = {\n tag: {\n type: [String, Object]\n },\n locale: {\n type: String\n },\n scope: {\n type: String,\n // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050\n validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',\n default: 'parent' /* ComponentI18nScope */\n },\n i18n: {\n type: Object\n }\n};\n\nfunction getInterpolateArg(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n{ slots }, // SetupContext,\nkeys) {\n if (keys.length === 1 && keys[0] === 'default') {\n // default slot with list\n const ret = slots.default ? slots.default() : [];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ret.reduce((slot, current) => {\n return [\n ...slot,\n // prettier-ignore\n ...(current.type === Fragment ? current.children : [current]\n )\n ];\n }, []);\n }\n else {\n // named slots\n return keys.reduce((arg, key) => {\n const slot = slots[key];\n if (slot) {\n arg[key] = slot();\n }\n return arg;\n }, {});\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getFragmentableTag(tag) {\n return Fragment ;\n}\n\nconst TranslationImpl = /*#__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-t',\n props: assign({\n keypath: {\n type: String,\n required: true\n },\n plural: {\n type: [Number, String],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n validator: (val) => isNumber(val) || !isNaN(val)\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const { slots, attrs } = context;\n // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return () => {\n const keys = Object.keys(slots).filter(key => key !== '_');\n const options = {};\n if (props.locale) {\n options.locale = props.locale;\n }\n if (props.plural !== undefined) {\n options.plural = isString(props.plural) ? +props.plural : props.plural;\n }\n const arg = getInterpolateArg(context, keys);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);\n const assignedAttrs = assign({}, attrs);\n const tag = isString(props.tag) || isObject(props.tag)\n ? props.tag\n : getFragmentableTag();\n return h(tag, assignedAttrs, children);\n };\n }\n});\n/**\n * export the public type for h/tsx inference\n * also to avoid inline import() in generated d.ts files\n */\n/**\n * Translation Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [TranslationProps](component#translationprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Component Interpolation](../guide/advanced/component)\n *\n * @example\n * ```html\n *
\n * \n * \n * {{ $t('tos') }}\n * \n * \n *
\n * ```\n * ```js\n * import { createApp } from 'vue'\n * import { createI18n } from 'vue-i18n'\n *\n * const messages = {\n * en: {\n * tos: 'Term of Service',\n * term: 'I accept xxx {0}.'\n * },\n * ja: {\n * tos: '利用規約',\n * term: '私は xxx の{0}に同意します。'\n * }\n * }\n *\n * const i18n = createI18n({\n * locale: 'en',\n * messages\n * })\n *\n * const app = createApp({\n * data: {\n * url: '/term'\n * }\n * }).use(i18n).mount('#app')\n * ```\n *\n * @VueI18nComponent\n */\nconst Translation = TranslationImpl;\nconst I18nT = Translation;\n\nfunction isVNode(target) {\n return isArray(target) && !isString(target[0]);\n}\nfunction renderFormatter(props, context, slotKeys, partFormatter) {\n const { slots, attrs } = context;\n return () => {\n const options = { part: true };\n let overrides = {};\n if (props.locale) {\n options.locale = props.locale;\n }\n if (isString(props.format)) {\n options.key = props.format;\n }\n else if (isObject(props.format)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isString(props.format.key)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options.key = props.format.key;\n }\n // Filter out number format options only\n overrides = Object.keys(props.format).reduce((options, prop) => {\n return slotKeys.includes(prop)\n ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any\n : options;\n }, {});\n }\n const parts = partFormatter(...[props.value, options, overrides]);\n let children = [options.key];\n if (isArray(parts)) {\n children = parts.map((part, index) => {\n const slot = slots[part.type];\n const node = slot\n ? slot({ [part.type]: part.value, index, parts })\n : [part.value];\n if (isVNode(node)) {\n node[0].key = `${part.type}-${index}`;\n }\n return node;\n });\n }\n else if (isString(parts)) {\n children = [parts];\n }\n const assignedAttrs = assign({}, attrs);\n const tag = isString(props.tag) || isObject(props.tag)\n ? props.tag\n : getFragmentableTag();\n return h(tag, assignedAttrs, children);\n };\n}\n\nconst NumberFormatImpl = /*#__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-n',\n props: assign({\n value: {\n type: Number,\n required: true\n },\n format: {\n type: [String, Object]\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) => \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n i18n[NumberPartsSymbol](...args));\n }\n});\n/**\n * export the public type for h/tsx inference\n * also to avoid inline import() in generated d.ts files\n */\n/**\n * Number Format Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [FormattableProps](component#formattableprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)\n *\n * @VueI18nDanger\n * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)\n *\n * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)\n *\n * @VueI18nComponent\n */\nconst NumberFormat = NumberFormatImpl;\nconst I18nN = NumberFormat;\n\nconst DatetimeFormatImpl = /* #__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-d',\n props: assign({\n value: {\n type: [Number, Date],\n required: true\n },\n format: {\n type: [String, Object]\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) => \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n i18n[DatetimePartsSymbol](...args));\n }\n});\n/**\n * Datetime Format Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [FormattableProps](component#formattableprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)\n *\n * @VueI18nDanger\n * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)\n *\n * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)\n *\n * @VueI18nComponent\n */\nconst DatetimeFormat = DatetimeFormatImpl;\nconst I18nD = DatetimeFormat;\n\nfunction getComposer$2(i18n, instance) {\n const i18nInternal = i18n;\n if (i18n.mode === 'composition') {\n return (i18nInternal.__getInstance(instance) || i18n.global);\n }\n else {\n const vueI18n = i18nInternal.__getInstance(instance);\n return vueI18n != null\n ? vueI18n.__composer\n : i18n.global.__composer;\n }\n}\nfunction vTDirective(i18n) {\n const _process = (binding) => {\n const { instance, modifiers, value } = binding;\n /* istanbul ignore if */\n if (!instance || !instance.$) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const composer = getComposer$2(i18n, instance.$);\n if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));\n }\n const parsedValue = parseValue(value);\n return [\n Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),\n composer\n ];\n };\n const register = (el, binding) => {\n const [textContent, composer] = _process(binding);\n if (inBrowser && i18n.global === composer) {\n // global scope only\n el.__i18nWatcher = watch(composer.locale, () => {\n binding.instance && binding.instance.$forceUpdate();\n });\n }\n el.__composer = composer;\n el.textContent = textContent;\n };\n const unregister = (el) => {\n if (inBrowser && el.__i18nWatcher) {\n el.__i18nWatcher();\n el.__i18nWatcher = undefined;\n delete el.__i18nWatcher;\n }\n if (el.__composer) {\n el.__composer = undefined;\n delete el.__composer;\n }\n };\n const update = (el, { value }) => {\n if (el.__composer) {\n const composer = el.__composer;\n const parsedValue = parseValue(value);\n el.textContent = Reflect.apply(composer.t, composer, [\n ...makeParams(parsedValue)\n ]);\n }\n };\n const getSSRProps = (binding) => {\n const [textContent] = _process(binding);\n return { textContent };\n };\n return {\n created: register,\n unmounted: unregister,\n beforeUpdate: update,\n getSSRProps\n };\n}\nfunction parseValue(value) {\n if (isString(value)) {\n return { path: value };\n }\n else if (isPlainObject(value)) {\n if (!('path' in value)) {\n throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');\n }\n return value;\n }\n else {\n throw createI18nError(I18nErrorCodes.INVALID_VALUE);\n }\n}\nfunction makeParams(value) {\n const { path, locale, args, choice, plural } = value;\n const options = {};\n const named = args || {};\n if (isString(locale)) {\n options.locale = locale;\n }\n if (isNumber(choice)) {\n options.plural = choice;\n }\n if (isNumber(plural)) {\n options.plural = plural;\n }\n return [path, named, options];\n}\n\nfunction apply(app, i18n, ...options) {\n const pluginOptions = isPlainObject(options[0])\n ? options[0]\n : {};\n const useI18nComponentName = !!pluginOptions.useI18nComponentName;\n const globalInstall = isBoolean(pluginOptions.globalInstall)\n ? pluginOptions.globalInstall\n : true;\n if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {\n warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {\n name: Translation.name\n }));\n }\n if (globalInstall) {\n [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));\n [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));\n [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));\n }\n // install directive\n {\n app.directive('t', vTDirective(i18n));\n }\n}\n\nconst VueDevToolsLabels = {\n [\"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',\n [\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',\n [\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'\n};\nconst VueDevToolsPlaceholders = {\n [\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'\n};\nconst VueDevToolsTimelineColors = {\n [\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19\n};\n\nconst VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';\nlet devtoolsApi;\nasync function enableDevTools(app, i18n) {\n return new Promise((resolve, reject) => {\n try {\n setupDevtoolsPlugin({\n id: \"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */,\n label: VueDevToolsLabels[\"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */],\n packageName: 'vue-i18n',\n homepage: 'https://vue-i18n.intlify.dev',\n logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',\n componentStateTypes: [VUE_I18N_COMPONENT_TYPES],\n app: app // eslint-disable-line @typescript-eslint/no-explicit-any\n }, api => {\n devtoolsApi = api;\n api.on.visitComponentTree(({ componentInstance, treeNode }) => {\n updateComponentTreeTags(componentInstance, treeNode, i18n);\n });\n api.on.inspectComponent(({ componentInstance, instanceData }) => {\n if (componentInstance.vnode.el &&\n componentInstance.vnode.el.__VUE_I18N__ &&\n instanceData) {\n if (i18n.mode === 'legacy') {\n // ignore global scope on legacy mode\n if (componentInstance.vnode.el.__VUE_I18N__ !==\n i18n.global.__composer) {\n inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);\n }\n }\n else {\n inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);\n }\n }\n });\n api.addInspector({\n id: \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,\n label: VueDevToolsLabels[\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],\n icon: 'language',\n treeFilterPlaceholder: VueDevToolsPlaceholders[\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]\n });\n api.on.getInspectorTree(payload => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n registerScope(payload, i18n);\n }\n });\n const roots = new Map();\n api.on.getInspectorState(async (payload) => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n api.unhighlightElement();\n inspectScope(payload, i18n);\n if (payload.nodeId === 'global') {\n if (!roots.has(payload.app)) {\n const [root] = await api.getComponentInstances(payload.app);\n roots.set(payload.app, root);\n }\n api.highlightElement(roots.get(payload.app));\n }\n else {\n const instance = getComponentInstance(payload.nodeId, i18n);\n instance && api.highlightElement(instance);\n }\n }\n });\n api.on.editInspectorState(payload => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n editScope(payload, i18n);\n }\n });\n api.addTimelineLayer({\n id: \"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */,\n label: VueDevToolsLabels[\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */],\n color: VueDevToolsTimelineColors[\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]\n });\n resolve(true);\n });\n }\n catch (e) {\n console.error(e);\n reject(false);\n }\n });\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getI18nScopeLable(instance) {\n return (instance.type.name ||\n instance.type.displayName ||\n instance.type.__file ||\n 'Anonymous');\n}\nfunction updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any\ntreeNode, i18n) {\n // prettier-ignore\n const global = i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {\n // add custom tags local scope only\n if (instance.vnode.el.__VUE_I18N__ !== global) {\n const tag = {\n label: `i18n (${getI18nScopeLable(instance)} Scope)`,\n textColor: 0x000000,\n backgroundColor: 0xffcd19\n };\n treeNode.tags.push(tag);\n }\n }\n}\nfunction inspectComposer(instanceData, composer) {\n const type = VUE_I18N_COMPONENT_TYPES;\n instanceData.state.push({\n type,\n key: 'locale',\n editable: true,\n value: composer.locale.value\n });\n instanceData.state.push({\n type,\n key: 'availableLocales',\n editable: false,\n value: composer.availableLocales\n });\n instanceData.state.push({\n type,\n key: 'fallbackLocale',\n editable: true,\n value: composer.fallbackLocale.value\n });\n instanceData.state.push({\n type,\n key: 'inheritLocale',\n editable: true,\n value: composer.inheritLocale\n });\n instanceData.state.push({\n type,\n key: 'messages',\n editable: false,\n value: getLocaleMessageValue(composer.messages.value)\n });\n {\n instanceData.state.push({\n type,\n key: 'datetimeFormats',\n editable: false,\n value: composer.datetimeFormats.value\n });\n instanceData.state.push({\n type,\n key: 'numberFormats',\n editable: false,\n value: composer.numberFormats.value\n });\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getLocaleMessageValue(messages) {\n const value = {};\n Object.keys(messages).forEach((key) => {\n const v = messages[key];\n if (isFunction(v) && 'source' in v) {\n value[key] = getMessageFunctionDetails(v);\n }\n else if (isMessageAST(v) && v.loc && v.loc.source) {\n value[key] = v.loc.source;\n }\n else if (isObject(v)) {\n value[key] = getLocaleMessageValue(v);\n }\n else {\n value[key] = v;\n }\n });\n return value;\n}\nconst ESC = {\n '<': '<',\n '>': '>',\n '\"': '"',\n '&': '&'\n};\nfunction escape(s) {\n return s.replace(/[<>\"&]/g, escapeChar);\n}\nfunction escapeChar(a) {\n return ESC[a] || a;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getMessageFunctionDetails(func) {\n const argString = func.source ? `(\"${escape(func.source)}\")` : `(?)`;\n return {\n _custom: {\n type: 'function',\n display: `ƒ ${argString}`\n }\n };\n}\nfunction registerScope(payload, i18n) {\n payload.rootNodes.push({\n id: 'global',\n label: 'Global Scope'\n });\n // prettier-ignore\n const global = i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n for (const [keyInstance, instance] of i18n.__instances) {\n // prettier-ignore\n const composer = i18n.mode === 'composition'\n ? instance\n : instance.__composer;\n if (global === composer) {\n continue;\n }\n payload.rootNodes.push({\n id: composer.id.toString(),\n label: `${getI18nScopeLable(keyInstance)} Scope`\n });\n }\n}\nfunction getComponentInstance(nodeId, i18n) {\n let instance = null;\n if (nodeId !== 'global') {\n for (const [component, composer] of i18n.__instances.entries()) {\n if (composer.id.toString() === nodeId) {\n instance = component;\n break;\n }\n }\n }\n return instance;\n}\nfunction getComposer$1(nodeId, i18n) {\n if (nodeId === 'global') {\n return i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n }\n else {\n const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);\n if (instance) {\n return i18n.mode === 'composition'\n ? instance\n : instance.__composer;\n }\n else {\n return null;\n }\n }\n}\nfunction inspectScope(payload, i18n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n const composer = getComposer$1(payload.nodeId, i18n);\n if (composer) {\n // TODO:\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n payload.state = makeScopeInspectState(composer);\n }\n return null;\n}\nfunction makeScopeInspectState(composer) {\n const state = {};\n const localeType = 'Locale related info';\n const localeStates = [\n {\n type: localeType,\n key: 'locale',\n editable: true,\n value: composer.locale.value\n },\n {\n type: localeType,\n key: 'fallbackLocale',\n editable: true,\n value: composer.fallbackLocale.value\n },\n {\n type: localeType,\n key: 'availableLocales',\n editable: false,\n value: composer.availableLocales\n },\n {\n type: localeType,\n key: 'inheritLocale',\n editable: true,\n value: composer.inheritLocale\n }\n ];\n state[localeType] = localeStates;\n const localeMessagesType = 'Locale messages info';\n const localeMessagesStates = [\n {\n type: localeMessagesType,\n key: 'messages',\n editable: false,\n value: getLocaleMessageValue(composer.messages.value)\n }\n ];\n state[localeMessagesType] = localeMessagesStates;\n {\n const datetimeFormatsType = 'Datetime formats info';\n const datetimeFormatsStates = [\n {\n type: datetimeFormatsType,\n key: 'datetimeFormats',\n editable: false,\n value: composer.datetimeFormats.value\n }\n ];\n state[datetimeFormatsType] = datetimeFormatsStates;\n const numberFormatsType = 'Datetime formats info';\n const numberFormatsStates = [\n {\n type: numberFormatsType,\n key: 'numberFormats',\n editable: false,\n value: composer.numberFormats.value\n }\n ];\n state[numberFormatsType] = numberFormatsStates;\n }\n return state;\n}\nfunction addTimelineEvent(event, payload) {\n if (devtoolsApi) {\n let groupId;\n if (payload && 'groupId' in payload) {\n groupId = payload.groupId;\n delete payload.groupId;\n }\n devtoolsApi.addTimelineEvent({\n layerId: \"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */,\n event: {\n title: event,\n groupId,\n time: Date.now(),\n meta: {},\n data: payload || {},\n logType: event === \"compile-error\" /* VueDevToolsTimelineEvents.COMPILE_ERROR */\n ? 'error'\n : event === \"fallback\" /* VueDevToolsTimelineEvents.FALBACK */ ||\n event === \"missing\" /* VueDevToolsTimelineEvents.MISSING */\n ? 'warning'\n : 'default'\n }\n });\n }\n}\nfunction editScope(payload, i18n) {\n const composer = getComposer$1(payload.nodeId, i18n);\n if (composer) {\n const [field] = payload.path;\n if (field === 'locale' && isString(payload.state.value)) {\n composer.locale.value = payload.state.value;\n }\n else if (field === 'fallbackLocale' &&\n (isString(payload.state.value) ||\n isArray(payload.state.value) ||\n isObject(payload.state.value))) {\n composer.fallbackLocale.value = payload.state.value;\n }\n else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {\n composer.inheritLocale = payload.state.value;\n }\n }\n}\n\n/**\n * Supports compatibility for legacy vue-i18n APIs\n * This mixin is used when we use vue-i18n@v9.x or later\n */\nfunction defineMixin(vuei18n, composer, i18n) {\n return {\n beforeCreate() {\n const instance = getCurrentInstance();\n /* istanbul ignore if */\n if (!instance) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const options = this.$options;\n if (options.i18n) {\n const optionsI18n = options.i18n;\n if (options.__i18n) {\n optionsI18n.__i18n = options.__i18n;\n }\n optionsI18n.__root = composer;\n if (this === this.$root) {\n // merge option and gttach global\n this.$i18n = mergeToGlobal(vuei18n, optionsI18n);\n }\n else {\n optionsI18n.__injectWithOption = true;\n optionsI18n.__extender = i18n.__vueI18nExtend;\n // atttach local VueI18n instance\n this.$i18n = createVueI18n(optionsI18n);\n // extend VueI18n instance\n const _vueI18n = this.$i18n;\n if (_vueI18n.__extender) {\n _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);\n }\n }\n }\n else if (options.__i18n) {\n if (this === this.$root) {\n // merge option and gttach global\n this.$i18n = mergeToGlobal(vuei18n, options);\n }\n else {\n // atttach local VueI18n instance\n this.$i18n = createVueI18n({\n __i18n: options.__i18n,\n __injectWithOption: true,\n __extender: i18n.__vueI18nExtend,\n __root: composer\n });\n // extend VueI18n instance\n const _vueI18n = this.$i18n;\n if (_vueI18n.__extender) {\n _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);\n }\n }\n }\n else {\n // attach global VueI18n instance\n this.$i18n = vuei18n;\n }\n if (options.__i18nGlobal) {\n adjustI18nResources(composer, options, options);\n }\n // defines vue-i18n legacy APIs\n this.$t = (...args) => this.$i18n.t(...args);\n this.$rt = (...args) => this.$i18n.rt(...args);\n this.$tc = (...args) => this.$i18n.tc(...args);\n this.$te = (key, locale) => this.$i18n.te(key, locale);\n this.$d = (...args) => this.$i18n.d(...args);\n this.$n = (...args) => this.$i18n.n(...args);\n this.$tm = (key) => this.$i18n.tm(key);\n i18n.__setInstance(instance, this.$i18n);\n },\n mounted() {\n /* istanbul ignore if */\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n this.$el &&\n this.$i18n) {\n const _vueI18n = this.$i18n;\n this.$el.__VUE_I18N__ = _vueI18n.__composer;\n const emitter = (this.__v_emitter =\n createEmitter());\n _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);\n emitter.on('*', addTimelineEvent);\n }\n },\n unmounted() {\n const instance = getCurrentInstance();\n /* istanbul ignore if */\n if (!instance) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const _vueI18n = this.$i18n;\n /* istanbul ignore if */\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n this.$el &&\n this.$el.__VUE_I18N__) {\n if (this.__v_emitter) {\n this.__v_emitter.off('*', addTimelineEvent);\n delete this.__v_emitter;\n }\n if (this.$i18n) {\n _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();\n delete this.$el.__VUE_I18N__;\n }\n }\n delete this.$t;\n delete this.$rt;\n delete this.$tc;\n delete this.$te;\n delete this.$d;\n delete this.$n;\n delete this.$tm;\n if (_vueI18n.__disposer) {\n _vueI18n.__disposer();\n delete _vueI18n.__disposer;\n delete _vueI18n.__extender;\n }\n i18n.__deleteInstance(instance);\n delete this.$i18n;\n }\n };\n}\nfunction mergeToGlobal(g, options) {\n g.locale = options.locale || g.locale;\n g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;\n g.missing = options.missing || g.missing;\n g.silentTranslationWarn =\n options.silentTranslationWarn || g.silentFallbackWarn;\n g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;\n g.formatFallbackMessages =\n options.formatFallbackMessages || g.formatFallbackMessages;\n g.postTranslation = options.postTranslation || g.postTranslation;\n g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;\n g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;\n g.sync = options.sync || g.sync;\n g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);\n const messages = getLocaleMessages(g.locale, {\n messages: options.messages,\n __i18n: options.__i18n\n });\n Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));\n if (options.datetimeFormats) {\n Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));\n }\n if (options.numberFormats) {\n Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));\n }\n return g;\n}\n\n/**\n * Injection key for {@link useI18n}\n *\n * @remarks\n * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.\n * Specify the i18n instance created by {@link createI18n} together with `provide` function.\n *\n * @VueI18nGeneral\n */\nconst I18nInjectionKey = \n/* #__PURE__*/ makeSymbol('global-vue-i18n');\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction createI18n(options = {}, VueI18nLegacy) {\n // prettier-ignore\n const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)\n ? options.legacy\n : __VUE_I18N_LEGACY_API__;\n // prettier-ignore\n const __globalInjection = isBoolean(options.globalInjection)\n ? options.globalInjection\n : true;\n // prettier-ignore\n const __allowComposition = __VUE_I18N_LEGACY_API__ && __legacyMode\n ? !!options.allowComposition\n : true;\n const __instances = new Map();\n const [globalScope, __global] = createGlobal(options, __legacyMode);\n const symbol = /* #__PURE__*/ makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');\n if ((process.env.NODE_ENV !== 'production')) {\n if (__legacyMode && __allowComposition && !false) {\n warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));\n }\n }\n function __getInstance(component) {\n return __instances.get(component) || null;\n }\n function __setInstance(component, instance) {\n __instances.set(component, instance);\n }\n function __deleteInstance(component) {\n __instances.delete(component);\n }\n {\n const i18n = {\n // mode\n get mode() {\n return __VUE_I18N_LEGACY_API__ && __legacyMode\n ? 'legacy'\n : 'composition';\n },\n // allowComposition\n get allowComposition() {\n return __allowComposition;\n },\n // install plugin\n async install(app, ...options) {\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false) {\n app.__VUE_I18N__ = i18n;\n }\n // setup global provider\n app.__VUE_I18N_SYMBOL__ = symbol;\n app.provide(app.__VUE_I18N_SYMBOL__, i18n);\n // set composer & vuei18n extend hook options from plugin options\n if (isPlainObject(options[0])) {\n const opts = options[0];\n i18n.__composerExtend =\n opts.__composerExtend;\n i18n.__vueI18nExtend =\n opts.__vueI18nExtend;\n }\n // global method and properties injection for Composition API\n let globalReleaseHandler = null;\n if (!__legacyMode && __globalInjection) {\n globalReleaseHandler = injectGlobalFields(app, i18n.global);\n }\n // install built-in components and directive\n if (__VUE_I18N_FULL_INSTALL__) {\n apply(app, i18n, ...options);\n }\n // setup mixin for Legacy API\n if (__VUE_I18N_LEGACY_API__ && __legacyMode) {\n app.mixin(defineMixin(__global, __global.__composer, i18n));\n }\n // release global scope\n const unmountApp = app.unmount;\n app.unmount = () => {\n globalReleaseHandler && globalReleaseHandler();\n i18n.dispose();\n unmountApp();\n };\n // setup vue-devtools plugin\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && !false) {\n const ret = await enableDevTools(app, i18n);\n if (!ret) {\n throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);\n }\n const emitter = createEmitter();\n if (__legacyMode) {\n const _vueI18n = __global;\n _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = __global;\n _composer[EnableEmitter] && _composer[EnableEmitter](emitter);\n }\n emitter.on('*', addTimelineEvent);\n }\n },\n // global accessor\n get global() {\n return __global;\n },\n dispose() {\n globalScope.stop();\n },\n // @internal\n __instances,\n // @internal\n __getInstance,\n // @internal\n __setInstance,\n // @internal\n __deleteInstance\n };\n return i18n;\n }\n}\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction useI18n(options = {}) {\n const instance = getCurrentInstance();\n if (instance == null) {\n throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);\n }\n if (!instance.isCE &&\n instance.appContext.app != null &&\n !instance.appContext.app.__VUE_I18N_SYMBOL__) {\n throw createI18nError(I18nErrorCodes.NOT_INSTALLED);\n }\n const i18n = getI18nInstance(instance);\n const gl = getGlobalComposer(i18n);\n const componentOptions = getComponentOptions(instance);\n const scope = getScope(options, componentOptions);\n if (__VUE_I18N_LEGACY_API__) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (i18n.mode === 'legacy' && !options.__useComponent) {\n if (!i18n.allowComposition) {\n throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);\n }\n return useI18nForLegacy(instance, scope, gl, options);\n }\n }\n if (scope === 'global') {\n adjustI18nResources(gl, options, componentOptions);\n return gl;\n }\n if (scope === 'parent') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let composer = getComposer(i18n, instance, options.__useComponent);\n if (composer == null) {\n if ((process.env.NODE_ENV !== 'production')) {\n warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));\n }\n composer = gl;\n }\n return composer;\n }\n const i18nInternal = i18n;\n let composer = i18nInternal.__getInstance(instance);\n if (composer == null) {\n const composerOptions = assign({}, options);\n if ('__i18n' in componentOptions) {\n composerOptions.__i18n = componentOptions.__i18n;\n }\n if (gl) {\n composerOptions.__root = gl;\n }\n composer = createComposer(composerOptions);\n if (i18nInternal.__composerExtend) {\n composer[DisposeSymbol] =\n i18nInternal.__composerExtend(composer);\n }\n setupLifeCycle(i18nInternal, instance, composer);\n i18nInternal.__setInstance(instance, composer);\n }\n return composer;\n}\n/**\n * Cast to VueI18n legacy compatible type\n *\n * @remarks\n * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).\n *\n * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.\n *\n * @param i18n - An instance of {@link I18n}\n * @returns A i18n instance which is casted to {@link VueI18n} type\n *\n * @VueI18nTip\n * :new: provided by **vue-i18n-bridge only**\n *\n * @VueI18nGeneral\n */\n/* #__NO_SIDE_EFFECTS__ */\nconst castToVueI18n = (i18n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => {\n if (!(__VUE_I18N_BRIDGE__ in i18n)) {\n throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);\n }\n return i18n;\n};\nfunction createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n const scope = effectScope();\n {\n const obj = __VUE_I18N_LEGACY_API__ && legacyMode\n ? scope.run(() => createVueI18n(options))\n : scope.run(() => createComposer(options));\n if (obj == null) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n return [scope, obj];\n }\n}\nfunction getI18nInstance(instance) {\n {\n const i18n = inject(!instance.isCE\n ? instance.appContext.app.__VUE_I18N_SYMBOL__\n : I18nInjectionKey);\n /* istanbul ignore if */\n if (!i18n) {\n throw createI18nError(!instance.isCE\n ? I18nErrorCodes.UNEXPECTED_ERROR\n : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);\n }\n return i18n;\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getScope(options, componentOptions) {\n // prettier-ignore\n return isEmptyObject(options)\n ? ('__i18n' in componentOptions)\n ? 'local'\n : 'global'\n : !options.useScope\n ? 'local'\n : options.useScope;\n}\nfunction getGlobalComposer(i18n) {\n // prettier-ignore\n return i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer\n ;\n}\nfunction getComposer(i18n, target, useComponent = false) {\n let composer = null;\n const root = target.root;\n let current = getParentComponentInstance(target, useComponent);\n while (current != null) {\n const i18nInternal = i18n;\n if (i18n.mode === 'composition') {\n composer = i18nInternal.__getInstance(current);\n }\n else {\n if (__VUE_I18N_LEGACY_API__) {\n const vueI18n = i18nInternal.__getInstance(current);\n if (vueI18n != null) {\n composer = vueI18n\n .__composer;\n if (useComponent &&\n composer &&\n !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n composer = null;\n }\n }\n }\n }\n if (composer != null) {\n break;\n }\n if (root === current) {\n break;\n }\n current = current.parent;\n }\n return composer;\n}\nfunction getParentComponentInstance(target, useComponent = false) {\n if (target == null) {\n return null;\n }\n {\n // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots\n return !useComponent\n ? target.parent\n : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n}\nfunction setupLifeCycle(i18n, target, composer) {\n let emitter = null;\n {\n onMounted(() => {\n // inject composer instance to DOM for intlify-devtools\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n target.vnode.el) {\n target.vnode.el.__VUE_I18N__ = composer;\n emitter = createEmitter();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = composer;\n _composer[EnableEmitter] && _composer[EnableEmitter](emitter);\n emitter.on('*', addTimelineEvent);\n }\n }, target);\n onUnmounted(() => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = composer;\n // remove composer instance from DOM for intlify-devtools\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n target.vnode.el &&\n target.vnode.el.__VUE_I18N__) {\n emitter && emitter.off('*', addTimelineEvent);\n _composer[DisableEmitter] && _composer[DisableEmitter]();\n delete target.vnode.el.__VUE_I18N__;\n }\n i18n.__deleteInstance(target);\n // dispose extended resources\n const dispose = _composer[DisposeSymbol];\n if (dispose) {\n dispose();\n delete _composer[DisposeSymbol];\n }\n }, target);\n }\n}\nfunction useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n const isLocalScope = scope === 'local';\n const _composer = shallowRef(null);\n if (isLocalScope &&\n instance.proxy &&\n !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {\n throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);\n }\n const _inheritLocale = isBoolean(options.inheritLocale)\n ? options.inheritLocale\n : !isString(options.locale);\n const _locale = ref(\n // prettier-ignore\n !isLocalScope || _inheritLocale\n ? root.locale.value\n : isString(options.locale)\n ? options.locale\n : DEFAULT_LOCALE);\n const _fallbackLocale = ref(\n // prettier-ignore\n !isLocalScope || _inheritLocale\n ? root.fallbackLocale.value\n : isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale.value);\n const _messages = ref(getLocaleMessages(_locale.value, options));\n // prettier-ignore\n const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale.value]: {} });\n // prettier-ignore\n const _numberFormats = ref(isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale.value]: {} });\n // prettier-ignore\n const _missingWarn = isLocalScope\n ? root.missingWarn\n : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n // prettier-ignore\n const _fallbackWarn = isLocalScope\n ? root.fallbackWarn\n : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n // prettier-ignore\n const _fallbackRoot = isLocalScope\n ? root.fallbackRoot\n : isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n // configure fall back to root\n const _fallbackFormat = !!options.fallbackFormat;\n // runtime missing\n const _missing = isFunction(options.missing) ? options.missing : null;\n // postTranslation handler\n const _postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n // prettier-ignore\n const _warnHtmlMessage = isLocalScope\n ? root.warnHtmlMessage\n : isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n const _escapeParameter = !!options.escapeParameter;\n // prettier-ignore\n const _modifiers = isLocalScope\n ? root.modifiers\n : isPlainObject(options.modifiers)\n ? options.modifiers\n : {};\n // pluralRules\n const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);\n // track reactivity\n function trackReactivityValues() {\n return [\n _locale.value,\n _fallbackLocale.value,\n _messages.value,\n _datetimeFormats.value,\n _numberFormats.value\n ];\n }\n // locale\n const locale = computed({\n get: () => {\n return _composer.value ? _composer.value.locale.value : _locale.value;\n },\n set: val => {\n if (_composer.value) {\n _composer.value.locale.value = val;\n }\n _locale.value = val;\n }\n });\n // fallbackLocale\n const fallbackLocale = computed({\n get: () => {\n return _composer.value\n ? _composer.value.fallbackLocale.value\n : _fallbackLocale.value;\n },\n set: val => {\n if (_composer.value) {\n _composer.value.fallbackLocale.value = val;\n }\n _fallbackLocale.value = val;\n }\n });\n // messages\n const messages = computed(() => {\n if (_composer.value) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _composer.value.messages.value;\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _messages.value;\n }\n });\n const datetimeFormats = computed(() => _datetimeFormats.value);\n const numberFormats = computed(() => _numberFormats.value);\n function getPostTranslationHandler() {\n return _composer.value\n ? _composer.value.getPostTranslationHandler()\n : _postTranslation;\n }\n function setPostTranslationHandler(handler) {\n if (_composer.value) {\n _composer.value.setPostTranslationHandler(handler);\n }\n }\n function getMissingHandler() {\n return _composer.value ? _composer.value.getMissingHandler() : _missing;\n }\n function setMissingHandler(handler) {\n if (_composer.value) {\n _composer.value.setMissingHandler(handler);\n }\n }\n function warpWithDeps(fn) {\n trackReactivityValues();\n return fn();\n }\n function t(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))\n : warpWithDeps(() => '');\n }\n function rt(...args) {\n return _composer.value\n ? Reflect.apply(_composer.value.rt, null, [...args])\n : '';\n }\n function d(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))\n : warpWithDeps(() => '');\n }\n function n(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))\n : warpWithDeps(() => '');\n }\n function tm(key) {\n return _composer.value ? _composer.value.tm(key) : {};\n }\n function te(key, locale) {\n return _composer.value ? _composer.value.te(key, locale) : false;\n }\n function getLocaleMessage(locale) {\n return _composer.value ? _composer.value.getLocaleMessage(locale) : {};\n }\n function setLocaleMessage(locale, message) {\n if (_composer.value) {\n _composer.value.setLocaleMessage(locale, message);\n _messages.value[locale] = message;\n }\n }\n function mergeLocaleMessage(locale, message) {\n if (_composer.value) {\n _composer.value.mergeLocaleMessage(locale, message);\n }\n }\n function getDateTimeFormat(locale) {\n return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};\n }\n function setDateTimeFormat(locale, format) {\n if (_composer.value) {\n _composer.value.setDateTimeFormat(locale, format);\n _datetimeFormats.value[locale] = format;\n }\n }\n function mergeDateTimeFormat(locale, format) {\n if (_composer.value) {\n _composer.value.mergeDateTimeFormat(locale, format);\n }\n }\n function getNumberFormat(locale) {\n return _composer.value ? _composer.value.getNumberFormat(locale) : {};\n }\n function setNumberFormat(locale, format) {\n if (_composer.value) {\n _composer.value.setNumberFormat(locale, format);\n _numberFormats.value[locale] = format;\n }\n }\n function mergeNumberFormat(locale, format) {\n if (_composer.value) {\n _composer.value.mergeNumberFormat(locale, format);\n }\n }\n const wrapper = {\n get id() {\n return _composer.value ? _composer.value.id : -1;\n },\n locale,\n fallbackLocale,\n messages,\n datetimeFormats,\n numberFormats,\n get inheritLocale() {\n return _composer.value ? _composer.value.inheritLocale : _inheritLocale;\n },\n set inheritLocale(val) {\n if (_composer.value) {\n _composer.value.inheritLocale = val;\n }\n },\n get availableLocales() {\n return _composer.value\n ? _composer.value.availableLocales\n : Object.keys(_messages.value);\n },\n get modifiers() {\n return (_composer.value ? _composer.value.modifiers : _modifiers);\n },\n get pluralRules() {\n return (_composer.value ? _composer.value.pluralRules : _pluralRules);\n },\n get isGlobal() {\n return _composer.value ? _composer.value.isGlobal : false;\n },\n get missingWarn() {\n return _composer.value ? _composer.value.missingWarn : _missingWarn;\n },\n set missingWarn(val) {\n if (_composer.value) {\n _composer.value.missingWarn = val;\n }\n },\n get fallbackWarn() {\n return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;\n },\n set fallbackWarn(val) {\n if (_composer.value) {\n _composer.value.missingWarn = val;\n }\n },\n get fallbackRoot() {\n return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;\n },\n set fallbackRoot(val) {\n if (_composer.value) {\n _composer.value.fallbackRoot = val;\n }\n },\n get fallbackFormat() {\n return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;\n },\n set fallbackFormat(val) {\n if (_composer.value) {\n _composer.value.fallbackFormat = val;\n }\n },\n get warnHtmlMessage() {\n return _composer.value\n ? _composer.value.warnHtmlMessage\n : _warnHtmlMessage;\n },\n set warnHtmlMessage(val) {\n if (_composer.value) {\n _composer.value.warnHtmlMessage = val;\n }\n },\n get escapeParameter() {\n return _composer.value\n ? _composer.value.escapeParameter\n : _escapeParameter;\n },\n set escapeParameter(val) {\n if (_composer.value) {\n _composer.value.escapeParameter = val;\n }\n },\n t,\n getPostTranslationHandler,\n setPostTranslationHandler,\n getMissingHandler,\n setMissingHandler,\n rt,\n d,\n n,\n tm,\n te,\n getLocaleMessage,\n setLocaleMessage,\n mergeLocaleMessage,\n getDateTimeFormat,\n setDateTimeFormat,\n mergeDateTimeFormat,\n getNumberFormat,\n setNumberFormat,\n mergeNumberFormat\n };\n function sync(composer) {\n composer.locale.value = _locale.value;\n composer.fallbackLocale.value = _fallbackLocale.value;\n Object.keys(_messages.value).forEach(locale => {\n composer.mergeLocaleMessage(locale, _messages.value[locale]);\n });\n Object.keys(_datetimeFormats.value).forEach(locale => {\n composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);\n });\n Object.keys(_numberFormats.value).forEach(locale => {\n composer.mergeNumberFormat(locale, _numberFormats.value[locale]);\n });\n composer.escapeParameter = _escapeParameter;\n composer.fallbackFormat = _fallbackFormat;\n composer.fallbackRoot = _fallbackRoot;\n composer.fallbackWarn = _fallbackWarn;\n composer.missingWarn = _missingWarn;\n composer.warnHtmlMessage = _warnHtmlMessage;\n }\n onBeforeMount(() => {\n if (instance.proxy == null || instance.proxy.$i18n == null) {\n throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const composer = (_composer.value = instance.proxy.$i18n\n .__composer);\n if (scope === 'global') {\n _locale.value = composer.locale.value;\n _fallbackLocale.value = composer.fallbackLocale.value;\n _messages.value = composer.messages.value;\n _datetimeFormats.value = composer.datetimeFormats.value;\n _numberFormats.value = composer.numberFormats.value;\n }\n else if (isLocalScope) {\n sync(composer);\n }\n });\n return wrapper;\n}\nconst globalExportProps = [\n 'locale',\n 'fallbackLocale',\n 'availableLocales'\n];\nconst globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']\n ;\nfunction injectGlobalFields(app, composer) {\n const i18n = Object.create(null);\n globalExportProps.forEach(prop => {\n const desc = Object.getOwnPropertyDescriptor(composer, prop);\n if (!desc) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const wrap = isRef(desc.value) // check computed props\n ? {\n get() {\n return desc.value.value;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n set(val) {\n desc.value.value = val;\n }\n }\n : {\n get() {\n return desc.get && desc.get();\n }\n };\n Object.defineProperty(i18n, prop, wrap);\n });\n app.config.globalProperties.$i18n = i18n;\n globalExportMethods.forEach(method => {\n const desc = Object.getOwnPropertyDescriptor(composer, method);\n if (!desc || !desc.value) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n Object.defineProperty(app.config.globalProperties, `$${method}`, desc);\n });\n const dispose = () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete app.config.globalProperties.$i18n;\n globalExportMethods.forEach(method => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete app.config.globalProperties[`$${method}`];\n });\n };\n return dispose;\n}\n\n{\n initFeatureFlags();\n}\n// register message compiler at vue-i18n\nif (__INTLIFY_JIT_COMPILATION__) {\n registerMessageCompiler(compile);\n}\nelse {\n registerMessageCompiler(compileToFunction);\n}\n// register message resolver at vue-i18n\nregisterMessageResolver(resolveValue);\n// register fallback locale at vue-i18n\nregisterLocaleFallbacker(fallbackWithLocaleChain);\n// NOTE: experimental !!\nif ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n const target = getGlobalThis();\n target.__INTLIFY__ = true;\n setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);\n}\nif ((process.env.NODE_ENV !== 'production')) ;\n\nexport { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, castToVueI18n, createI18n, useI18n, vTDirective };\n","\r\n\r\n\r\n\r\n\r\n","import {\r\n ConnectingLink,\r\n LGraphNode,\r\n Vector2,\r\n INodeInputSlot,\r\n INodeOutputSlot,\r\n INodeSlot\r\n} from '@comfyorg/litegraph'\r\n\r\nexport class ConnectingLinkImpl implements ConnectingLink {\r\n node: LGraphNode\r\n slot: number\r\n input: INodeInputSlot | null\r\n output: INodeOutputSlot | null\r\n pos: Vector2\r\n\r\n constructor(\r\n node: LGraphNode,\r\n slot: number,\r\n input: INodeInputSlot | null,\r\n output: INodeOutputSlot | null,\r\n pos: Vector2\r\n ) {\r\n this.node = node\r\n this.slot = slot\r\n this.input = input\r\n this.output = output\r\n this.pos = pos\r\n }\r\n\r\n static createFromPlainObject(obj: ConnectingLink) {\r\n return new ConnectingLinkImpl(\r\n obj.node,\r\n obj.slot,\r\n obj.input,\r\n obj.output,\r\n obj.pos\r\n )\r\n }\r\n\r\n get type(): string | null {\r\n const result = this.input ? this.input.type : this.output.type\r\n return result === -1 ? null : result\r\n }\r\n\r\n /**\r\n * Which slot type is release and need to be reconnected.\r\n * - 'output' means we need a new node's outputs slot to connect with this link\r\n */\r\n get releaseSlotType(): 'input' | 'output' {\r\n return this.output ? 'input' : 'output'\r\n }\r\n\r\n connectTo(newNode: LGraphNode) {\r\n const newNodeSlots =\r\n this.releaseSlotType === 'output' ? newNode.outputs : newNode.inputs\r\n const newNodeSlot = newNodeSlots.findIndex(\r\n (slot: INodeSlot) =>\r\n slot.type === this.type || slot.type === '*' || this.type === '*'\r\n )\r\n\r\n if (newNodeSlot === -1) {\r\n console.warn(\r\n `Could not find slot with type ${this.type} on node ${newNode.title}. This should never happen`\r\n )\r\n return\r\n }\r\n\r\n if (this.releaseSlotType === 'input') {\r\n this.node.connect(this.slot, newNode, newNodeSlot)\r\n } else {\r\n newNode.connect(newNodeSlot, this.node, this.slot)\r\n }\r\n }\r\n}\r\n","\r\n\r\n\r\n\r\n\r\n","\r\n\r\n\r\n\r\n\r\n","function _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nexport { _arrayWithHoles as default };","function _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = !0,\n o = !1;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = !0, n = r;\n } finally {\n try {\n if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nexport { _iterableToArrayLimit as default };","function _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nexport { _arrayLikeToArray as default };","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0;\n }\n}\nexport { _unsupportedIterableToArray as default };","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nexport { _nonIterableRest as default };","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nfunction _slicedToArray(r, e) {\n return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();\n}\nexport { _slicedToArray as default };","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bind = void 0;\nfunction bind(target, _a) {\n var type = _a.type, listener = _a.listener, options = _a.options;\n target.addEventListener(type, listener, options);\n return function unbind() {\n target.removeEventListener(type, listener, options);\n };\n}\nexports.bind = bind;\n","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bindAll = void 0;\nvar bind_1 = require(\"./bind\");\nfunction toOptions(value) {\n if (typeof value === 'undefined') {\n return undefined;\n }\n if (typeof value === 'boolean') {\n return {\n capture: value,\n };\n }\n return value;\n}\nfunction getBinding(original, sharedOptions) {\n if (sharedOptions == null) {\n return original;\n }\n var binding = __assign(__assign({}, original), { options: __assign(__assign({}, toOptions(sharedOptions)), toOptions(original.options)) });\n return binding;\n}\nfunction bindAll(target, bindings, sharedOptions) {\n var unbinds = bindings.map(function (original) {\n var binding = getBinding(original, sharedOptions);\n return (0, bind_1.bind)(target, binding);\n });\n return function unbindAll() {\n unbinds.forEach(function (unbind) { return unbind(); });\n };\n}\nexports.bindAll = bindAll;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bindAll = exports.bind = void 0;\nvar bind_1 = require(\"./bind\");\nObject.defineProperty(exports, \"bind\", { enumerable: true, get: function () { return bind_1.bind; } });\nvar bind_all_1 = require(\"./bind-all\");\nObject.defineProperty(exports, \"bindAll\", { enumerable: true, get: function () { return bind_all_1.bindAll; } });\n","// pulling this into a separate file so adapter(s) that don't\n// need the honey pot can pay as little as possible for it.\nexport var honeyPotDataAttribute = 'data-pdnd-honey-pot';","import { honeyPotDataAttribute } from './honey-pot-data-attribute';\nexport function isHoneyPotElement(target) {\n return target instanceof Element && target.hasAttribute(honeyPotDataAttribute);\n}","import _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\nimport { isHoneyPotElement } from './is-honey-pot-element';\nexport function getElementFromPointWithoutHoneypot(client) {\n // eslint-disable-next-line no-restricted-syntax\n var _document$elementsFro = document.elementsFromPoint(client.x, client.y),\n _document$elementsFro2 = _slicedToArray(_document$elementsFro, 2),\n top = _document$elementsFro2[0],\n second = _document$elementsFro2[1];\n if (!top) {\n return null;\n }\n if (isHoneyPotElement(top)) {\n return second !== null && second !== void 0 ? second : null;\n }\n return top;\n}","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nexport { _typeof as default };","import _typeof from \"./typeof.js\";\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nexport { toPrimitive as default };","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nexport { _defineProperty as default };","// Maximum possible z-index\n// https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index\nexport var maxZIndex = 2147483647;","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nimport { bind, bindAll } from 'bind-event-listener';\nimport { maxZIndex } from '../util/max-z-index';\nimport { honeyPotDataAttribute } from './honey-pot-data-attribute';\nvar honeyPotSize = 2;\nvar halfHoneyPotSize = honeyPotSize / 2;\n\n/**\n * `clientX` and `clientY` can be in sub pixels (eg `2.332`)\n * However, browser hitbox testing is commonly do to the closest pixel.\n *\n * → https://issues.chromium.org/issues/40940531\n *\n * To be sure that the honey pot will be over the `client` position,\n * we `.floor()` `clientX` and`clientY` and then make it `2px` in size.\n **/\nfunction floorToClosestPixel(point) {\n return {\n x: Math.floor(point.x),\n y: Math.floor(point.y)\n };\n}\n\n/**\n * We want to make sure the honey pot sits around the users position.\n * This seemed to be the most resilient while testing.\n */\nfunction pullBackByHalfHoneyPotSize(point) {\n return {\n x: point.x - halfHoneyPotSize,\n y: point.y - halfHoneyPotSize\n };\n}\n\n/**\n * Prevent the honey pot from changing the window size.\n * This is super unlikely to occur, but just being safe.\n */\nfunction preventGoingBackwardsOffScreen(point) {\n return {\n x: Math.max(point.x, 0),\n y: Math.max(point.y, 0)\n };\n}\n\n/**\n * Prevent the honey pot from changing the window size.\n * This is super unlikely to occur, but just being safe.\n */\nfunction preventGoingForwardsOffScreen(point) {\n return {\n x: Math.min(point.x, window.innerWidth - honeyPotSize),\n y: Math.min(point.y, window.innerHeight - honeyPotSize)\n };\n}\n\n/**\n * Create a `2x2` `DOMRect` around the `client` position\n */\nfunction getHoneyPotRectFor(_ref) {\n var client = _ref.client;\n var point = preventGoingForwardsOffScreen(preventGoingBackwardsOffScreen(pullBackByHalfHoneyPotSize(floorToClosestPixel(client))));\n\n // When debugging, it is helpful to\n // make this element a bit bigger\n return DOMRect.fromRect({\n x: point.x,\n y: point.y,\n width: honeyPotSize,\n height: honeyPotSize\n });\n}\nfunction getRectStyles(_ref2) {\n var clientRect = _ref2.clientRect;\n return {\n left: \"\".concat(clientRect.left, \"px\"),\n top: \"\".concat(clientRect.top, \"px\"),\n width: \"\".concat(clientRect.width, \"px\"),\n height: \"\".concat(clientRect.height, \"px\")\n };\n}\nfunction isWithin(_ref3) {\n var client = _ref3.client,\n clientRect = _ref3.clientRect;\n return (\n // is within horizontal bounds\n client.x >= clientRect.x && client.x <= clientRect.x + clientRect.width &&\n // is within vertical bounds\n client.y >= clientRect.y && client.y <= clientRect.y + clientRect.height\n );\n}\n/**\n * The honey pot fix is designed to get around a painful bug in all browsers.\n *\n * [Overview](https://www.youtube.com/watch?v=udE9qbFTeQg)\n *\n * **Background**\n *\n * When a drag starts, browsers incorrectly think that the users pointer is\n * still depressed where the drag started. Any element that goes under this position\n * will be entered into, causing `\"mouseenter\"` events and `\":hover\"` styles to be applied.\n *\n * _This is a violation of the spec_\n *\n * > \"From the moment that the user agent is to initiate the drag-and-drop operation,\n * > until the end \tof the drag-and-drop operation, device input events\n * > (e.g. mouse and keyboard events) must be suppressed.\"\n * >\n * > - https://html.spec.whatwg.org/multipage/dnd.html#drag-and-drop-processing-model\n *\n * _Some impacts_\n *\n * - `\":hover\"` styles being applied where they shouldn't (looks messy)\n * - components such as tooltips responding to `\"mouseenter\"` can show during a drag,\n * and on an element the user isn't even over\n *\n * Bug: https://issues.chromium.org/issues/41129937\n *\n * **Honey pot fix**\n *\n * 1. Create an element where the browser thinks the depressed pointer is\n * to absorb the incorrect pointer events\n * 2. Remove that element when it is no longer needed\n */\nfunction mountHoneyPot(_ref4) {\n var initial = _ref4.initial;\n var element = document.createElement('div');\n element.setAttribute(honeyPotDataAttribute, 'true');\n\n // can shift during the drag thanks to Firefox\n var clientRect = getHoneyPotRectFor({\n client: initial\n });\n Object.assign(element.style, _objectSpread(_objectSpread({\n // Setting a background color explicitly to avoid any inherited styles.\n // Looks like this could be `opacity: 0`, but worried that _might_\n // cause the element to be ignored on some platforms.\n // When debugging, set backgroundColor to something like \"red\".\n backgroundColor: 'transparent',\n position: 'fixed',\n // Being explicit to avoid inheriting styles\n padding: 0,\n margin: 0,\n boxSizing: 'border-box'\n }, getRectStyles({\n clientRect: clientRect\n })), {}, {\n // We want this element to absorb pointer events,\n // it's kind of the whole point 😉\n pointerEvents: 'auto',\n // Want to make sure the honey pot is top of everything else.\n // Don't need to worry about native drag previews, as they will\n // have been rendered (and removed) before the honey pot is rendered\n zIndex: maxZIndex\n }));\n document.body.appendChild(element);\n\n /**\n * 🦊 In firefox we can get `\"pointermove\"` events after the drag\n * has started, which is a spec violation.\n * The final `\"pointermove\"` will reveal where the \"depressed\" position\n * is for our honey pot fix.\n */\n var unbindPointerMove = bind(window, {\n type: 'pointermove',\n listener: function listener(event) {\n var client = {\n x: event.clientX,\n y: event.clientY\n };\n clientRect = getHoneyPotRectFor({\n client: client\n });\n Object.assign(element.style, getRectStyles({\n clientRect: clientRect\n }));\n },\n // using capture so we are less likely to be impacted by event stopping\n options: {\n capture: true\n }\n });\n return function finish(_ref5) {\n var current = _ref5.current;\n // Don't need this any more\n unbindPointerMove();\n\n // If the user is hover the honey pot, we remove it\n // so that the user can continue to interact with the page normally.\n if (isWithin({\n client: current,\n clientRect: clientRect\n })) {\n element.remove();\n return;\n }\n function cleanup() {\n unbindPostDragEvents();\n element.remove();\n }\n var unbindPostDragEvents = bindAll(window, [{\n type: 'pointerdown',\n listener: cleanup\n }, {\n type: 'pointermove',\n listener: cleanup\n }, {\n type: 'focusin',\n listener: cleanup\n }, {\n type: 'focusout',\n listener: cleanup\n },\n // a 'pointerdown' should happen before 'dragstart', but just being super safe\n {\n type: 'dragstart',\n listener: cleanup\n },\n // if the user has dragged something out of the window\n // and then is dragging something back into the window\n // the first events we will see are \"dragenter\" (and then \"dragover\").\n // So if we see any of these we need to clear the post drag fix.\n {\n type: 'dragenter',\n listener: cleanup\n }, {\n type: 'dragover',\n listener: cleanup\n }\n\n // Not adding a \"wheel\" event listener, as \"wheel\" by itself does not\n // resolve the bug.\n ], {\n // Using `capture` so less likely to be impacted by other code stopping events\n capture: true\n });\n };\n}\nexport function makeHoneyPotFix() {\n var latestPointerMove = null;\n function bindEvents() {\n // For sanity, only collecting this value from when events are first bound.\n // This prevents the case where a super old \"pointermove\" could be used\n // from a prior interaction.\n latestPointerMove = null;\n return bind(window, {\n type: 'pointermove',\n listener: function listener(event) {\n latestPointerMove = {\n x: event.clientX,\n y: event.clientY\n };\n },\n // listening for pointer move in capture phase\n // so we are less likely to be impacted by events being stopped.\n options: {\n capture: true\n }\n });\n }\n function getOnPostDispatch() {\n var finish = null;\n return function onPostEvent(_ref6) {\n var eventName = _ref6.eventName,\n payload = _ref6.payload;\n // We are adding the honey pot `onDragStart` so we don't\n // impact the creation of the native drag preview.\n if (eventName === 'onDragStart') {\n var _latestPointerMove;\n var input = payload.location.initial.input;\n\n // Sometimes there will be no latest \"pointermove\" (eg iOS).\n // In which case, we use the start position of the drag.\n var initial = (_latestPointerMove = latestPointerMove) !== null && _latestPointerMove !== void 0 ? _latestPointerMove : {\n x: input.clientX,\n y: input.clientY\n };\n\n // Don't need to defensively call `finish()` as `onDrop` from\n // one interaction is guaranteed to be called before `onDragStart`\n // of the next.\n finish = mountHoneyPot({\n initial: initial\n });\n }\n if (eventName === 'onDrop') {\n var _finish;\n var _input = payload.location.current.input;\n (_finish = finish) === null || _finish === void 0 || _finish({\n current: {\n x: _input.clientX,\n y: _input.clientY\n }\n });\n finish = null;\n // this interaction is finished, we want to use\n // the latest \"pointermove\" for each interaction\n latestPointerMove = null;\n }\n };\n }\n return {\n bindEvents: bindEvents,\n getOnPostDispatch: getOnPostDispatch\n };\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return arrayLikeToArray(r);\n}\nexport { _arrayWithoutHoles as default };","function _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nexport { _iterableToArray as default };","function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nexport { _nonIterableSpread as default };","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nfunction _toConsumableArray(r) {\n return arrayWithoutHoles(r) || iterableToArray(r) || unsupportedIterableToArray(r) || nonIterableSpread();\n}\nexport { _toConsumableArray as default };","/** Provide a function that you only ever want to be called a single time */\nexport function once(fn) {\n var cache = null;\n return function wrapped() {\n if (!cache) {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n var result = fn.apply(this, args);\n cache = {\n result: result\n };\n }\n return cache.result;\n };\n}","import { once } from '../public-utils/once';\n\n// using `cache` as our `isFirefox()` result will not change in a browser\n\n/**\n * Returns `true` if a `Firefox` browser\n * */\nexport var isFirefox = once(function isFirefox() {\n if (process.env.NODE_ENV === 'test') {\n return false;\n }\n return navigator.userAgent.includes('Firefox');\n});","import { once } from '../public-utils/once';\n\n// using `cache` as our `isSafari()` result will not change in a browser\n\n/**\n * Returns `true` if a `Safari` browser.\n * Returns `true` if the browser is running on iOS (they are all Safari).\n * */\nexport var isSafari = once(function isSafari() {\n if (process.env.NODE_ENV === 'test') {\n return false;\n }\n var _navigator = navigator,\n userAgent = _navigator.userAgent;\n return userAgent.includes('AppleWebKit') && !userAgent.includes('Chrome');\n});","import { bindAll } from 'bind-event-listener';\nimport { isSafari } from '../is-safari';\n\n/* For \"dragenter\" events, the browser should set `relatedTarget` to the previous element.\n * For external drag operations, our first \"dragenter\" event should have a `event.relatedTarget` of `null`.\n *\n * Unfortunately in Safari `event.relatedTarget` is *always* set to `null`\n * Safari bug: https://bugs.webkit.org/show_bug.cgi?id=242627\n * To work around this we count \"dragenter\" and \"dragleave\" events */\n\n// Using symbols for event properties so we don't clash with\n// anything on the `event` object\nvar symbols = {\n isLeavingWindow: Symbol('leaving'),\n isEnteringWindow: Symbol('entering')\n};\nexport function isEnteringWindowInSafari(_ref) {\n var dragEnter = _ref.dragEnter;\n if (!isSafari()) {\n return false;\n }\n return dragEnter.hasOwnProperty(symbols.isEnteringWindow);\n}\nexport function isLeavingWindowInSafari(_ref2) {\n var dragLeave = _ref2.dragLeave;\n if (!isSafari()) {\n return false;\n }\n return dragLeave.hasOwnProperty(symbols.isLeavingWindow);\n}\n(function fixSafari() {\n // Don't do anything when server side rendering\n if (typeof window === 'undefined') {\n return;\n }\n\n // rather than checking the userAgent for \"jsdom\" we can do this check\n // so that the check will be removed completely in production code\n if (process.env.NODE_ENV === 'test') {\n return;\n }\n if (!isSafari()) {\n return;\n }\n function getInitialState() {\n return {\n enterCount: 0,\n isOverWindow: false\n };\n }\n var state = getInitialState();\n function resetState() {\n state = getInitialState();\n }\n\n // These event listeners are bound _forever_ and _never_ removed\n // We don't bother cleaning up these event listeners (for now)\n // as this workaround is only for Safari\n\n // This is how the event count works:\n //\n // lift (+1 enterCount)\n // - dragstart(draggable) [enterCount: 0]\n // - dragenter(draggable) [enterCount: 1]\n // leaving draggable (+0 enterCount)\n // - dragenter(document.body) [enterCount: 2]\n // - dragleave(draggable) [enterCount: 1]\n // leaving window (-1 enterCount)\n // - dragleave(document.body) [enterCount: 0] {leaving the window}\n\n // Things to note:\n // - dragenter and dragleave bubble\n // - the first dragenter when entering a window might not be on `window`\n // - it could be on an element that is pressed up against the window\n // - (so we cannot rely on `event.target` values)\n\n bindAll(window, [{\n type: 'dragstart',\n listener: function listener() {\n state.enterCount = 0;\n // drag start occurs in the source window\n state.isOverWindow = true;\n // When a drag first starts it will also trigger a \"dragenter\" on the draggable element\n }\n }, {\n type: 'drop',\n listener: resetState\n }, {\n type: 'dragend',\n listener: resetState\n }, {\n type: 'dragenter',\n listener: function listener(event) {\n if (!state.isOverWindow && state.enterCount === 0) {\n // Patching the `event` object\n // The `event` object is shared with all event listeners for the event\n // @ts-expect-error: adding property to the event object\n event[symbols.isEnteringWindow] = true;\n }\n state.isOverWindow = true;\n state.enterCount++;\n }\n }, {\n type: 'dragleave',\n listener: function listener(event) {\n state.enterCount--;\n if (state.isOverWindow && state.enterCount === 0) {\n // Patching the `event` object as it is shared with all event listeners\n // The `event` object is shared with all event listeners for the event\n // @ts-expect-error: adding property to the event object\n event[symbols.isLeavingWindow] = true;\n state.isOverWindow = false;\n }\n }\n }],\n // using `capture: true` so that adding event listeners\n // in bubble phase will have the correct symbols\n {\n capture: true\n });\n})();","/**\n * Does the `EventTarget` look like a `Node` based on \"duck typing\".\n *\n * Helpful when the `Node` might be outside of the current document\n * so we cannot to an `target instanceof Node` check.\n */\nfunction isNodeLike(target) {\n return 'nodeName' in target;\n}\n\n/**\n * Is an `EventTarget` a `Node` from another `window`?\n */\nexport function isFromAnotherWindow(eventTarget) {\n return isNodeLike(eventTarget) && eventTarget.ownerDocument !== document;\n}","import { isFirefox } from '../is-firefox';\nimport { isSafari } from '../is-safari';\nimport { isLeavingWindowInSafari } from './count-events-for-safari';\nimport { isFromAnotherWindow } from './is-from-another-window';\nexport function isLeavingWindow(_ref) {\n var dragLeave = _ref.dragLeave;\n var type = dragLeave.type,\n relatedTarget = dragLeave.relatedTarget;\n if (type !== 'dragleave') {\n return false;\n }\n if (isSafari()) {\n return isLeavingWindowInSafari({\n dragLeave: dragLeave\n });\n }\n\n // Standard check: if going to `null` we are leaving the `window`\n if (relatedTarget == null) {\n return true;\n }\n\n /**\n * 🦊 Exception: `iframe` in Firefox (`125.0`)\n *\n * Case 1: parent `window` → child `iframe`\n * `dragLeave.relatedTarget` is element _inside_ the child `iframe`\n * (foreign element)\n *\n * Case 2: child `iframe` → parent `window`\n * `dragLeave.relatedTarget` is the `iframe` in the parent `window`\n * (foreign element)\n */\n\n if (isFirefox()) {\n return isFromAnotherWindow(relatedTarget);\n }\n\n /**\n * 🌏 Exception: `iframe` in Chrome (`124.0`)\n *\n * Case 1: parent `window` → child `iframe`\n * `dragLeave.relatedTarget` is the `iframe` in the parent `window`\n *\n * Case 2: child `iframe` → parent `window`\n * `dragLeave.relatedTarget` is `null` *(standard check)*\n */\n\n // Case 2\n // Using `instanceof` check as the element will be in the same `window`\n return relatedTarget instanceof HTMLIFrameElement;\n}","export function getBindingsForBrokenDrags(_ref) {\n var onDragEnd = _ref.onDragEnd;\n return [\n // ## Detecting drag ending for removed draggables\n //\n // If a draggable element is removed during a drag and the user drops:\n // 1. if over a valid drop target: we get a \"drop\" event to know the drag is finished\n // 2. if not over a valid drop target (or cancelled): we get nothing\n // The \"dragend\" event will not fire on the source draggable if it has been\n // removed from the DOM.\n // So we need to figure out if a drag operation has finished by looking at other events\n // We can do this by looking at other events\n\n // ### First detection: \"pointermove\" events\n\n // 1. \"pointermove\" events cannot fire during a drag and drop operation\n // according to the spec. So if we get a \"pointermove\" it means that\n // the drag and drop operations has finished. So if we get a \"pointermove\"\n // we know that the drag is over\n // 2. 🦊😤 Drag and drop operations are _supposed_ to suppress\n // other pointer events. However, firefox will allow a few\n // pointer event to get through after a drag starts.\n // The most I've seen is 3\n {\n type: 'pointermove',\n listener: function () {\n var callCount = 0;\n return function listener() {\n // Using 20 as it is far bigger than the most observed (3)\n if (callCount < 20) {\n callCount++;\n return;\n }\n onDragEnd();\n };\n }()\n },\n // ### Second detection: \"pointerdown\" events\n\n // If we receive this event then we know that a drag operation has finished\n // and potentially another one is about to start.\n // Note: `pointerdown` fires on all browsers / platforms before \"dragstart\"\n {\n type: 'pointerdown',\n listener: onDragEnd\n }];\n}","export function getInput(event) {\n return {\n altKey: event.altKey,\n button: event.button,\n buttons: event.buttons,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n clientX: event.clientX,\n clientY: event.clientY,\n pageX: event.pageX,\n pageY: event.pageY\n };\n}","var rafSchd = function rafSchd(fn) {\n var lastArgs = [];\n var frameId = null;\n\n var wrapperFn = function wrapperFn() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n lastArgs = args;\n\n if (frameId) {\n return;\n }\n\n frameId = requestAnimationFrame(function () {\n frameId = null;\n fn.apply(void 0, lastArgs);\n });\n };\n\n wrapperFn.cancel = function () {\n if (!frameId) {\n return;\n }\n\n cancelAnimationFrame(frameId);\n frameId = null;\n };\n\n return wrapperFn;\n};\n\nexport default rafSchd;\n","import rafSchd from 'raf-schd';\nvar scheduleOnDrag = rafSchd(function (fn) {\n return fn();\n});\nvar dragStart = function () {\n var scheduled = null;\n function schedule(fn) {\n var frameId = requestAnimationFrame(function () {\n scheduled = null;\n fn();\n });\n scheduled = {\n frameId: frameId,\n fn: fn\n };\n }\n function flush() {\n if (scheduled) {\n cancelAnimationFrame(scheduled.frameId);\n scheduled.fn();\n scheduled = null;\n }\n }\n return {\n schedule: schedule,\n flush: flush\n };\n}();\nexport function makeDispatch(_ref) {\n var source = _ref.source,\n initial = _ref.initial,\n dispatchEvent = _ref.dispatchEvent;\n var previous = {\n dropTargets: []\n };\n function safeDispatch(args) {\n dispatchEvent(args);\n previous = {\n dropTargets: args.payload.location.current.dropTargets\n };\n }\n var dispatch = {\n start: function start(_ref2) {\n var nativeSetDragImage = _ref2.nativeSetDragImage;\n // Ensuring that both `onGenerateDragPreview` and `onDragStart` get the same location.\n // We do this so that `previous` is`[]` in `onDragStart` (which is logical)\n var location = {\n current: initial,\n previous: previous,\n initial: initial\n };\n // a `onGenerateDragPreview` does _not_ add another entry for `previous`\n // onDragPreview\n safeDispatch({\n eventName: 'onGenerateDragPreview',\n payload: {\n source: source,\n location: location,\n nativeSetDragImage: nativeSetDragImage\n }\n });\n dragStart.schedule(function () {\n safeDispatch({\n eventName: 'onDragStart',\n payload: {\n source: source,\n location: location\n }\n });\n });\n },\n dragUpdate: function dragUpdate(_ref3) {\n var current = _ref3.current;\n dragStart.flush();\n scheduleOnDrag.cancel();\n safeDispatch({\n eventName: 'onDropTargetChange',\n payload: {\n source: source,\n location: {\n initial: initial,\n previous: previous,\n current: current\n }\n }\n });\n },\n drag: function drag(_ref4) {\n var current = _ref4.current;\n scheduleOnDrag(function () {\n dragStart.flush();\n var location = {\n initial: initial,\n previous: previous,\n current: current\n };\n safeDispatch({\n eventName: 'onDrag',\n payload: {\n source: source,\n location: location\n }\n });\n });\n },\n drop: function drop(_ref5) {\n var current = _ref5.current,\n updatedSourcePayload = _ref5.updatedSourcePayload;\n dragStart.flush();\n scheduleOnDrag.cancel();\n safeDispatch({\n eventName: 'onDrop',\n payload: {\n source: updatedSourcePayload !== null && updatedSourcePayload !== void 0 ? updatedSourcePayload : source,\n location: {\n current: current,\n previous: previous,\n initial: initial\n }\n }\n });\n }\n };\n return dispatch;\n}","import _toConsumableArray from \"@babel/runtime/helpers/toConsumableArray\";\nimport { bindAll } from 'bind-event-listener';\nimport { getElementFromPointWithoutHoneypot } from '../honey-pot-fix/get-element-from-point-without-honey-pot';\nimport { isHoneyPotElement } from '../honey-pot-fix/is-honey-pot-element';\nimport { isLeavingWindow } from '../util/changing-window/is-leaving-window';\nimport { getBindingsForBrokenDrags } from '../util/detect-broken-drag';\nimport { getInput } from '../util/get-input';\nimport { makeDispatch } from './dispatch-consumer-event';\nvar globalState = {\n isActive: false\n};\nfunction canStart() {\n return !globalState.isActive;\n}\nfunction getNativeSetDragImage(event) {\n if (event.dataTransfer) {\n // need to use `.bind` as `setDragImage` is required\n // to be run with `event.dataTransfer` as the \"this\" context\n return event.dataTransfer.setDragImage.bind(event.dataTransfer);\n }\n return null;\n}\nfunction hasHierarchyChanged(_ref) {\n var current = _ref.current,\n next = _ref.next;\n if (current.length !== next.length) {\n return true;\n }\n // not checking stickiness, data or dropEffect,\n // just whether the hierarchy has changed\n for (var i = 0; i < current.length; i++) {\n if (current[i].element !== next[i].element) {\n return true;\n }\n }\n return false;\n}\nfunction start(_ref2) {\n var event = _ref2.event,\n dragType = _ref2.dragType,\n getDropTargetsOver = _ref2.getDropTargetsOver,\n dispatchEvent = _ref2.dispatchEvent;\n if (!canStart()) {\n return;\n }\n var initial = getStartLocation({\n event: event,\n dragType: dragType,\n getDropTargetsOver: getDropTargetsOver\n });\n globalState.isActive = true;\n var state = {\n current: initial\n };\n\n // Setting initial drop effect for the drag\n setDropEffectOnEvent({\n event: event,\n current: initial.dropTargets\n });\n var dispatch = makeDispatch({\n source: dragType.payload,\n dispatchEvent: dispatchEvent,\n initial: initial\n });\n function updateState(next) {\n // only looking at whether hierarchy has changed to determine whether something as 'changed'\n var hasChanged = hasHierarchyChanged({\n current: state.current.dropTargets,\n next: next.dropTargets\n });\n\n // Always updating the state to include latest data, dropEffect and stickiness\n // Only updating consumers if the hierarchy has changed in some way\n // Consumers can get the latest data by using `onDrag`\n state.current = next;\n if (hasChanged) {\n dispatch.dragUpdate({\n current: state.current\n });\n }\n }\n function onUpdateEvent(event) {\n var input = getInput(event);\n\n // If we are over the honey pot, we need to get the element\n // that the user would have been over if not for the honey pot\n var target = isHoneyPotElement(event.target) ? getElementFromPointWithoutHoneypot({\n x: input.clientX,\n y: input.clientY\n }) : event.target;\n var nextDropTargets = getDropTargetsOver({\n target: target,\n input: input,\n source: dragType.payload,\n current: state.current.dropTargets\n });\n if (nextDropTargets.length) {\n // 🩸 must call `event.preventDefault()` to allow a browser drop to occur\n event.preventDefault();\n setDropEffectOnEvent({\n event: event,\n current: nextDropTargets\n });\n }\n updateState({\n dropTargets: nextDropTargets,\n input: input\n });\n }\n function cancel() {\n // The spec behaviour is that when a drag is cancelled, or when dropping on no drop targets,\n // a \"dragleave\" event is fired on the active drop target before a \"dragend\" event.\n // We are replicating that behaviour in `cancel` if there are any active drop targets to\n // ensure consistent behaviour.\n //\n // Note: When cancelling, or dropping on no drop targets, a \"dragleave\" event\n // will have already cleared the dropTargets to `[]` (as that particular \"dragleave\" has a `relatedTarget` of `null`)\n\n if (state.current.dropTargets.length) {\n updateState({\n dropTargets: [],\n input: state.current.input\n });\n }\n dispatch.drop({\n current: state.current,\n updatedSourcePayload: null\n });\n finish();\n }\n function finish() {\n globalState.isActive = false;\n unbindEvents();\n }\n var unbindEvents = bindAll(window, [{\n // 👋 Note: we are repurposing the `dragover` event as our `drag` event\n // this is because firefox does not publish pointer coordinates during\n // a `drag` event, but does for every other type of drag event\n // `dragover` fires on all elements that are being dragged over\n // Because we are binding to `window` - our `dragover` is effectively the same as a `drag`\n // 🦊😤\n type: 'dragover',\n listener: function listener(event) {\n // We need to regularly calculate the drop targets in order to allow:\n // - dynamic `canDrop()` checks\n // - rapid updating `getData()` calls to attach data in response to user input (eg for edge detection)\n // Sadly we cannot schedule inspecting changes resulting from this event\n // we need to be able to conditionally cancel the event with `event.preventDefault()`\n // to enable the correct native drop experience.\n\n // 1. check to see if anything has changed\n onUpdateEvent(event);\n\n // 2. let consumers know a move has occurred\n // This will include the latest 'input' values\n dispatch.drag({\n current: state.current\n });\n }\n }, {\n type: 'dragenter',\n listener: onUpdateEvent\n }, {\n type: 'dragleave',\n listener: function listener(event) {\n if (!isLeavingWindow({\n dragLeave: event\n })) {\n return;\n }\n\n /**\n * At this point we don't know if a drag is being cancelled,\n * or if a drag is leaving the `window`.\n *\n * Both have:\n * 1. \"dragleave\" (with `relatedTarget: null`)\n * 2. \"dragend\" (a \"dragend\" can occur when outside the `window`)\n *\n * **Clearing drop targets**\n *\n * For either case we are clearing the the drop targets\n *\n * - cancelling: we clear drop targets in `\"dragend\"` anyway\n * - leaving the `window`: we clear the drop targets (to clear stickiness)\n *\n * **Leaving the window and finishing the drag**\n *\n * _internal drags_\n *\n * - The drag continues when the user is outside the `window`\n * and can resume if the user drags back over the `window`,\n * or end when the user drops in an external `window`.\n * - We will get a `\"dragend\"`, or we can listen for other\n * events to determine the drag is finished when the user re-enters the `window`).\n *\n * _external drags_\n *\n * - We conclude the drag operation.\n * - We have no idea if the user will drag back over the `window`,\n * or if the drag ends elsewhere.\n * - We will create a new drag if the user re-enters the `window`.\n *\n * **Not updating `input`**\n *\n * 🐛 Bug[Chrome] the final `\"dragleave\"` has default input values (eg `clientX == 0`)\n * Workaround: intentionally not updating `input` in \"dragleave\"\n * rather than the users current input values\n * - [Conversation](https://twitter.com/alexandereardon/status/1642697633864241152)\n * - [Bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1429937)\n **/\n\n updateState({\n input: state.current.input,\n dropTargets: []\n });\n if (dragType.startedFrom === 'external') {\n cancel();\n }\n }\n }, {\n // A \"drop\" can only happen if the browser allowed the drop\n type: 'drop',\n listener: function listener(event) {\n // Capture the final input.\n // We are capturing the final `input` for the\n // most accurate honey pot experience\n state.current = {\n dropTargets: state.current.dropTargets,\n input: getInput(event)\n };\n\n /** If there are no drop targets, then we will get\n * a \"drop\" event if:\n * - `preventUnhandled()` is being used\n * - there is an unmanaged drop target (eg another library)\n * In these cases, it's up to the consumer\n * to handle the drop if it's not over one of our drop targets\n * - `preventUnhandled()` will cancel the \"drop\"\n * - unmanaged drop targets can handle the \"drop\" how they want to\n * We won't call `event.preventDefault()` in this call path */\n\n if (!state.current.dropTargets.length) {\n cancel();\n return;\n }\n event.preventDefault();\n\n // applying the latest drop effect to the event\n setDropEffectOnEvent({\n event: event,\n current: state.current.dropTargets\n });\n dispatch.drop({\n current: state.current,\n // When dropping something native, we need to extract the latest\n // `.items` from the \"drop\" event as it is now accessible\n updatedSourcePayload: dragType.type === 'external' ? dragType.getDropPayload(event) : null\n });\n finish();\n }\n }, {\n // \"dragend\" fires when on the drag source (eg a draggable element)\n // when the drag is finished.\n // \"dragend\" will fire after \"drop\" (if there was a successful drop)\n // \"dragend\" does not fire if the draggable source has been removed during the drag\n // or for external drag sources (eg files)\n\n // This \"dragend\" listener will not fire if there was a successful drop\n // as we will have already removed the event listener\n\n type: 'dragend',\n listener: function listener(event) {\n // In firefox, the position of the \"dragend\" event can\n // be a bit different to the last \"dragover\" event.\n // Updating the input so we can get the best possible\n // information for the honey pot.\n state.current = {\n dropTargets: state.current.dropTargets,\n input: getInput(event)\n };\n cancel();\n }\n }].concat(_toConsumableArray(getBindingsForBrokenDrags({\n onDragEnd: cancel\n }))),\n // Once we have started a managed drag operation it is important that we see / own all drag events\n // We got one adoption bug pop up where some code was stopping (`event.stopPropagation()`)\n // all \"drop\" events in the bubble phase on the `document.body`.\n // This meant that we never saw the \"drop\" event.\n {\n capture: true\n });\n dispatch.start({\n nativeSetDragImage: getNativeSetDragImage(event)\n });\n}\nfunction setDropEffectOnEvent(_ref3) {\n var _current$;\n var event = _ref3.event,\n current = _ref3.current;\n // setting the `dropEffect` to be the innerMost drop targets dropEffect\n var innerMost = (_current$ = current[0]) === null || _current$ === void 0 ? void 0 : _current$.dropEffect;\n if (innerMost != null && event.dataTransfer) {\n event.dataTransfer.dropEffect = innerMost;\n }\n}\nfunction getStartLocation(_ref4) {\n var event = _ref4.event,\n dragType = _ref4.dragType,\n getDropTargetsOver = _ref4.getDropTargetsOver;\n var input = getInput(event);\n\n // When dragging from outside of the browser,\n // the drag is not being sourced from any local drop targets\n if (dragType.startedFrom === 'external') {\n return {\n input: input,\n dropTargets: []\n };\n }\n var dropTargets = getDropTargetsOver({\n input: input,\n source: dragType.payload,\n target: event.target,\n current: []\n });\n return {\n input: input,\n dropTargets: dropTargets\n };\n}\nexport var lifecycle = {\n canStart: canStart,\n start: start\n};","// Extending `Map` to allow us to link Key and Values together\n\nvar ledger = new Map();\nfunction registerUsage(_ref) {\n var typeKey = _ref.typeKey,\n mount = _ref.mount;\n var entry = ledger.get(typeKey);\n if (entry) {\n entry.usageCount++;\n return entry;\n }\n var initial = {\n typeKey: typeKey,\n unmount: mount(),\n usageCount: 1\n };\n ledger.set(typeKey, initial);\n return initial;\n}\nexport function register(args) {\n var entry = registerUsage(args);\n return function unregister() {\n entry.usageCount--;\n if (entry.usageCount > 0) {\n return;\n }\n // Only a single usage left, remove it\n entry.unmount();\n ledger.delete(args.typeKey);\n };\n}","/** Create a new combined function that will call all the provided functions */\nexport function combine() {\n for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n fns[_key] = arguments[_key];\n }\n return function cleanup() {\n fns.forEach(function (fn) {\n return fn();\n });\n };\n}","export function addAttribute(element, _ref) {\n var attribute = _ref.attribute,\n value = _ref.value;\n element.setAttribute(attribute, value);\n return function () {\n return element.removeAttribute(attribute);\n };\n}","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _toConsumableArray from \"@babel/runtime/helpers/toConsumableArray\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nimport { combine } from '../public-utils/combine';\nimport { addAttribute } from '../util/add-attribute';\nfunction copyReverse(array) {\n return array.slice(0).reverse();\n}\nexport function makeDropTarget(_ref) {\n var typeKey = _ref.typeKey,\n defaultDropEffect = _ref.defaultDropEffect;\n var registry = new WeakMap();\n var dropTargetDataAtt = \"data-drop-target-for-\".concat(typeKey);\n var dropTargetSelector = \"[\".concat(dropTargetDataAtt, \"]\");\n function addToRegistry(args) {\n registry.set(args.element, args);\n return function () {\n return registry.delete(args.element);\n };\n }\n function dropTargetForConsumers(args) {\n // Guardrail: warn if the draggable element is already registered\n if (process.env.NODE_ENV !== 'production') {\n var existing = registry.get(args.element);\n if (existing) {\n // eslint-disable-next-line no-console\n console.warn(\"You have already registered a [\".concat(typeKey, \"] dropTarget on the same element\"), {\n existing: existing,\n proposed: args\n });\n }\n if (args.element instanceof HTMLIFrameElement) {\n // eslint-disable-next-line no-console\n console.warn(\"\\n We recommend not registering